@geek-fun/serverlessinsight 0.9.0 → 0.9.2

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 (112) 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 +3 -3
  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-poc-timer-app-insight-poc-timer.json.backup +109 -0
  8. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +2 -2
  9. package/.serverlessinsight/state-insight-volc-nested-app-insight-volc-nested.json.backup +3 -3
  10. package/.serverlessinsight/state-nested-drift-app-nested-drift-service.json.backup +2 -2
  11. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +3 -3
  12. package/CHANGELOG.md +17 -0
  13. package/README.md +78 -2
  14. package/README.zh-CN.md +69 -2
  15. package/codecov +0 -0
  16. package/codecov.SHA256SUM +1 -0
  17. package/codecov.SHA256SUM.sig +16 -0
  18. package/dist/package.json +2 -2
  19. package/dist/src/commands/deploy.js +9 -3
  20. package/dist/src/commands/destroy.js +8 -2
  21. package/dist/src/commands/forceUnlock.js +5 -5
  22. package/dist/src/commands/index.js +173 -85
  23. package/dist/src/commands/login.js +12 -1
  24. package/dist/src/commands/migrate.js +287 -0
  25. package/dist/src/commands/plan.js +28 -2
  26. package/dist/src/commands/schema.js +24 -0
  27. package/dist/src/commands/show.js +99 -33
  28. package/dist/src/commands/validate.js +34 -2
  29. package/dist/src/common/aliyunClient/apigwOperations.js +4 -4
  30. package/dist/src/common/aliyunClient/ecsOperations.js +22 -13
  31. package/dist/src/common/aliyunClient/fc3Operations.js +39 -4
  32. package/dist/src/common/aliyunClient/nasOperations.js +4 -3
  33. package/dist/src/common/aliyunClient/ossOperations.js +52 -8
  34. package/dist/src/common/aliyunClient/slsOperations.js +3 -2
  35. package/dist/src/common/aliyunClient/tablestoreOperations.js +22 -11
  36. package/dist/src/common/apiClient.js +22 -5
  37. package/dist/src/common/constants.js +7 -1
  38. package/dist/src/common/context.js +5 -4
  39. package/dist/src/common/jsonOutput.js +77 -0
  40. package/dist/src/common/lockManager.js +1 -1
  41. package/dist/src/common/logger.js +6 -3
  42. package/dist/src/common/migrationMarker.js +34 -0
  43. package/dist/src/common/noColor.js +9 -0
  44. package/dist/src/common/planFormatter.js +12 -6
  45. package/dist/src/common/runtimeMapper.js +7 -3
  46. package/dist/src/common/siCron.js +415 -0
  47. package/dist/src/common/stateBackend/cosStateBackend.js +1 -1
  48. package/dist/src/common/stateBackend/index.js +5 -2
  49. package/dist/src/common/stateBackend/localStateBackend.js +8 -2
  50. package/dist/src/common/stateBackend/ossStateBackend.js +1 -1
  51. package/dist/src/common/stateBackend/remoteStateBackend.js +19 -2
  52. package/dist/src/common/stateBackend/saasStateBackend.js +88 -9
  53. package/dist/src/common/stateManager.js +56 -5
  54. package/dist/src/common/tencentClient/cosOperations.js +1 -1
  55. package/dist/src/common/tencentClient/scfOperations.js +4 -1
  56. package/dist/src/common/volcengineClient/apigwOperations.js +2 -2
  57. package/dist/src/common/volcengineClient/index.js +6 -2
  58. package/dist/src/common/volcengineClient/vefaasOperations.js +48 -3
  59. package/dist/src/lang/en.js +254 -1
  60. package/dist/src/lang/index.js +36 -1
  61. package/dist/src/lang/zh-CN.js +253 -1
  62. package/dist/src/parser/functionParser.js +47 -1
  63. package/dist/src/parser/index.js +1 -1
  64. package/dist/src/stack/aliyunStack/apigwExecutor.js +2 -2
  65. package/dist/src/stack/aliyunStack/apigwResource.js +22 -10
  66. package/dist/src/stack/aliyunStack/databaseExecutor.js +5 -5
  67. package/dist/src/stack/aliyunStack/databasePlanner.js +2 -2
  68. package/dist/src/stack/aliyunStack/databaseResource.js +18 -10
  69. package/dist/src/stack/aliyunStack/esServerlessTypes.js +2 -1
  70. package/dist/src/stack/aliyunStack/fc3Executor.js +2 -2
  71. package/dist/src/stack/aliyunStack/fc3Planner.js +26 -0
  72. package/dist/src/stack/aliyunStack/fc3Resource.js +190 -13
  73. package/dist/src/stack/aliyunStack/ossExecutor.js +2 -2
  74. package/dist/src/stack/aliyunStack/ossResource.js +5 -1
  75. package/dist/src/stack/aliyunStack/rdsTypes.js +5 -1
  76. package/dist/src/stack/aliyunStack/tablestoreExecutor.js +2 -2
  77. package/dist/src/stack/aliyunStack/tablestoreResource.js +3 -3
  78. package/dist/src/stack/aliyunStack/tablestoreTypes.js +3 -2
  79. package/dist/src/stack/deploy.js +2 -3
  80. package/dist/src/stack/localStack/event.js +2 -13
  81. package/dist/src/stack/localStack/function.js +2 -13
  82. package/dist/src/stack/localStack/functionRunner.js +5 -4
  83. package/dist/src/stack/localStack/index.js +8 -1
  84. package/dist/src/stack/localStack/timer.js +162 -0
  85. package/dist/src/stack/localStack/utils.js +19 -1
  86. package/dist/src/stack/scfStack/cosExecutor.js +2 -2
  87. package/dist/src/stack/scfStack/cosResource.js +2 -2
  88. package/dist/src/stack/scfStack/esServerlessExecutor.js +5 -5
  89. package/dist/src/stack/scfStack/esServerlessResource.js +7 -3
  90. package/dist/src/stack/scfStack/esServerlessTypes.js +2 -1
  91. package/dist/src/stack/scfStack/scfExecutor.js +2 -2
  92. package/dist/src/stack/scfStack/scfPlanner.js +52 -18
  93. package/dist/src/stack/scfStack/scfResource.js +202 -12
  94. package/dist/src/stack/scfStack/tdsqlcExecutor.js +5 -5
  95. package/dist/src/stack/scfStack/tdsqlcResource.js +7 -3
  96. package/dist/src/stack/volcengineStack/apigwExecutor.js +2 -2
  97. package/dist/src/stack/volcengineStack/apigwResource.js +7 -4
  98. package/dist/src/stack/volcengineStack/tosExecutor.js +2 -2
  99. package/dist/src/stack/volcengineStack/tosResource.js +1 -1
  100. package/dist/src/stack/volcengineStack/vefaasExecutor.js +2 -2
  101. package/dist/src/stack/volcengineStack/vefaasPlanner.js +49 -0
  102. package/dist/src/stack/volcengineStack/vefaasResource.js +221 -4
  103. package/dist/src/validator/functionSchema.js +25 -2
  104. package/dist/src/validator/iacSchema.js +2 -1
  105. package/dist/src/validator/index.js +4 -1
  106. package/dist/src/validator/rootSchema.js +77 -19
  107. package/dist/src/validator/schemaExport.js +60 -0
  108. package/dist/src/validator/semanticValidation.js +79 -0
  109. package/dist/src/validator/templateRefSchema.js +9 -1
  110. package/dist/tsconfig.tsbuildinfo +1 -1
  111. package/package.json +2 -2
  112. package/samples/aliyun-poc-timer.yml +39 -0
@@ -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;
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.createSaasStateBackend = void 0;
7
7
  const apiClient_1 = require("../apiClient");
8
8
  const credentialStore_1 = require("../credentialStore");
9
+ const logger_1 = require("../logger");
9
10
  const types_1 = require("../../types");
10
11
  const stateManager_1 = require("../stateManager");
11
12
  const eventQueue_1 = require("../eventQueue");
@@ -19,18 +20,29 @@ const getDefaultState = (provider, app, service) => ({
19
20
  stages: {},
20
21
  resources: {},
21
22
  });
22
- const createSaasStateBackend = (context) => {
23
+ const createSaasStateBackend = (context, options) => {
23
24
  const creds = (0, credentialStore_1.loadCredentials)();
24
- const apiKey = creds?.apiKey;
25
+ const apiKey = options?.apiKey || creds?.apiKey;
25
26
  const consoleUrl = (0, credentialStore_1.getConsoleUrl)();
26
- const orgId = creds?.orgId ?? '';
27
+ let knownOrgId = creds?.orgId ?? '';
27
28
  if (!apiKey) {
28
29
  throw new Error(lang_1.lang.__('SAAS_BACKEND_NO_CREDENTIALS'));
29
30
  }
31
+ // D-6 fast path: when both the yaml declaration and the stored slug are
32
+ // known, fail before touching the network at all.
33
+ if (context.declaredOrg && creds?.orgSlug && context.declaredOrg !== creds.orgSlug) {
34
+ throw new Error(lang_1.lang.__('SAAS_ORG_MISMATCH', {
35
+ declared: context.declaredOrg,
36
+ actual: creds.orgSlug,
37
+ }));
38
+ }
39
+ if (!context.declaredOrg && creds?.orgName) {
40
+ logger_1.logger.info(lang_1.lang.__('SAAS_ORG_FROM_CREDENTIALS', { orgName: creds.orgName }));
41
+ }
30
42
  const client = (0, apiClient_1.createApiClient)({
31
43
  apiKey,
32
44
  baseUrl: consoleUrl,
33
- orgId,
45
+ orgId: knownOrgId,
34
46
  });
35
47
  let currentDeploymentId = null;
36
48
  let currentStage = null;
@@ -66,11 +78,58 @@ const createSaasStateBackend = (context) => {
66
78
  flushOnExit: true,
67
79
  });
68
80
  };
81
+ /**
82
+ * D-6: resolve the API key's org identity (id + slug). Credentials written
83
+ * before the slug field existed lack it — fetch it from the validate endpoint
84
+ * once, cache it for this backend instance and heal the stored file so later
85
+ * commands check locally. Unresolvable (network / version skew) degrades to
86
+ * skipping the checks: the key still only ever writes to its own org.
87
+ */
88
+ let resolvedIdentity = null;
89
+ const resolveKeyOrgIdentity = async () => {
90
+ if (resolvedIdentity) {
91
+ return resolvedIdentity;
92
+ }
93
+ const local = {
94
+ orgId: creds?.orgId || undefined,
95
+ orgSlug: creds?.orgSlug,
96
+ };
97
+ if (local.orgId && local.orgSlug) {
98
+ resolvedIdentity = local;
99
+ return local;
100
+ }
101
+ try {
102
+ const fetched = await client.get('/api/v1/auth/api-keys/validate');
103
+ if (fetched.orgSlug && creds) {
104
+ (0, credentialStore_1.saveCredentials)({ ...creds, orgSlug: fetched.orgSlug });
105
+ }
106
+ resolvedIdentity = {
107
+ orgId: local.orgId ?? fetched.orgId,
108
+ orgSlug: local.orgSlug ?? fetched.orgSlug,
109
+ };
110
+ knownOrgId = resolvedIdentity.orgId ?? knownOrgId;
111
+ }
112
+ catch {
113
+ resolvedIdentity = local;
114
+ }
115
+ return resolvedIdentity;
116
+ };
69
117
  /**
70
118
  * Provision the deployment by calling the unified POST endpoint.
71
119
  * This resolves YAML names to Console UUIDs and caches them.
72
120
  */
73
121
  const provision = async (provider, stage) => {
122
+ // D-6: the org declaration must match the key's org BEFORE provisioning —
123
+ // this POST is what auto-creates app/service, i.e. the wrong-org write.
124
+ if (context.declaredOrg) {
125
+ const { orgSlug } = await resolveKeyOrgIdentity();
126
+ if (orgSlug && orgSlug !== context.declaredOrg) {
127
+ throw new Error(lang_1.lang.__('SAAS_ORG_MISMATCH', {
128
+ declared: context.declaredOrg,
129
+ actual: orgSlug,
130
+ }));
131
+ }
132
+ }
74
133
  const result = await client.post('/api/v1/deployments/', {
75
134
  appName: context.app,
76
135
  serviceName: context.service,
@@ -99,6 +158,20 @@ const createSaasStateBackend = (context) => {
99
158
  try {
100
159
  const state = await client.get(`/api/v1/apps/${resolvedAppId}/services/${resolvedServiceId}/state/current?stage=${encodeURIComponent(stage)}`);
101
160
  const migrated = (0, stateManager_1.migrateState)(state.stateJson);
161
+ // D-6 identity anchor: the state records the org id that owns this
162
+ // service (persisted on every SaaS save / migrate backfill). A mismatch
163
+ // with the current key's org means a wrong key — or an org deleted and
164
+ // recreated under the same slug (name matches, identity does not).
165
+ // Refuse before anything downstream reads or writes this state.
166
+ if (migrated.orgId) {
167
+ const { orgId: keyOrgId } = await resolveKeyOrgIdentity();
168
+ if (keyOrgId && migrated.orgId !== keyOrgId) {
169
+ throw new Error(lang_1.lang.__('SAAS_STATE_ORG_MISMATCH', {
170
+ stateOrgId: migrated.orgId,
171
+ keyOrgId,
172
+ }));
173
+ }
174
+ }
102
175
  // Legacy Console states hold fresh resources only in the top-level
103
176
  // field (pre-stage-syncing saves) — prefer the stage store, fall back.
104
177
  const stageResources = migrated.stages?.[stage]?.resources;
@@ -111,16 +184,22 @@ const createSaasStateBackend = (context) => {
111
184
  return {
112
185
  ...migrated,
113
186
  resources,
114
- orgId,
187
+ orgId: knownOrgId,
115
188
  appId: resolvedAppId,
116
189
  serviceId: resolvedServiceId,
117
190
  };
118
191
  }
119
- catch {
192
+ catch (error) {
193
+ // Only a genuine 404 ("no state yet for this service+stage") may start
194
+ // from an empty state. Network/5xx failures must surface — treating
195
+ // them as empty would make the next plan propose full re-creation.
196
+ if (!(error instanceof apiClient_1.ApiError && error.status === 404)) {
197
+ throw error;
198
+ }
120
199
  const defaultState = getDefaultState(provider, app, service);
121
200
  return {
122
201
  ...defaultState,
123
- orgId,
202
+ orgId: knownOrgId,
124
203
  appId: resolvedAppId,
125
204
  serviceId: resolvedServiceId,
126
205
  };
@@ -191,10 +270,10 @@ const createSaasStateBackend = (context) => {
191
270
  },
192
271
  withLock: async (operation, fn, _options, onLockAcquired) => {
193
272
  if (!currentStage) {
194
- throw new Error('SaaS state backend: call loadState() first to set stage');
273
+ throw new Error(lang_1.lang.__('SAAS_BACKEND_SET_STAGE_FIRST'));
195
274
  }
196
275
  if (!currentDeploymentId) {
197
- throw new Error('SaaS state backend: no deployment available, call loadState() first');
276
+ throw new Error(lang_1.lang.__('SAAS_BACKEND_NO_DEPLOYMENT'));
198
277
  }
199
278
  // Acquire lock via phase:start (server checks for 409 conflicts)
200
279
  await client.patch(`/api/v1/deployments/${currentDeploymentId}`, { phase: 'start' });
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getRoleArnFromState = exports.removeSharedResource = exports.setSharedResource = exports.getSharedResource = exports.getAllSharedResources = exports.getAllResources = exports.removeResource = exports.setResource = exports.getResource = exports.saveStateWithLock = exports.saveState = exports.loadState = exports.toPersistedState = exports.migrateState = exports.clearStateMigrations = exports.registerStateMigration = exports.ensureStateDir = exports.getStatePath = void 0;
6
+ exports.getRoleArnFromState = exports.removeSharedResource = exports.setSharedResource = exports.getSharedResource = exports.getAllSharedResources = exports.getAllResources = exports.removeResource = exports.setResource = exports.getResource = exports.saveStateWithLock = exports.patchPersistedState = exports.writeStateFileAtomically = exports.saveState = exports.loadState = exports.toPersistedState = exports.migrateState = exports.clearStateMigrations = exports.registerStateMigration = exports.ensureStateDir = exports.getStatePath = void 0;
7
7
  const node_fs_1 = __importDefault(require("node:fs"));
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
9
  const node_crypto_1 = __importDefault(require("node:crypto"));
@@ -147,8 +147,6 @@ exports.loadState = loadState;
147
147
  const saveState = (state, app, service, stage, baseDir = process.cwd()) => {
148
148
  (0, exports.ensureStateDir)(baseDir);
149
149
  const statePath = (0, exports.getStatePath)(app, service, baseDir);
150
- const tmpPath = `${statePath}.tmp`;
151
- const backupPath = `${statePath}.backup`;
152
150
  // Read the existing file to preserve other stages
153
151
  let existing = {
154
152
  version: types_1.CURRENT_STATE_VERSION,
@@ -184,13 +182,23 @@ const saveState = (state, app, service, stage, baseDir = process.cwd()) => {
184
182
  },
185
183
  };
186
184
  // Atomic write: back up the previous state, then write tmp + fsync + rename
185
+ (0, exports.writeStateFileAtomically)(statePath, JSON.stringify(stateToSave, null, 2));
186
+ };
187
+ exports.saveState = saveState;
188
+ /**
189
+ * Back up the previous state file, then write tmp + fsync + rename. Shared by
190
+ * saveState and patchPersistedState.
191
+ */
192
+ const writeStateFileAtomically = (statePath, content) => {
193
+ const tmpPath = `${statePath}.tmp`;
194
+ const backupPath = `${statePath}.backup`;
187
195
  try {
188
196
  if (node_fs_1.default.existsSync(statePath)) {
189
197
  node_fs_1.default.copyFileSync(statePath, backupPath);
190
198
  }
191
199
  const fd = node_fs_1.default.openSync(tmpPath, 'w');
192
200
  try {
193
- node_fs_1.default.writeFileSync(fd, JSON.stringify(stateToSave, null, 2), 'utf-8');
201
+ node_fs_1.default.writeFileSync(fd, content, 'utf-8');
194
202
  node_fs_1.default.fsyncSync(fd);
195
203
  }
196
204
  finally {
@@ -210,7 +218,50 @@ const saveState = (state, app, service, stage, baseDir = process.cwd()) => {
210
218
  throw error;
211
219
  }
212
220
  };
213
- exports.saveState = saveState;
221
+ exports.writeStateFileAtomically = writeStateFileAtomically;
222
+ /**
223
+ * Merge top-level fields into the persisted state file without touching
224
+ * stages/resources. A patch value of `undefined` deletes the key. Written as
225
+ * a new persisted version (serial+1, previous file backed up). Used by
226
+ * `si migrate` for the console-UUID backfill and the migration marker.
227
+ */
228
+ /* istanbul ignore next */
229
+ const patchPersistedState = (app, service, patch, baseDir = process.cwd()) => {
230
+ (0, exports.ensureStateDir)(baseDir);
231
+ const statePath = (0, exports.getStatePath)(app, service, baseDir);
232
+ let existing = {
233
+ version: types_1.CURRENT_STATE_VERSION,
234
+ provider: '',
235
+ app,
236
+ service,
237
+ stages: {},
238
+ };
239
+ try {
240
+ if (node_fs_1.default.existsSync(statePath)) {
241
+ const content = node_fs_1.default.readFileSync(statePath, 'utf-8');
242
+ existing = (0, exports.toPersistedState)(JSON.parse(content));
243
+ }
244
+ }
245
+ catch {
246
+ // use default
247
+ }
248
+ const patched = { ...existing };
249
+ for (const [key, value] of Object.entries(patch)) {
250
+ if (value === undefined) {
251
+ delete patched[key];
252
+ }
253
+ else {
254
+ patched[key] = value;
255
+ }
256
+ }
257
+ const stateToSave = {
258
+ ...patched,
259
+ version: types_1.CURRENT_STATE_VERSION,
260
+ serial: (existing.serial ?? 0) + 1,
261
+ };
262
+ (0, exports.writeStateFileAtomically)(statePath, JSON.stringify(stateToSave, null, 2));
263
+ };
264
+ exports.patchPersistedState = patchPersistedState;
214
265
  /**
215
266
  * Save state with automatic locking.
216
267
  * This should be used by high-level operations like deploy/destroy.
@@ -190,7 +190,7 @@ const createCosOperations = (cosClient, region, dnsOps) => {
190
190
  }
191
191
  catch (error) {
192
192
  logger_1.logger.warn(lang_1.lang.__('COS_DNS_DOMAIN_NOT_MANAGED', { domain, cname: cosEndpoint }));
193
- logger_1.logger.debug(`DNS error: ${error}`);
193
+ logger_1.logger.debug(lang_1.lang.__('DNS_OPERATION_ERROR', { error: String(error) }));
194
194
  return { domain, cname: cosEndpoint, bucketDomainBound };
195
195
  }
196
196
  };
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createScfOperations = void 0;
4
4
  const polling_1 = require("../polling");
5
5
  const constants_1 = require("../constants");
6
+ const lang_1 = require("../../lang");
6
7
  const createScfOperations = (scfClient, deps) => {
7
8
  const { tag: tagClient, cam: camClient, region, namespace } = deps;
8
9
  const getAccountUin = async () => {
@@ -13,7 +14,7 @@ const createScfOperations = (scfClient, deps) => {
13
14
  const res = await camClient.GetUserAppId(null);
14
15
  const uin = res?.OwnerUin || res?.Uin;
15
16
  if (!uin) {
16
- throw new Error('Failed to resolve Tencent Cloud account Uin for resource tagging');
17
+ throw new Error(lang_1.lang.__('SCF_RESOLVE_UIN_FAILED'));
17
18
  }
18
19
  return uin;
19
20
  };
@@ -211,6 +212,8 @@ const createScfOperations = (scfClient, deps) => {
211
212
  ...(params.TriggerDesc ? { TriggerDesc: params.TriggerDesc } : {}),
212
213
  ...(params.Qualifier ? { Qualifier: params.Qualifier } : {}),
213
214
  ...(params.Enable ? { Enable: params.Enable } : {}),
215
+ ...(params.CustomArgument !== undefined ? { CustomArgument: params.CustomArgument } : {}),
216
+ ...(params.Description ? { Description: params.Description } : {}),
214
217
  });
215
218
  },
216
219
  deleteTrigger: async (params) => {
@@ -175,7 +175,7 @@ const APIGW_POLL_MAX_ATTEMPTS = 120; // up to 20 minutes
175
175
  const reason = info.message
176
176
  ? `: ${info.message}`
177
177
  : ` (status ${info.status}) — check the Volcengine console for the gateway instance`;
178
- throw new Error(`API Gateway ${gatewayId} creation failed${reason}`);
178
+ throw new Error(lang_1.lang.__('VOLC_APIGW_CREATE_FAILED', { gatewayId, reason }));
179
179
  }
180
180
  return info;
181
181
  },
@@ -192,7 +192,7 @@ const APIGW_POLL_MAX_ATTEMPTS = 120; // up to 20 minutes
192
192
  },
193
193
  });
194
194
  if (!gateway) {
195
- throw new Error(`API Gateway ${gatewayId} disappeared while waiting for Running`);
195
+ throw new Error(lang_1.lang.__('VOLC_APIGW_DISAPPEARED', { gatewayId }));
196
196
  }
197
197
  return gateway;
198
198
  },
@@ -16,6 +16,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.createVolcengineClient = void 0;
18
18
  const openapi_1 = require("@volcengine/openapi");
19
+ const lang_1 = require("../../lang");
19
20
  const tls_1 = require("@volcengine/openapi/lib/services/tls");
20
21
  const vefaasOperations_1 = require("./vefaasOperations");
21
22
  const tosOperations_1 = require("./tosOperations");
@@ -41,8 +42,11 @@ const wrapService = (service) => {
41
42
  if (apiError?.Code) {
42
43
  const requestId = response?.ResponseMetadata?.RequestId;
43
44
  const action = params.Action || '';
44
- const error = new Error(`Volcengine ${action} failed: ${apiError.Code}: ${apiError.Message ?? ''}` +
45
- (requestId ? ` (RequestId: ${requestId})` : ''));
45
+ const error = new Error(lang_1.lang.__('VOLC_API_FAILED', {
46
+ service: action,
47
+ code: apiError.Code,
48
+ message: apiError.Message ?? '',
49
+ }) + (requestId ? lang_1.lang.__('VOLC_API_REQUEST_ID', { requestId }) : ''));
46
50
  error.code = apiError.Code;
47
51
  error.requestId = requestId;
48
52
  error.action = action;
@@ -210,7 +210,7 @@ const createVefaasOperations = (client) => {
210
210
  },
211
211
  });
212
212
  if (releaseStatus === 'failed') {
213
- throw new Error(`veFaaS function ${functionId} release failed`);
213
+ throw new Error(lang_1.lang.__('VEFAAS_RELEASE_FAILED', { functionId }));
214
214
  }
215
215
  return releaseRecordId;
216
216
  },
@@ -226,7 +226,7 @@ const createVefaasOperations = (client) => {
226
226
  }
227
227
  catch (e) {
228
228
  if (e instanceof polling_1.PollingTimeoutError) {
229
- throw new Error(`Timed out waiting for veFaaS function ${functionId} to be deleted`, {
229
+ throw new Error(lang_1.lang.__('VEFAAS_TIMEOUT_DELETED', { functionId }), {
230
230
  cause: e,
231
231
  });
232
232
  }
@@ -313,7 +313,7 @@ const createVefaasOperations = (client) => {
313
313
  const result = (response.Result || {});
314
314
  const functionId = result.Id ?? result.FunctionId;
315
315
  if (!functionId) {
316
- throw new Error(`CreateFunction did not return a function Id for ${config.functionName}`);
316
+ throw new Error(lang_1.lang.__('VEFAAS_CREATE_NO_ID', { functionName: config.functionName }));
317
317
  }
318
318
  const releaseRecordId = await operations.releaseFunction(functionId);
319
319
  logger_1.logger.info(lang_1.lang.__('FUNCTION_CREATED', { functionName: config.functionName }));
@@ -598,6 +598,51 @@ const createVefaasOperations = (client) => {
598
598
  lastModifiedTime: fn.LastUpdateTime,
599
599
  }));
600
600
  },
601
+ // veFaaS timer triggers (issue #258): CreateTrigger/ListTriggers/
602
+ // DeleteTrigger of the veFaaS OpenAPI (Version 2024-06-06). A timer
603
+ // trigger binds one function via FunctionId; the config travels as a JSON
604
+ // `Source` string with SourceType 'Timer' — unix 5-field crontab
605
+ // (translation handled in common/siCron, which rejects non-zero seconds).
606
+ createTrigger: async (params) => {
607
+ await client.fetchOpenAPI({
608
+ Action: 'CreateTrigger',
609
+ Version: '2024-06-06',
610
+ method: 'POST',
611
+ headers: { 'content-type': 'application/json' },
612
+ data: {
613
+ FunctionId: params.functionId,
614
+ Name: params.name,
615
+ SourceType: 'Timer',
616
+ Source: JSON.stringify(params.source),
617
+ },
618
+ });
619
+ },
620
+ listTriggers: async (functionId) => {
621
+ const response = await client.fetchOpenAPI({
622
+ Action: 'ListTriggers',
623
+ Version: '2024-06-06',
624
+ method: 'POST',
625
+ headers: { 'content-type': 'application/json' },
626
+ data: { FunctionId: functionId },
627
+ });
628
+ const result = (response.Result || {});
629
+ const items = (result.Triggers ?? result.Items ?? []);
630
+ return items.map((item) => ({
631
+ id: item.Id ?? item.TriggerId,
632
+ name: item.Name ?? item.TriggerName,
633
+ sourceType: item.SourceType,
634
+ source: item.Source,
635
+ }));
636
+ },
637
+ deleteTrigger: async (functionId, triggerId) => {
638
+ await client.fetchOpenAPI({
639
+ Action: 'DeleteTrigger',
640
+ Version: '2024-06-06',
641
+ method: 'POST',
642
+ headers: { 'content-type': 'application/json' },
643
+ data: { FunctionId: functionId, TriggerId: triggerId },
644
+ });
645
+ },
601
646
  };
602
647
  return operations;
603
648
  };