@geek-fun/serverlessinsight 0.8.9 → 0.9.1

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 (102) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +1 -1
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +2 -2
  3. package/.serverlessinsight/state-insight-poc-app-insight-poc-tencent.json.backup +2 -2
  4. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +123 -0
  5. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +4 -4
  6. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -1
  7. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +2 -2
  8. package/.serverlessinsight/state-insight-volc-nested-app-insight-volc-nested.json.backup +93 -0
  9. package/.serverlessinsight/state-nested-drift-app-nested-drift-service.json.backup +148 -0
  10. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +3 -3
  11. package/CHANGELOG.md +29 -0
  12. package/README.md +2 -2
  13. package/README.zh-CN.md +2 -2
  14. package/dist/package.json +2 -2
  15. package/dist/src/commands/deploy.js +12 -4
  16. package/dist/src/commands/destroy.js +8 -2
  17. package/dist/src/commands/forceUnlock.js +5 -5
  18. package/dist/src/commands/index.js +114 -53
  19. package/dist/src/commands/login.js +12 -1
  20. package/dist/src/commands/migrate.js +287 -0
  21. package/dist/src/commands/plan.js +7 -1
  22. package/dist/src/commands/show.js +37 -25
  23. package/dist/src/common/aliyunClient/apigwOperations.js +4 -4
  24. package/dist/src/common/aliyunClient/ecsOperations.js +22 -13
  25. package/dist/src/common/aliyunClient/fc3Operations.js +12 -3
  26. package/dist/src/common/aliyunClient/nasOperations.js +4 -3
  27. package/dist/src/common/aliyunClient/ossOperations.js +52 -8
  28. package/dist/src/common/aliyunClient/slsOperations.js +3 -2
  29. package/dist/src/common/aliyunClient/tablestoreOperations.js +22 -11
  30. package/dist/src/common/apiClient.js +22 -5
  31. package/dist/src/common/context.js +5 -4
  32. package/dist/src/common/lockManager.js +1 -1
  33. package/dist/src/common/migrationMarker.js +34 -0
  34. package/dist/src/common/nameBuilder.js +13 -1
  35. package/dist/src/common/planCompare.js +31 -1
  36. package/dist/src/common/planFormatter.js +69 -54
  37. package/dist/src/common/refreshPlanner.js +31 -8
  38. package/dist/src/common/runtimeMapper.js +7 -3
  39. package/dist/src/common/stateBackend/cosStateBackend.js +1 -1
  40. package/dist/src/common/stateBackend/index.js +5 -2
  41. package/dist/src/common/stateBackend/localStateBackend.js +8 -2
  42. package/dist/src/common/stateBackend/ossStateBackend.js +1 -1
  43. package/dist/src/common/stateBackend/remoteStateBackend.js +19 -2
  44. package/dist/src/common/stateBackend/saasStateBackend.js +83 -5
  45. package/dist/src/common/stateManager.js +56 -5
  46. package/dist/src/common/tencentClient/cosOperations.js +1 -1
  47. package/dist/src/common/tencentClient/scfOperations.js +2 -1
  48. package/dist/src/common/volcengineClient/apigwOperations.js +2 -2
  49. package/dist/src/common/volcengineClient/index.js +6 -2
  50. package/dist/src/common/volcengineClient/vefaasOperations.js +3 -3
  51. package/dist/src/lang/en.js +231 -7
  52. package/dist/src/lang/zh-CN.js +230 -7
  53. package/dist/src/parser/index.js +1 -1
  54. package/dist/src/stack/aliyunStack/apigwExecutor.js +2 -2
  55. package/dist/src/stack/aliyunStack/apigwPlanner.js +26 -5
  56. package/dist/src/stack/aliyunStack/apigwResource.js +22 -10
  57. package/dist/src/stack/aliyunStack/databaseExecutor.js +5 -5
  58. package/dist/src/stack/aliyunStack/databasePlanner.js +8 -3
  59. package/dist/src/stack/aliyunStack/databaseResource.js +28 -12
  60. package/dist/src/stack/aliyunStack/deployer.js +30 -13
  61. package/dist/src/stack/aliyunStack/esServerlessTypes.js +2 -1
  62. package/dist/src/stack/aliyunStack/fc3Executor.js +2 -2
  63. package/dist/src/stack/aliyunStack/fc3Planner.js +46 -25
  64. package/dist/src/stack/aliyunStack/fc3Resource.js +80 -31
  65. package/dist/src/stack/aliyunStack/ossExecutor.js +2 -2
  66. package/dist/src/stack/aliyunStack/ossPlanner.js +6 -1
  67. package/dist/src/stack/aliyunStack/ossResource.js +14 -3
  68. package/dist/src/stack/aliyunStack/rdsTypes.js +5 -1
  69. package/dist/src/stack/aliyunStack/tablestoreExecutor.js +2 -2
  70. package/dist/src/stack/aliyunStack/tablestorePlanner.js +2 -1
  71. package/dist/src/stack/aliyunStack/tablestoreResource.js +5 -4
  72. package/dist/src/stack/aliyunStack/tablestoreTypes.js +3 -2
  73. package/dist/src/stack/deploy.js +12 -7
  74. package/dist/src/stack/localStack/functionRunner.js +5 -4
  75. package/dist/src/stack/scfStack/cosExecutor.js +2 -2
  76. package/dist/src/stack/scfStack/cosPlanner.js +6 -1
  77. package/dist/src/stack/scfStack/cosResource.js +8 -4
  78. package/dist/src/stack/scfStack/deployer.js +21 -6
  79. package/dist/src/stack/scfStack/esServerlessExecutor.js +5 -5
  80. package/dist/src/stack/scfStack/esServerlessPlanner.js +6 -1
  81. package/dist/src/stack/scfStack/esServerlessResource.js +12 -4
  82. package/dist/src/stack/scfStack/esServerlessTypes.js +2 -1
  83. package/dist/src/stack/scfStack/scfExecutor.js +2 -2
  84. package/dist/src/stack/scfStack/scfPlanner.js +26 -27
  85. package/dist/src/stack/scfStack/scfResource.js +38 -13
  86. package/dist/src/stack/scfStack/tdsqlcExecutor.js +5 -5
  87. package/dist/src/stack/scfStack/tdsqlcPlanner.js +6 -1
  88. package/dist/src/stack/scfStack/tdsqlcResource.js +12 -4
  89. package/dist/src/stack/volcengineStack/apigwExecutor.js +2 -2
  90. package/dist/src/stack/volcengineStack/apigwPlanner.js +5 -1
  91. package/dist/src/stack/volcengineStack/apigwResource.js +7 -4
  92. package/dist/src/stack/volcengineStack/deployer.js +15 -4
  93. package/dist/src/stack/volcengineStack/tosExecutor.js +2 -2
  94. package/dist/src/stack/volcengineStack/tosPlanner.js +6 -1
  95. package/dist/src/stack/volcengineStack/tosResource.js +11 -4
  96. package/dist/src/stack/volcengineStack/vefaasExecutor.js +2 -2
  97. package/dist/src/stack/volcengineStack/vefaasPlanner.js +39 -11
  98. package/dist/src/stack/volcengineStack/vefaasResource.js +11 -3
  99. package/dist/src/validator/rootSchema.js +29 -2
  100. package/dist/src/validator/semanticValidation.js +24 -0
  101. package/dist/tsconfig.tsbuildinfo +1 -1
  102. package/package.json +2 -2
@@ -1,7 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateApiKey = exports.createApiClient = void 0;
3
+ exports.validateApiKey = exports.createApiClient = exports.ApiError = void 0;
4
4
  const lang_1 = require("../lang");
5
+ /**
6
+ * API error carrying the HTTP status so callers can distinguish "not found"
7
+ * (legitimate empty state on first deploy) from network/5xx failures, which
8
+ * must never be mistaken for an empty state.
9
+ */
10
+ class ApiError extends Error {
11
+ status;
12
+ constructor(message, status) {
13
+ super(message);
14
+ this.name = 'ApiError';
15
+ this.status = status;
16
+ }
17
+ }
18
+ exports.ApiError = ApiError;
5
19
  // Opaque JSONB payloads from the Console API — their internal keys must NOT be case-converted
6
20
  const SKIP_CASE_CONVERT = new Set([
7
21
  'spec',
@@ -29,13 +43,15 @@ const camelizeKeys = (value) => {
29
43
  const handleHttpError = (response) => {
30
44
  const status = response.status;
31
45
  if (status === 401)
32
- throw new Error(lang_1.lang.__('API_ERROR_401'));
46
+ throw new ApiError(lang_1.lang.__('API_ERROR_401'), 401);
33
47
  if (status === 403)
34
- throw new Error(lang_1.lang.__('API_ERROR_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);
35
51
  if (status === 409) {
36
- throw new Error(lang_1.lang.__('API_ERROR_409', { message: `HTTP Error ${status}` }));
52
+ throw new ApiError(lang_1.lang.__('API_ERROR_409', { message: `HTTP Error ${status}` }), 409);
37
53
  }
38
- throw new Error(lang_1.lang.__('API_ERROR_UNKNOWN', { status: String(status), message: `HTTP Error ${status}` }));
54
+ throw new ApiError(lang_1.lang.__('API_ERROR_UNKNOWN', { status: String(status), message: `HTTP Error ${status}` }), status);
39
55
  };
40
56
  const buildRequestInit = (method, headers, body) => ({
41
57
  method: method.toUpperCase(),
@@ -95,6 +111,7 @@ const validateApiKey = async (apiKey, baseUrl) => {
95
111
  return {
96
112
  orgId: result.orgId ?? '',
97
113
  orgName: result.orgName ?? '',
114
+ orgSlug: result.orgSlug,
98
115
  userEmail: result.userEmail ?? result.user?.email ?? '',
99
116
  scopes: result.scopes ?? [],
100
117
  };
@@ -10,6 +10,7 @@ const credentials_1 = require("./credentials");
10
10
  const imsClient_1 = require("./imsClient");
11
11
  const providerEnum_1 = require("./providerEnum");
12
12
  const refreshCache_1 = require("./refreshCache");
13
+ const lang_1 = require("../lang");
13
14
  let context;
14
15
  const DEFAULT_IAC_FILES = [
15
16
  'serverlessinsight.yml',
@@ -50,7 +51,7 @@ const getIacLocation = (location) => {
50
51
  const attemptedList = Array.from(attempted)
51
52
  .map((n) => `'${n}'`)
52
53
  .join(', ');
53
- throw new Error(`No IaC file found. Tried: ${attemptedList}`);
54
+ throw new Error(lang_1.lang.__('CONTEXT_NO_IAC_FILE', { attemptedList }));
54
55
  };
55
56
  exports.getIacLocation = getIacLocation;
56
57
  const setContext = async (config, reaValToken = false) => {
@@ -60,7 +61,7 @@ const setContext = async (config, reaValToken = false) => {
60
61
  process.env.ALIYUN_REGION ??
61
62
  'cn-hangzhou';
62
63
  if (process.env.ROS_REGION_ID && !process.env.SI_REGION) {
63
- console.warn('Warning: ROS_REGION_ID environment variable is deprecated. Please use SI_REGION instead.');
64
+ console.warn(lang_1.lang.__('CONTEXT_REGION_DEPRECATED'));
64
65
  }
65
66
  const provider = (config.provider ??
66
67
  config.iacProvider?.name ??
@@ -97,14 +98,14 @@ const setContext = async (config, reaValToken = false) => {
97
98
  exports.setContext = setContext;
98
99
  const getContext = () => {
99
100
  if (!context) {
100
- throw new Error('No context found');
101
+ throw new Error(lang_1.lang.__('CONTEXT_NOT_FOUND'));
101
102
  }
102
103
  return context;
103
104
  };
104
105
  exports.getContext = getContext;
105
106
  const setIac = (iac) => {
106
107
  if (!context) {
107
- throw new Error('Context must be set before setting IAC');
108
+ throw new Error(lang_1.lang.__('CONTEXT_IAC_REQUIRES_CONTEXT'));
108
109
  }
109
110
  context.iac = iac;
110
111
  };
@@ -229,7 +229,7 @@ const forceUnlock = (statePath, lockId) => {
229
229
  return false; // No lock to remove
230
230
  }
231
231
  if (existingLock.id !== lockId) {
232
- throw new Error(`Lock ID mismatch. Current lock ID is ${existingLock.id}, but you provided ${lockId}`);
232
+ throw new Error(lang_1.lang.__('LOCK_ID_MISMATCH', { actualId: existingLock.id, providedId: lockId }));
233
233
  }
234
234
  removeLockFile(lockPath);
235
235
  return true;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.enforceMigrationMarker = exports.isMigratedToSaas = exports.MANAGED_BY_SAAS = void 0;
4
+ const logger_1 = require("./logger");
5
+ const lang_1 = require("../lang");
6
+ /**
7
+ * Value written into the legacy state's top-level `managedBy` field once
8
+ * `si migrate` has copied the state to the Console (docs/state-migration-saas.md
9
+ * §6.3). The marker is just a new persisted version of the state — there is no
10
+ * separate tombstone mechanism.
11
+ */
12
+ exports.MANAGED_BY_SAAS = 'saas';
13
+ /** True when the state has been migrated to (and is now owned by) the Console. */
14
+ const isMigratedToSaas = (state) => {
15
+ return state?.managedBy === exports.MANAGED_BY_SAAS;
16
+ };
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
+ const enforceMigrationMarker = (state, action) => {
26
+ if (action === 'off' || !(0, exports.isMigratedToSaas)(state)) {
27
+ return;
28
+ }
29
+ if (action === 'refuse') {
30
+ throw new Error(lang_1.lang.__('MIGRATION_MARKER_REFUSED'));
31
+ }
32
+ logger_1.logger.warn(lang_1.lang.__('MIGRATION_MARKER_WARN'));
33
+ };
34
+ exports.enforceMigrationMarker = enforceMigrationMarker;
@@ -16,7 +16,7 @@
16
16
  * deploy set are additionally rejected up-front by semantic validation.
17
17
  */
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.buildRolePolicyName = exports.buildFunctionRoleName = exports.CONSTRAINT_NAME_LIMITS = exports.buildConstrainedName = exports.stableHash = exports.DEFAULT_HASH_LENGTH = void 0;
19
+ exports.buildNasAccessGroupName = exports.buildRolePolicyName = exports.buildFunctionRoleName = exports.CONSTRAINT_NAME_LIMITS = exports.buildConstrainedName = exports.stableHash = exports.DEFAULT_HASH_LENGTH = void 0;
20
20
  const FNV_OFFSET_BASIS = 0x811c9dc5;
21
21
  const FNV_PRIME = 0x01000193;
22
22
  const SANITISERS = {
@@ -89,3 +89,15 @@ exports.buildFunctionRoleName = buildFunctionRoleName;
89
89
  /** Single source of truth for the execution policy name attached to a role. */
90
90
  const buildRolePolicyName = (roleName) => `${roleName}-policy`;
91
91
  exports.buildRolePolicyName = buildRolePolicyName;
92
+ /**
93
+ * Single source of truth for function-owned NAS access-group names. The raw
94
+ * mount path is flattened (slashes folded, leading dash trimmed) so every
95
+ * derivation site — create and update/repair alike — produces the identical
96
+ * group for the same config; deriving it inline is what caused the recreated
97
+ * target to bind to a never-created group (issue #234 M4).
98
+ *
99
+ * Deliberately not routed through buildConstrainedName: existing deployments
100
+ * must keep byte-identical names (stored-first on rename).
101
+ */
102
+ const buildNasAccessGroupName = (fnName, stage, mountPath) => `${fnName}-${stage}-nas-access-${mountPath.replace(/\//g, '-').replace(/^-/, '')}`;
103
+ exports.buildNasAccessGroupName = buildNasAccessGroupName;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.jsonDocumentDiffers = exports.remoteDiffersFromDesired = void 0;
3
+ exports.computeRevertKeys = exports.mergeLiveBefore = exports.jsonDocumentDiffers = exports.remoteDiffersFromDesired = void 0;
4
4
  const hashUtils_1 = require("./hashUtils");
5
5
  /**
6
6
  * A desired value "declares" a dimension only when the executor would write it:
@@ -60,3 +60,33 @@ const jsonDocumentDiffers = (desired, cloud) => {
60
60
  }
61
61
  };
62
62
  exports.jsonDocumentDiffers = jsonDocumentDiffers;
63
+ /**
64
+ * Best-known "current live" display baseline (issue #246): the plan diff's
65
+ * `before` must always be cloud reality, not the stored intent. Live mapper
66
+ * output covers only the attributes the cloud API exposes, so stored
67
+ * definition keys the mapper never emits (codeHash, iam, ...) are carried
68
+ * over from the stored definition — live values win where readable, stored
69
+ * values fill the unreadable rest.
70
+ */
71
+ const mergeLiveBefore = (stored, live) => ({ ...stored, ...live });
72
+ exports.mergeLiveBefore = mergeLiveBefore;
73
+ /**
74
+ * Field-level drift signature (issue #246): top-level keys where the stored
75
+ * definition already matches the desired one while the live value does not —
76
+ * i.e. the difference on that key is entirely a cloud-side edit the config
77
+ * never asked for. All three sides should be passed through the same
78
+ * normalization the display uses, so keys line up with the rendered diff.
79
+ */
80
+ const computeRevertKeys = (stored, live, desired) => {
81
+ // Only keys the live read actually carries can claim a cloud-side edit —
82
+ // a desired-declared key the mapper never emits (codeHash, iam, ...) is an
83
+ // unreadable dimension, not a revert.
84
+ return Object.keys(live)
85
+ .filter((key) => {
86
+ const storedMatchesDesired = (0, hashUtils_1.attributesEqual)({ [key]: stored[key] }, { [key]: desired[key] });
87
+ const liveMatchesDesired = (0, hashUtils_1.attributesEqual)({ [key]: live[key] }, { [key]: desired[key] });
88
+ return storedMatchesDesired && !liveMatchesDesired;
89
+ })
90
+ .sort((a, b) => a.localeCompare(b));
91
+ };
92
+ exports.computeRevertKeys = computeRevertKeys;
@@ -28,8 +28,6 @@ const DEFAULT_CONFIG = {
28
28
  colorize: true,
29
29
  indentSize: 4,
30
30
  keyAlignWidth: 12,
31
- showUnchangedAttributes: false,
32
- maxUnchangedHidden: 5,
33
31
  };
34
32
  const isObject = (val) => typeof val === 'object' && val !== null && !Array.isArray(val);
35
33
  const isSimpleObject = (val) => {
@@ -142,9 +140,17 @@ const computeMaxKeyWidth = (diffs, baseIndent) => diffs.reduce((maxWidth, diff)
142
140
  : 0;
143
141
  return Math.max(maxWidth, keyWidth, childWidth);
144
142
  }, 0);
145
- const formatAttributeLines = (diff, indent, config, keyWidth) => {
143
+ const formatAttributeLines = (diff, indent, config, keyWidth, revertKeys) => {
146
144
  const spaces = ' '.repeat(indent);
147
145
  const alignedKey = (diff.key + ':').padEnd(keyWidth);
146
+ // Issue #246: a field whose stored value already matched the config while
147
+ // the cloud diverged is annotated at the line level — the resource block
148
+ // stays in place, only this line explains why it appears. Only leaf lines
149
+ // reach suffix (parent cases early-return on children), so a revert key
150
+ // with nested children never carries the annotation.
151
+ const suffix = (line) => revertKeys?.has(diff.key)
152
+ ? `${line} ${colorize(lang_1.lang.__('PLAN_REVERT_ANNOTATION'), 'CYAN', config.colorize)}`
153
+ : line;
148
154
  switch (diff.action) {
149
155
  case 'add': {
150
156
  if (diff.children && diff.children.length > 0) {
@@ -157,7 +163,7 @@ const formatAttributeLines = (diff, indent, config, keyWidth) => {
157
163
  const value = diff.isComputed
158
164
  ? colorize(lang_1.lang.__('PLAN_COMPUTED_VALUE'), 'CYAN', config.colorize)
159
165
  : formatValue(diff.after);
160
- return [colorize(`${spaces}${alignedKey} ${value}`, 'GREEN', config.colorize)];
166
+ return [suffix(colorize(`${spaces}${alignedKey} ${value}`, 'GREEN', config.colorize))];
161
167
  }
162
168
  case 'remove': {
163
169
  if (diff.children && diff.children.length > 0) {
@@ -168,7 +174,7 @@ const formatAttributeLines = (diff, indent, config, keyWidth) => {
168
174
  ];
169
175
  }
170
176
  return [
171
- colorize(`${spaces}${alignedKey} ${formatValue(diff.before)}`, 'RED', config.colorize),
177
+ suffix(colorize(`${spaces}${alignedKey} ${formatValue(diff.before)}`, 'RED', config.colorize)),
172
178
  ];
173
179
  }
174
180
  case 'change': {
@@ -182,7 +188,7 @@ const formatAttributeLines = (diff, indent, config, keyWidth) => {
182
188
  const beforeStr = formatValue(diff.before);
183
189
  const afterStr = formatValue(diff.after);
184
190
  return [
185
- colorize(`${spaces}${alignedKey} ${beforeStr} -> ${afterStr}`, 'YELLOW', config.colorize),
191
+ suffix(colorize(`${spaces}${alignedKey} ${beforeStr} -> ${afterStr}`, 'YELLOW', config.colorize)),
186
192
  ];
187
193
  }
188
194
  }
@@ -192,49 +198,68 @@ const ACTION_DESC = {
192
198
  update: 'PLAN_WILL_UPDATE',
193
199
  delete: 'PLAN_WILL_DESTROY',
194
200
  noop: 'PLAN_NO_CHANGES',
195
- refresh: 'PLAN_WILL_REFRESH',
196
201
  };
197
202
  const ACTION_SYMBOL = {
198
203
  create: '+',
199
204
  update: '~',
200
205
  delete: '-',
201
- refresh: '↻',
202
206
  };
203
207
  const ACTION_COLOR = {
204
208
  create: 'GREEN',
205
209
  update: 'YELLOW',
206
210
  delete: 'RED',
207
- refresh: 'CYAN',
208
211
  };
212
+ /**
213
+ * A create plan for a resource that also has a recorded `before` is a
214
+ * recreation (the cloud copy disappeared or was tainted) — rendered as a
215
+ * single `-/+` block showing the old→new fields, never as two separate
216
+ * add/remove blocks (issue #246 resource-paradigm invariant).
217
+ */
218
+ const isRecreate = (item) => item.action === 'create' && !!item.changes?.before;
209
219
  /* istanbul ignore next */
210
220
  const formatPlanItem = (item, config = DEFAULT_CONFIG) => {
211
- const descKey = ACTION_DESC[item.action] ?? 'PLAN_NO_CHANGES';
212
- const headerLine = ` # ${item.logicalId} ${lang_1.lang.__(descKey)}`;
213
221
  if (item.action === 'noop') {
214
- return headerLine;
222
+ // Unchanged resources are not rendered as blocks — they only surface in
223
+ // the plan summary count (issue #246 display spec).
224
+ return '';
215
225
  }
216
- const symbol = ACTION_SYMBOL[item.action] ?? ' ';
217
- const symbolColor = ACTION_COLOR[item.action] ?? 'RESET';
226
+ const recreate = isRecreate(item);
227
+ const descKey = recreate ? 'PLAN_WILL_RECREATE' : (ACTION_DESC[item.action] ?? 'PLAN_NO_CHANGES');
228
+ const headerLine = ` # ${item.logicalId} ${lang_1.lang.__(descKey)}`;
229
+ const symbol = recreate ? '-/+' : (ACTION_SYMBOL[item.action] ?? ' ');
230
+ const symbolColor = recreate ? 'YELLOW' : (ACTION_COLOR[item.action] ?? 'RESET');
218
231
  const resourceLine = colorize(` ${symbol} ${item.logicalId}:`, symbolColor, config.colorize);
219
- // A drifted update is caused by an out-of-config cloud edit — surface that
220
- // so it doesn't read like an ordinary config change.
221
- const driftedLine = item.drifted && item.action !== 'delete'
222
- ? [colorize(` # ${lang_1.lang.__('PLAN_DRIFTED_MARKER')}`, 'CYAN', config.colorize)]
223
- : [];
232
+ // Probe-level drift (role policy, logstore, ...) has no attribute-level
233
+ // diff to show — each reason becomes its own explanatory line.
234
+ const reasonLines = (item.driftReasons ?? []).map((reason) => colorize(` # ${lang_1.lang.__(reason)}`, 'CYAN', config.colorize));
224
235
  if (!item.changes) {
225
- return [headerLine, resourceLine, ...driftedLine].join('\n');
236
+ // No changes payload at all: the drift marker is the only explanation
237
+ // available (fallback — planners normally attach changes or reasons).
238
+ const driftedLine = item.drifted && reasonLines.length === 0
239
+ ? [colorize(` # ${lang_1.lang.__('PLAN_DRIFTED_MARKER')}`, 'CYAN', config.colorize)]
240
+ : [];
241
+ return [headerLine, resourceLine, ...reasonLines, ...driftedLine].join('\n');
226
242
  }
227
243
  const { diffs, unchangedCount } = (0, exports.computeAttributeDiffs)(item.changes.before, item.changes.after);
228
244
  const keyWidth = Math.max(config.keyAlignWidth, computeMaxKeyWidth(diffs, config.indentSize));
245
+ const revertKeys = new Set(item.revertKeys ?? []);
229
246
  const attrLines = diffs.length > 0
230
- ? diffs.flatMap((diff) => formatAttributeLines(diff, config.indentSize, config, keyWidth))
247
+ ? diffs.flatMap((diff) => formatAttributeLines(diff, config.indentSize, config, keyWidth, revertKeys))
231
248
  : [];
232
- const hiddenLine = unchangedCount > 0 && !config.showUnchangedAttributes
249
+ const hiddenLine = unchangedCount > 0
233
250
  ? [
234
251
  colorize(` # ${lang_1.lang.__('PLAN_UNCHANGED_ATTRS', { count: String(unchangedCount) })}`, 'DIM', config.colorize),
235
252
  ]
236
253
  : [];
237
- return [headerLine, resourceLine, ...driftedLine, ...attrLines, ...hiddenLine].join('\n');
254
+ // Invariant backstop (issue #246): a drifted item must always explain
255
+ // itself — attribute lines, reasons, or as a last resort the generic
256
+ // marker. Planners attach at least one of these for every drifted item.
257
+ const driftedFallback = item.drifted && attrLines.length === 0 && reasonLines.length === 0
258
+ ? [colorize(` # ${lang_1.lang.__('PLAN_DRIFTED_MARKER')}`, 'CYAN', config.colorize)]
259
+ : [];
260
+ return [headerLine, resourceLine, ...reasonLines, ...attrLines, ...hiddenLine, ...driftedFallback]
261
+ .filter((line) => line.length > 0)
262
+ .join('\n');
238
263
  };
239
264
  exports.formatPlanItem = formatPlanItem;
240
265
  /* istanbul ignore next */
@@ -242,39 +267,29 @@ const formatPlan = (items, config = DEFAULT_CONFIG) => {
242
267
  if (items.length === 0) {
243
268
  return lang_1.lang.__('NO_CHANGES_INFRASTRUCTURE_UP_TO_DATE');
244
269
  }
245
- const createItems = items.filter((i) => i.action === 'create');
246
- const updateItems = items.filter((i) => i.action === 'update');
247
- const deleteItems = items.filter((i) => i.action === 'delete');
248
- const refreshItems = items.filter((i) => i.action === 'refresh');
249
- const noopItems = items.filter((i) => i.action === 'noop');
250
- const actionItems = [
251
- ...createItems,
252
- ...updateItems,
253
- ...deleteItems,
254
- ...refreshItems,
255
- ...noopItems,
256
- ];
257
- const header = [
258
- `${lang_1.lang.__('PLAN_HEADER')}\n`,
259
- colorize(lang_1.lang.__('PLAN_LEGEND_CREATE'), 'GREEN', config.colorize),
260
- colorize(lang_1.lang.__('PLAN_LEGEND_UPDATE'), 'YELLOW', config.colorize),
261
- colorize(lang_1.lang.__('PLAN_LEGEND_DESTROY'), 'RED', config.colorize),
262
- '',
263
- ];
264
- const itemLines = actionItems.flatMap((item) => [(0, exports.formatPlanItem)(item, config), '']);
265
- const driftedCount = items.filter((i) => i.drifted && i.action !== 'delete').length;
266
- const driftedSummary = driftedCount > 0
267
- ? [
268
- colorize(lang_1.lang.__('PLAN_DRIFTED_SUMMARY', { driftedCount: String(driftedCount) }), 'CYAN', config.colorize),
269
- '',
270
- ]
271
- : [];
270
+ // Resource paradigm (issue #246): render blocks in the planner's domain
271
+ // order, one block per resource, never regrouped by action. Unchanged
272
+ // resources only surface in the summary count.
273
+ const unchangedCount = items.filter((i) => i.action === 'noop').length;
274
+ const itemLines = items
275
+ .filter((i) => i.action !== 'noop')
276
+ .flatMap((item) => {
277
+ const block = (0, exports.formatPlanItem)(item, config);
278
+ return block ? [block, ''] : [];
279
+ });
280
+ const recreateCount = items.filter(isRecreate).length;
281
+ const addCount = items.filter((i) => i.action === 'create' && !isRecreate(i)).length;
282
+ const modifyCount = items.filter((i) => i.action === 'update').length;
283
+ const removeCount = items.filter((i) => i.action === 'delete').length;
284
+ const header = [`${lang_1.lang.__('PLAN_HEADER')}\n`];
272
285
  const summary = lang_1.lang.__('PLAN_SUMMARY', {
273
- createCount: String(createItems.length),
274
- updateCount: String(updateItems.length),
275
- deleteCount: String(deleteItems.length),
286
+ addCount: String(addCount),
287
+ modifyCount: String(modifyCount),
288
+ removeCount: String(removeCount),
289
+ recreateCount: String(recreateCount),
290
+ unchangedCount: String(unchangedCount),
276
291
  });
277
- return [...header, ...itemLines, ...driftedSummary, summary].join('\n');
292
+ return [...header, ...itemLines, summary].join('\n');
278
293
  };
279
294
  exports.formatPlan = formatPlan;
280
295
  /* istanbul ignore next */
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.planRefreshedResource = exports.decideRefreshedExistsAction = void 0;
4
4
  const hashUtils_1 = require("./hashUtils");
5
5
  const planCompare_1 = require("./planCompare");
6
+ const logger_1 = require("./logger");
7
+ const lang_1 = require("../lang");
6
8
  const decideRefreshedExistsAction = async (args) => {
7
9
  const remote = await args.read();
8
10
  if (!remote) {
@@ -14,11 +16,16 @@ const decideRefreshedExistsAction = async (args) => {
14
16
  }
15
17
  const remoteDiffers = (0, planCompare_1.remoteDiffersFromDesired)(attributes, args.desiredDefinition);
16
18
  if (args.definitionChanged || remoteDiffers) {
17
- return { action: 'update', drifted: true };
19
+ return { action: 'update', drifted: true, liveAttributes: attributes };
18
20
  }
19
21
  const extra = await args.extraUpdate?.();
20
22
  if (extra?.update) {
21
- return { action: 'update', drifted: extra.drifted };
23
+ return {
24
+ action: 'update',
25
+ drifted: extra.drifted,
26
+ liveAttributes: attributes,
27
+ ...(extra.reason ? { driftReasons: [extra.reason] } : {}),
28
+ };
22
29
  }
23
30
  return { action: 'noop' };
24
31
  };
@@ -28,8 +35,12 @@ exports.decideRefreshedExistsAction = decideRefreshedExistsAction;
28
35
  * no-state-probe / exists-refresh decision chain of the simple planners
29
36
  * (buckets, tables, databases). Function and gateway planners keep their
30
37
  * custom flows (role probes, trigger reconciliation, config normalization).
31
- * Read failures on the exists path degrade to a create plan — the pre-existing
32
- * planner behavior, preserved verbatim.
38
+ *
39
+ * Issue #246 display contract: a drift/intent update's `changes.before` is
40
+ * always cloud reality — live attributes merged over the stored definition
41
+ * (stored fills the keys the cloud mapper never emits) — so every update
42
+ * renders a complete live→desired field diff, and `revertKeys` marks the
43
+ * fields whose difference is purely an out-of-config cloud edit.
33
44
  */
34
45
  const planRefreshedResource = async (args) => {
35
46
  const { logicalId, resourceType, currentState, desiredDefinition } = args;
@@ -81,24 +92,36 @@ const planRefreshedResource = async (args) => {
81
92
  logicalId,
82
93
  action: 'create',
83
94
  resourceType,
84
- changes: { before: normalize(currentDefinition), after: desiredDefinition },
95
+ changes: { before: normalizedCurrent, after: desiredDefinition },
85
96
  drifted: true,
86
97
  };
87
98
  }
99
+ const normalizedLive = normalize(decision.liveAttributes);
100
+ const revertKeys = (0, planCompare_1.computeRevertKeys)(normalizedCurrent, normalizedLive, normalizedDesired);
88
101
  return {
89
102
  logicalId,
90
103
  action: 'update',
91
104
  resourceType,
92
- changes: { before: normalizedCurrent, after: normalizedDesired },
105
+ changes: {
106
+ before: normalize((0, planCompare_1.mergeLiveBefore)(currentDefinition, normalizedLive)),
107
+ after: normalizedDesired,
108
+ },
93
109
  ...(decision.drifted ? { drifted: true } : {}),
110
+ ...(revertKeys.length ? { revertKeys } : {}),
111
+ ...(decision.driftReasons?.length ? { driftReasons: decision.driftReasons } : {}),
94
112
  };
95
113
  }
96
- catch {
114
+ catch (error) {
115
+ logger_1.logger.warn(lang_1.lang.__('PLAN_LIVE_READ_FAILED', {
116
+ logicalId,
117
+ error: error instanceof Error ? error.message : String(error),
118
+ }));
97
119
  return {
98
120
  logicalId,
99
121
  action: 'create',
100
122
  resourceType,
101
- changes: { before: normalize(currentDefinition), after: desiredDefinition },
123
+ changes: { before: normalizedCurrent, after: normalizedDesired },
124
+ drifted: true,
102
125
  };
103
126
  }
104
127
  };
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getSupportedRuntimes = exports.isRuntimeSupported = exports.mapRuntime = exports.StandardRuntime = void 0;
4
4
  const providerEnum_1 = require("./providerEnum");
5
+ const lang_1 = require("../lang");
5
6
  var StandardRuntime;
6
7
  (function (StandardRuntime) {
7
8
  StandardRuntime["NODEJS24"] = "nodejs24";
@@ -151,12 +152,15 @@ const runtimeMappings = {
151
152
  const mapRuntime = (standardRuntime, provider) => {
152
153
  const mapping = runtimeMappings[standardRuntime];
153
154
  if (!mapping) {
154
- throw new Error(`Unsupported standard runtime: ${standardRuntime}`);
155
+ throw new Error(lang_1.lang.__('RUNTIME_UNSUPPORTED_STANDARD', { standardRuntime }));
155
156
  }
156
157
  const providerRuntime = mapping[provider];
157
158
  if (!providerRuntime) {
158
- throw new Error(`Runtime ${standardRuntime} is not supported for provider ${provider}. ` +
159
- `Supported providers for this runtime: ${Object.keys(mapping).join(', ')}`);
159
+ throw new Error(lang_1.lang.__('RUNTIME_NOT_SUPPORTED_FOR_PROVIDER', {
160
+ runtime: standardRuntime,
161
+ provider,
162
+ supportedProviders: Object.keys(mapping).join(', '),
163
+ }));
160
164
  }
161
165
  return providerRuntime;
162
166
  };
@@ -69,6 +69,6 @@ const createCosStorageAdapter = (config) => {
69
69
  };
70
70
  const createCosStateBackend = (config) => {
71
71
  const adapter = createCosStorageAdapter(config);
72
- return (0, remoteStateBackend_1.createRemoteStateBackend)(adapter, { key: config.key });
72
+ return (0, remoteStateBackend_1.createRemoteStateBackend)(adapter, { key: config.key, markerAction: config.markerAction });
73
73
  };
74
74
  exports.createCosStateBackend = createCosStateBackend;
@@ -34,10 +34,11 @@ const createStateBackend = (backendConfig, context) => {
34
34
  return (0, saasStateBackend_1.createSaasStateBackend)({
35
35
  app: context.app,
36
36
  service: context.service,
37
- });
37
+ declaredOrg: context.declaredOrg,
38
+ }, { apiKey: context.siApiKey });
38
39
  }
39
40
  if (backendConfig.type === types_1.StateBackendType.LOCAL) {
40
- return (0, localStateBackend_1.createLocalStateBackend)(context.app, context.service, context.baseDir);
41
+ return (0, localStateBackend_1.createLocalStateBackend)(context.app, context.service, context.baseDir, context.migrationMarker);
41
42
  }
42
43
  const bucketConfig = backendConfig;
43
44
  const region = context.region;
@@ -52,6 +53,7 @@ const createStateBackend = (backendConfig, context) => {
52
53
  accessKeyId,
53
54
  accessKeySecret,
54
55
  securityToken,
56
+ markerAction: context.migrationMarker,
55
57
  });
56
58
  }
57
59
  return (0, ossStateBackend_1.createOssStateBackend)({
@@ -61,6 +63,7 @@ const createStateBackend = (backendConfig, context) => {
61
63
  accessKeyId,
62
64
  accessKeySecret,
63
65
  securityToken,
66
+ markerAction: context.migrationMarker,
64
67
  });
65
68
  };
66
69
  exports.createStateBackend = createStateBackend;
@@ -2,16 +2,22 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createLocalStateBackend = void 0;
4
4
  const stateManager_1 = require("../stateManager");
5
+ const migrationMarker_1 = require("../migrationMarker");
5
6
  const lockManager_1 = require("../lockManager");
6
- const createLocalStateBackend = (app, service, baseDir = process.cwd()) => {
7
+ const createLocalStateBackend = (app, service, baseDir = process.cwd(), markerAction = 'off') => {
7
8
  const statePath = (0, stateManager_1.getStatePath)(app, service, baseDir);
8
9
  return {
9
10
  loadState: async (provider, loadApp, loadService, stage) => {
10
- return (0, stateManager_1.loadState)(provider, loadApp, loadService, stage, baseDir);
11
+ const state = (0, stateManager_1.loadState)(provider, loadApp, loadService, stage, baseDir);
12
+ (0, migrationMarker_1.enforceMigrationMarker)(state, markerAction);
13
+ return state;
11
14
  },
12
15
  saveState: async (state, saveApp, saveService, stage) => {
13
16
  (0, stateManager_1.saveState)(state, saveApp, saveService, stage, baseDir);
14
17
  },
18
+ patchPersisted: async (patch) => {
19
+ (0, stateManager_1.patchPersistedState)(app, service, patch, baseDir);
20
+ },
15
21
  acquireLock: async (operation, options) => {
16
22
  const lockMeta = await (0, lockManager_1.acquireLockInternal)(statePath, operation, options);
17
23
  return lockMeta.id;
@@ -51,6 +51,6 @@ const createOssStorageAdapter = (config) => {
51
51
  };
52
52
  const createOssStateBackend = (config) => {
53
53
  const adapter = createOssStorageAdapter(config);
54
- return (0, remoteStateBackend_1.createRemoteStateBackend)(adapter, { key: config.key });
54
+ return (0, remoteStateBackend_1.createRemoteStateBackend)(adapter, { key: config.key, markerAction: config.markerAction });
55
55
  };
56
56
  exports.createOssStateBackend = createOssStateBackend;
@@ -7,6 +7,7 @@ exports.createRemoteStateBackend = void 0;
7
7
  const node_os_1 = __importDefault(require("node:os"));
8
8
  const types_1 = require("../../types");
9
9
  const stateManager_1 = require("../stateManager");
10
+ const migrationMarker_1 = require("../migrationMarker");
10
11
  const constants_1 = require("../constants");
11
12
  const lockManager_1 = require("../lockManager");
12
13
  const logger_1 = require("../logger");
@@ -14,6 +15,7 @@ const lang_1 = require("../../lang");
14
15
  const lockUtils_1 = require("./lockUtils");
15
16
  const createRemoteStateBackend = (adapter, config) => {
16
17
  const lockKey = `${config.key}${lockUtils_1.LOCK_KEY_SUFFIX}`;
18
+ const markerAction = config.markerAction ?? 'off';
17
19
  const readLockObject = async () => {
18
20
  return adapter.read(lockKey);
19
21
  };
@@ -73,10 +75,25 @@ const createRemoteStateBackend = (adapter, config) => {
73
75
  if (state) {
74
76
  const migrated = (0, stateManager_1.migrateState)(state);
75
77
  const stageResources = migrated.stages?.[stage]?.resources ?? {};
76
- return { ...migrated, resources: stageResources };
78
+ const loaded = { ...migrated, resources: stageResources };
79
+ (0, migrationMarker_1.enforceMigrationMarker)(loaded, markerAction);
80
+ return loaded;
77
81
  }
78
82
  return { version: types_1.CURRENT_STATE_VERSION, provider, app, service, stages: {}, resources: {} };
79
83
  },
84
+ patchPersisted: async (patch) => {
85
+ const raw = await adapter.read(config.key);
86
+ const merged = raw ? { ...(0, stateManager_1.toPersistedState)(raw) } : {};
87
+ for (const [key, value] of Object.entries(patch)) {
88
+ if (value === undefined) {
89
+ delete merged[key];
90
+ }
91
+ else {
92
+ merged[key] = value;
93
+ }
94
+ }
95
+ await adapter.write(config.key, merged);
96
+ },
80
97
  saveState: async (state, app, service, stage) => {
81
98
  let existing = {
82
99
  version: types_1.CURRENT_STATE_VERSION,
@@ -124,7 +141,7 @@ const createRemoteStateBackend = (adapter, config) => {
124
141
  if (!existing)
125
142
  return false;
126
143
  if (existing.id !== lockId) {
127
- throw new Error(`Lock ID mismatch. Current lock ID is ${existing.id}, but you provided ${lockId}`);
144
+ throw new Error(lang_1.lang.__('LOCK_ID_MISMATCH', { actualId: existing.id, providedId: lockId }));
128
145
  }
129
146
  await adapter.delete(lockKey);
130
147
  return true;