@geek-fun/serverlessinsight 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +14 -0
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +14 -0
  3. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +348 -0
  4. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +14 -0
  5. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +114 -0
  6. package/.serverlessinsight/state-insight-volc-destroy-app-insight-volc-destroy.json.backup +1 -0
  7. package/README.md +26 -18
  8. package/README.zh-CN.md +19 -6
  9. package/dist/package.json +3 -1
  10. package/dist/src/commands/deploy.js +87 -4
  11. package/dist/src/commands/destroy.js +61 -10
  12. package/dist/src/commands/forceUnlock.js +8 -0
  13. package/dist/src/commands/index.js +34 -2
  14. package/dist/src/commands/login.js +195 -0
  15. package/dist/src/commands/logout.js +17 -0
  16. package/dist/src/commands/show.js +15 -7
  17. package/dist/src/commands/whoami.js +20 -0
  18. package/dist/src/common/aliyunClient/apigwOperations.js +332 -32
  19. package/dist/src/common/aliyunClient/esOperations.js +43 -29
  20. package/dist/src/common/aliyunClient/fc3Operations.js +481 -207
  21. package/dist/src/common/aliyunClient/ossOperations.js +165 -13
  22. package/dist/src/common/aliyunClient/rdsOperations.js +143 -39
  23. package/dist/src/common/aliyunClient/slsOperations.js +56 -26
  24. package/dist/src/common/aliyunClient/tablestoreOperations.js +25 -22
  25. package/dist/src/common/apiClient.js +102 -0
  26. package/dist/src/common/constants.js +9 -4
  27. package/dist/src/common/credentialStore.js +94 -0
  28. package/dist/src/common/credentials.js +2 -0
  29. package/dist/src/common/eventQueue.js +208 -0
  30. package/dist/src/common/hashUtils.js +87 -11
  31. package/dist/src/common/imsClient.js +1 -0
  32. package/dist/src/common/index.js +3 -0
  33. package/dist/src/common/lockManager.js +61 -54
  34. package/dist/src/common/logger.js +2 -0
  35. package/dist/src/common/polling.js +54 -0
  36. package/dist/src/common/reportResourceEvent.js +8 -0
  37. package/dist/src/common/runtimeMapper.js +11 -12
  38. package/dist/src/common/stateBackend/index.js +10 -1
  39. package/dist/src/common/stateBackend/localStateBackend.js +4 -1
  40. package/dist/src/common/stateBackend/remoteStateBackend.js +6 -3
  41. package/dist/src/common/stateBackend/saasStateBackend.js +266 -0
  42. package/dist/src/common/stateManager.js +135 -13
  43. package/dist/src/common/tencentClient/cosOperations.js +180 -3
  44. package/dist/src/common/tencentClient/esOperations.js +110 -46
  45. package/dist/src/common/tencentClient/index.js +22 -1
  46. package/dist/src/common/tencentClient/scfOperations.js +255 -133
  47. package/dist/src/common/tencentClient/tdsqlcClusterMapper.js +81 -0
  48. package/dist/src/common/tencentClient/tdsqlcOperations.js +93 -99
  49. package/dist/src/common/triggerMapper.js +36 -0
  50. package/dist/src/common/volcengineClient/apigwOperations.js +539 -159
  51. package/dist/src/common/volcengineClient/iamOperations.js +58 -48
  52. package/dist/src/common/volcengineClient/index.js +46 -21
  53. package/dist/src/common/volcengineClient/stsOperations.js +32 -0
  54. package/dist/src/common/volcengineClient/tlsOperations.js +229 -178
  55. package/dist/src/common/volcengineClient/tosOperations.js +78 -19
  56. package/dist/src/common/volcengineClient/vefaasOperations.js +272 -54
  57. package/dist/src/lang/en.js +84 -0
  58. package/dist/src/lang/zh-CN.js +84 -0
  59. package/dist/src/parser/eventParser.js +2 -0
  60. package/dist/src/parser/functionParser.js +96 -65
  61. package/dist/src/parser/index.js +7 -4
  62. package/dist/src/stack/aliyunStack/apigwExecutor.js +39 -1
  63. package/dist/src/stack/aliyunStack/apigwPlanner.js +14 -10
  64. package/dist/src/stack/aliyunStack/apigwResource.js +230 -125
  65. package/dist/src/stack/aliyunStack/apigwTypes.js +16 -3
  66. package/dist/src/stack/aliyunStack/databaseExecutor.js +39 -1
  67. package/dist/src/stack/aliyunStack/databasePlanner.js +13 -1
  68. package/dist/src/stack/aliyunStack/databaseResource.js +135 -40
  69. package/dist/src/stack/aliyunStack/deployer.js +2 -2
  70. package/dist/src/stack/aliyunStack/destroyer.js +2 -2
  71. package/dist/src/stack/aliyunStack/fc3Executor.js +25 -2
  72. package/dist/src/stack/aliyunStack/fc3Planner.js +11 -1
  73. package/dist/src/stack/aliyunStack/fc3Resource.js +327 -64
  74. package/dist/src/stack/aliyunStack/ossExecutor.js +39 -1
  75. package/dist/src/stack/aliyunStack/ossPlanner.js +15 -1
  76. package/dist/src/stack/aliyunStack/ossResource.js +267 -219
  77. package/dist/src/stack/aliyunStack/tablestoreExecutor.js +39 -1
  78. package/dist/src/stack/aliyunStack/tablestorePlanner.js +13 -1
  79. package/dist/src/stack/aliyunStack/tablestoreResource.js +54 -20
  80. package/dist/src/stack/alreadyExists.js +26 -0
  81. package/dist/src/stack/ownershipTag.js +40 -0
  82. package/dist/src/stack/rfsStack/index.js +3 -1
  83. package/dist/src/stack/scfStack/cosExecutor.js +39 -1
  84. package/dist/src/stack/scfStack/cosPlanner.js +11 -1
  85. package/dist/src/stack/scfStack/cosResource.js +167 -64
  86. package/dist/src/stack/scfStack/deployer.js +2 -2
  87. package/dist/src/stack/scfStack/destroyer.js +2 -2
  88. package/dist/src/stack/scfStack/esServerlessExecutor.js +39 -1
  89. package/dist/src/stack/scfStack/esServerlessPlanner.js +11 -1
  90. package/dist/src/stack/scfStack/esServerlessResource.js +88 -23
  91. package/dist/src/stack/scfStack/scfExecutor.js +39 -1
  92. package/dist/src/stack/scfStack/scfPlanner.js +12 -2
  93. package/dist/src/stack/scfStack/scfResource.js +484 -14
  94. package/dist/src/stack/scfStack/tdsqlcExecutor.js +39 -1
  95. package/dist/src/stack/scfStack/tdsqlcPlanner.js +12 -1
  96. package/dist/src/stack/scfStack/tdsqlcResource.js +95 -16
  97. package/dist/src/stack/scfStack/tdsqlcTypes.js +5 -1
  98. package/dist/src/stack/volcengineStack/apigwExecutor.js +39 -1
  99. package/dist/src/stack/volcengineStack/apigwPlanner.js +25 -53
  100. package/dist/src/stack/volcengineStack/apigwResource.js +418 -222
  101. package/dist/src/stack/volcengineStack/apigwTypes.js +76 -66
  102. package/dist/src/stack/volcengineStack/deployer.js +49 -14
  103. package/dist/src/stack/volcengineStack/destroyer.js +1 -1
  104. package/dist/src/stack/volcengineStack/index.js +1 -2
  105. package/dist/src/stack/volcengineStack/tosExecutor.js +25 -2
  106. package/dist/src/stack/volcengineStack/tosPlanner.js +11 -1
  107. package/dist/src/stack/volcengineStack/tosResource.js +82 -27
  108. package/dist/src/stack/volcengineStack/tosTypes.js +12 -0
  109. package/dist/src/stack/volcengineStack/vefaasExecutor.js +25 -2
  110. package/dist/src/stack/volcengineStack/vefaasPlanner.js +71 -2
  111. package/dist/src/stack/volcengineStack/vefaasResource.js +148 -98
  112. package/dist/src/stack/volcengineStack/vefaasTypes.js +1 -3
  113. package/dist/src/types/domains/backend.js +1 -0
  114. package/dist/src/types/domains/state.js +29 -1
  115. package/dist/src/validator/eventSchema.js +10 -0
  116. package/dist/src/validator/functionSchema.js +37 -12
  117. package/dist/src/validator/iacSchema.js +1 -0
  118. package/dist/tsconfig.tsbuildinfo +1 -1
  119. package/package.json +3 -1
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateApiKey = exports.createApiClient = void 0;
4
+ const lang_1 = require("../lang");
5
+ // Opaque JSONB payloads from the Console API — their internal keys must NOT be case-converted
6
+ const SKIP_CASE_CONVERT = new Set([
7
+ 'spec',
8
+ 'result',
9
+ 'details',
10
+ 'condition',
11
+ 'notifications',
12
+ 'stateJson',
13
+ 'state_json',
14
+ ]);
15
+ const camelize = (key) => key.replace(/_([a-z0-9])/g, (_m, c) => c.toUpperCase());
16
+ const camelizeKeys = (value) => {
17
+ if (value === null || value === undefined || typeof value !== 'object')
18
+ return value;
19
+ if (Array.isArray(value))
20
+ return value.map(camelizeKeys);
21
+ const obj = value;
22
+ const result = {};
23
+ for (const key of Object.keys(obj)) {
24
+ const camelKey = camelize(key);
25
+ result[camelKey] = SKIP_CASE_CONVERT.has(key) ? obj[key] : camelizeKeys(obj[key]);
26
+ }
27
+ return result;
28
+ };
29
+ const handleHttpError = (response) => {
30
+ const status = response.status;
31
+ if (status === 401)
32
+ throw new Error(lang_1.lang.__('API_ERROR_401'));
33
+ if (status === 403)
34
+ throw new Error(lang_1.lang.__('API_ERROR_403'));
35
+ if (status === 409) {
36
+ throw new Error(lang_1.lang.__('API_ERROR_409', { message: `HTTP Error ${status}` }));
37
+ }
38
+ throw new Error(lang_1.lang.__('API_ERROR_UNKNOWN', { status: String(status), message: `HTTP Error ${status}` }));
39
+ };
40
+ const buildRequestInit = (method, headers, body) => ({
41
+ method: method.toUpperCase(),
42
+ headers,
43
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
44
+ });
45
+ // The Console API wraps every response in { code, messages, data } and serializes
46
+ // payload keys as snake_case. Unwrap the envelope and camelCase the payload so
47
+ // callers consume camelCase data directly. Only unwrap when the `code` field is
48
+ // present — plain non-envelope payloads pass through untouched.
49
+ const unwrapResponse = (json) => {
50
+ if (json && typeof json === 'object' && 'code' in json) {
51
+ const envelope = json;
52
+ return camelizeKeys(envelope.data);
53
+ }
54
+ return json;
55
+ };
56
+ const createApiClient = (options) => {
57
+ const { apiKey, baseUrl, orgId } = options;
58
+ const headers = {
59
+ Authorization: `Bearer ${apiKey}`,
60
+ 'Content-Type': 'application/json',
61
+ };
62
+ if (orgId) {
63
+ headers['X-Org-Id'] = orgId;
64
+ }
65
+ const request = async (method, path, body) => {
66
+ let response;
67
+ try {
68
+ response = await fetch(`${baseUrl}${path}`, buildRequestInit(method, headers, body));
69
+ }
70
+ catch {
71
+ // Network-level failures (DNS, connection refused, timeout) surface as fetch rejections
72
+ throw new Error(lang_1.lang.__('CREDENTIAL_NETWORK_ERROR'));
73
+ }
74
+ if (!response.ok) {
75
+ handleHttpError(response);
76
+ }
77
+ try {
78
+ return unwrapResponse(await response.json());
79
+ }
80
+ catch {
81
+ return undefined;
82
+ }
83
+ };
84
+ return {
85
+ get: (path) => request('get', path),
86
+ post: (path, body) => request('post', path, body),
87
+ patch: (path, body) => request('patch', path, body),
88
+ delete: (path) => request('delete', path),
89
+ };
90
+ };
91
+ exports.createApiClient = createApiClient;
92
+ const validateApiKey = async (apiKey, baseUrl) => {
93
+ const client = (0, exports.createApiClient)({ apiKey, baseUrl });
94
+ const result = await client.get('/api/v1/auth/api-keys/validate');
95
+ return {
96
+ orgId: result.orgId ?? '',
97
+ orgName: result.orgName ?? '',
98
+ userEmail: result.userEmail ?? result.user?.email ?? '',
99
+ scopes: result.scopes ?? [],
100
+ };
101
+ };
102
+ exports.validateApiKey = validateApiKey;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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_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.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_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';
@@ -19,14 +19,19 @@ exports.DEFAULT_LOCK_RETRY_DELAY = 2000; // 2 seconds
19
19
  exports.STALE_LOCK_THRESHOLD = 60 * 60 * 1000; // 1 hour
20
20
  // Shared domain binding retry configuration (used by API Gateway, OSS, and future resources)
21
21
  exports.DOMAIN_BIND_MAX_RETRIES = 5;
22
- exports.DOMAIN_BIND_RETRY_DELAY_MS = 30000; // 30 seconds
22
+ exports.DOMAIN_BIND_RETRY_DELAY_MS = 30_000; // 30 seconds
23
23
  // Shared DNS propagation polling configuration (used by API Gateway, OSS, and future resources)
24
24
  exports.DNS_PROPAGATION_MAX_ATTEMPTS = 10;
25
- exports.DNS_PROPAGATION_DELAY_MS = 60000; // 1 minute
25
+ exports.DNS_PROPAGATION_DELAY_MS = 60_000; // 1 minute
26
26
  // API Gateway domain binding (aliases for shared constants)
27
27
  exports.APIGW_DOMAIN_BIND_MAX_RETRIES = exports.DOMAIN_BIND_MAX_RETRIES;
28
28
  exports.APIGW_DOMAIN_BIND_RETRY_DELAY_MS = exports.DOMAIN_BIND_RETRY_DELAY_MS;
29
29
  exports.APIGW_DNS_PUBLIC_RESOLUTION_MAX_ATTEMPTS = 10;
30
- exports.APIGW_DNS_PUBLIC_RESOLUTION_DELAY_MS = 30000; // 30 seconds
30
+ exports.APIGW_DNS_PUBLIC_RESOLUTION_DELAY_MS = 30_000; // 30 seconds
31
31
  // RAM role propagation
32
32
  exports.RAM_ROLE_PROPAGATION_DELAY_MS = 5000; // 5 seconds
33
+ // SCF function status polling (CreateFunction is async — Status is 'Creating'
34
+ // until the platform finishes provisioning; follow-up calls like CreateTrigger
35
+ // fail with "Status is Creating, unsupport operate" if issued too early)
36
+ exports.SCF_STATUS_POLL_INTERVAL_MS = 3000; // 3 seconds
37
+ exports.SCF_STATUS_POLL_MAX_ATTEMPTS = 20; // up to 60 seconds
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.validateApiKeyFormat = exports.resolveApiKey = exports.resolveConsoleUiUrl = exports.getConsoleUrl = exports.resolveConsoleUrl = exports.clearCredentials = exports.deleteCredentials = exports.saveCredentials = exports.loadCredentials = exports.getCredentialsPath = void 0;
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const node_os_1 = __importDefault(require("node:os"));
10
+ const logger_1 = require("./logger");
11
+ const lang_1 = require("../lang");
12
+ const CREDENTIALS_DIR = '.serverlessinsight';
13
+ const CREDENTIALS_FILE = 'credentials.json';
14
+ const DEFAULT_CONSOLE_URL = 'https://api.console.serverlessinsight.com';
15
+ const getCredentialsPath = () => {
16
+ return node_path_1.default.join(node_os_1.default.homedir(), CREDENTIALS_DIR, CREDENTIALS_FILE);
17
+ };
18
+ exports.getCredentialsPath = getCredentialsPath;
19
+ const ensureCredentialsDir = () => {
20
+ const dir = node_path_1.default.join(node_os_1.default.homedir(), CREDENTIALS_DIR);
21
+ if (!node_fs_1.default.existsSync(dir)) {
22
+ node_fs_1.default.mkdirSync(dir, { recursive: true });
23
+ }
24
+ };
25
+ const loadCredentials = () => {
26
+ const credPath = (0, exports.getCredentialsPath)();
27
+ if (!node_fs_1.default.existsSync(credPath)) {
28
+ return null;
29
+ }
30
+ try {
31
+ const content = node_fs_1.default.readFileSync(credPath, 'utf-8');
32
+ const parsed = JSON.parse(content);
33
+ if (!parsed.apiKey || !parsed.consoleUrl || !parsed.orgId) {
34
+ return null;
35
+ }
36
+ return parsed;
37
+ }
38
+ catch {
39
+ logger_1.logger.warn(lang_1.lang.__('CREDENTIAL_CORRUPTED'));
40
+ return null;
41
+ }
42
+ };
43
+ exports.loadCredentials = loadCredentials;
44
+ const saveCredentials = (creds) => {
45
+ ensureCredentialsDir();
46
+ const credPath = (0, exports.getCredentialsPath)();
47
+ node_fs_1.default.writeFileSync(credPath, JSON.stringify(creds, null, 2), 'utf-8');
48
+ node_fs_1.default.chmodSync(credPath, 0o600);
49
+ };
50
+ exports.saveCredentials = saveCredentials;
51
+ const deleteCredentials = () => {
52
+ const credPath = (0, exports.getCredentialsPath)();
53
+ if (node_fs_1.default.existsSync(credPath)) {
54
+ node_fs_1.default.unlinkSync(credPath);
55
+ }
56
+ };
57
+ exports.deleteCredentials = deleteCredentials;
58
+ exports.clearCredentials = exports.deleteCredentials;
59
+ const resolveConsoleUrl = (creds) => {
60
+ return process.env.SI_CONSOLE_URL || creds?.consoleUrl || DEFAULT_CONSOLE_URL;
61
+ };
62
+ exports.resolveConsoleUrl = resolveConsoleUrl;
63
+ const getConsoleUrl = () => {
64
+ return process.env.SI_CONSOLE_URL || DEFAULT_CONSOLE_URL;
65
+ };
66
+ exports.getConsoleUrl = getConsoleUrl;
67
+ /**
68
+ * Resolve the console FRONTEND (UI) URL for browser flows (e.g. /cli/authorize).
69
+ * The API URL and the UI URL differ: production uses api./console. subdomains;
70
+ * local dev runs the API on :3000 and the Vite dev server on :5173.
71
+ */
72
+ const resolveConsoleUiUrl = (creds) => {
73
+ if (process.env.SI_CONSOLE_UI_URL) {
74
+ return process.env.SI_CONSOLE_UI_URL;
75
+ }
76
+ const apiUrl = (0, exports.resolveConsoleUrl)(creds);
77
+ if (apiUrl.includes('api.')) {
78
+ return apiUrl.replace('api.', 'console.');
79
+ }
80
+ if (apiUrl.includes('localhost:3000')) {
81
+ return apiUrl.replace('localhost:3000', 'localhost:5173');
82
+ }
83
+ return apiUrl;
84
+ };
85
+ exports.resolveConsoleUiUrl = resolveConsoleUiUrl;
86
+ const resolveApiKey = (params) => {
87
+ const { siApiKey, envKey, creds } = params;
88
+ return siApiKey ?? envKey ?? creds?.apiKey ?? null;
89
+ };
90
+ exports.resolveApiKey = resolveApiKey;
91
+ const validateApiKeyFormat = (key) => {
92
+ return /^si_[A-Za-z0-9_-]{12}_[A-Za-z0-9_-]{32}$/.test(key);
93
+ };
94
+ exports.validateApiKeyFormat = validateApiKeyFormat;
@@ -14,9 +14,11 @@ const getCredentials = (config, provider) => {
14
14
  case providerEnum_1.ProviderEnum.VOLCENGINE:
15
15
  return {
16
16
  accessKeyId: config?.accessKeyId ??
17
+ process.env.VOLCENGINE_ACCESS_KEY ??
17
18
  process.env.VOLCSTACK_ACCESS_KEY_ID ??
18
19
  process.env.VOLCENGINE_ACCESS_KEY_ID,
19
20
  accessKeySecret: config?.accessKeySecret ??
21
+ process.env.VOLCENGINE_SECRET_KEY ??
20
22
  process.env.VOLCSTACK_SECRET_ACCESS_KEY ??
21
23
  process.env.VOLCENGINE_ACCESS_KEY_SECRET,
22
24
  securityToken: config?.securityToken ??
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.EventQueue = void 0;
37
+ const fs = __importStar(require("node:fs"));
38
+ const os = __importStar(require("node:os"));
39
+ const path = __importStar(require("node:path"));
40
+ const logger_1 = require("./logger");
41
+ const lang_1 = require("../lang");
42
+ const retryUtils_1 = require("./retryUtils");
43
+ const DEFAULT_QUEUE_DIR = path.join(os.homedir(), '.serverlessinsight', 'event-queue');
44
+ const DEFAULT_BATCH_SIZE = 20;
45
+ const DEFAULT_FLUSH_INTERVAL_MS = 5000;
46
+ const DEFAULT_MAX_RETRIES = 3;
47
+ const EXIT_FLUSH_TIMEOUT_MS = 3000;
48
+ class EventQueue {
49
+ deploymentId;
50
+ queueDir;
51
+ sendBatch;
52
+ batchSize;
53
+ flushIntervalMs;
54
+ baseRetryMs;
55
+ maxRetries;
56
+ pending = [];
57
+ filePath;
58
+ lastFlushAt = 0;
59
+ flushing = false;
60
+ intervalTimer = null;
61
+ constructor(options) {
62
+ this.deploymentId = options.deploymentId;
63
+ this.queueDir = options.queueDir ?? DEFAULT_QUEUE_DIR;
64
+ this.sendBatch = options.sendBatch;
65
+ this.batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
66
+ this.flushIntervalMs = options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;
67
+ this.baseRetryMs = options.baseRetryMs ?? 1000;
68
+ this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
69
+ this.filePath = path.join(this.queueDir, `${this.deploymentId}.jsonl`);
70
+ if (options.flushOnExit) {
71
+ this.installExitHandlers();
72
+ }
73
+ this.intervalTimer = setInterval(() => {
74
+ void this.maybeFlushByInterval();
75
+ }, this.flushIntervalMs);
76
+ this.intervalTimer.unref?.();
77
+ }
78
+ /** Enqueue an event — write-first to the JSONL file, then try to flush. */
79
+ report(event) {
80
+ this.appendToFile([event]);
81
+ this.pending.push(event);
82
+ if (this.pending.length >= this.batchSize) {
83
+ void this.flush();
84
+ }
85
+ }
86
+ /** Flush pending events now (bounded by backoff on failure). */
87
+ async flush() {
88
+ if (this.flushing)
89
+ return;
90
+ if (this.pending.length === 0)
91
+ return;
92
+ this.flushing = true;
93
+ const batch = this.pending.splice(0, this.pending.length);
94
+ try {
95
+ await this.sendWithRetry(batch);
96
+ this.removeFromFile(batch);
97
+ this.lastFlushAt = Date.now();
98
+ }
99
+ catch (error) {
100
+ // Send failed — restore the batch to the pending queue; it remains in
101
+ // the JSONL file and will be retried on the next flush / run.
102
+ this.pending.unshift(...batch);
103
+ logger_1.logger.warn(lang_1.lang.__('EVENT_FLUSH_FAILED', {
104
+ deploymentId: this.deploymentId,
105
+ count: String(batch.length),
106
+ error: error instanceof Error ? error.message : String(error),
107
+ }));
108
+ }
109
+ finally {
110
+ this.flushing = false;
111
+ }
112
+ }
113
+ /** Bounded final flush for process exit (SIGINT/SIGTERM / normal exit). */
114
+ async flushOnExit() {
115
+ if (this.intervalTimer) {
116
+ clearInterval(this.intervalTimer);
117
+ this.intervalTimer = null;
118
+ }
119
+ if (this.pending.length === 0)
120
+ return;
121
+ await Promise.race([this.flush(), (0, retryUtils_1.sleep)(EXIT_FLUSH_TIMEOUT_MS).then(() => undefined)]);
122
+ }
123
+ /** Replay orphaned queue files left by a previous (interrupted) run. */
124
+ async replayOrphanedQueues() {
125
+ if (!fs.existsSync(this.queueDir))
126
+ return;
127
+ const files = fs.readdirSync(this.queueDir).filter((f) => f.endsWith('.jsonl'));
128
+ for (const file of files) {
129
+ const filePath = path.join(this.queueDir, file);
130
+ const events = this.readFile(filePath);
131
+ if (events.length === 0) {
132
+ fs.rmSync(filePath, { force: true });
133
+ continue;
134
+ }
135
+ try {
136
+ await this.sendWithRetry(events);
137
+ fs.rmSync(filePath, { force: true });
138
+ }
139
+ catch (error) {
140
+ logger_1.logger.warn(lang_1.lang.__('EVENT_REPLAY_FAILED', {
141
+ file,
142
+ error: error instanceof Error ? error.message : String(error),
143
+ }));
144
+ }
145
+ }
146
+ }
147
+ get pendingCount() {
148
+ return this.pending.length;
149
+ }
150
+ async maybeFlushByInterval() {
151
+ if (this.pending.length === 0)
152
+ return;
153
+ if (Date.now() - this.lastFlushAt >= this.flushIntervalMs) {
154
+ await this.flush();
155
+ }
156
+ }
157
+ async sendWithRetry(batch) {
158
+ let attempt = 0;
159
+ for (;;) {
160
+ try {
161
+ await this.sendBatch(batch);
162
+ return;
163
+ }
164
+ catch (error) {
165
+ attempt += 1;
166
+ if (attempt >= this.maxRetries) {
167
+ throw error;
168
+ }
169
+ const delay = this.baseRetryMs * 2 ** (attempt - 1);
170
+ await (0, retryUtils_1.sleep)(Math.min(delay, 30000));
171
+ }
172
+ }
173
+ }
174
+ appendToFile(events) {
175
+ fs.mkdirSync(this.queueDir, { recursive: true });
176
+ const lines = events.map((e) => JSON.stringify(e)).join('\n') + '\n';
177
+ fs.appendFileSync(this.filePath, lines, 'utf8');
178
+ }
179
+ removeFromFile(events) {
180
+ if (!fs.existsSync(this.filePath))
181
+ return;
182
+ const sent = new Set(events.map((e) => JSON.stringify(e)));
183
+ const remaining = this.readFile(this.filePath).filter((e) => !sent.has(JSON.stringify(e)));
184
+ if (remaining.length === 0) {
185
+ fs.rmSync(this.filePath, { force: true });
186
+ }
187
+ else {
188
+ fs.writeFileSync(this.filePath, remaining.map((e) => JSON.stringify(e)).join('\n') + '\n', 'utf8');
189
+ }
190
+ }
191
+ readFile(filePath) {
192
+ if (!fs.existsSync(filePath))
193
+ return [];
194
+ const content = fs.readFileSync(filePath, 'utf8');
195
+ return content
196
+ .split('\n')
197
+ .filter((l) => l.trim().length > 0)
198
+ .map((l) => JSON.parse(l));
199
+ }
200
+ installExitHandlers() {
201
+ const onExit = () => {
202
+ void this.flushOnExit();
203
+ };
204
+ process.once('SIGINT', onExit);
205
+ process.once('SIGTERM', onExit);
206
+ }
207
+ }
208
+ exports.EventQueue = EventQueue;
@@ -1,9 +1,42 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
37
  };
5
38
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.diffAttributes = exports.attributesEqual = exports.computeDirectoryHash = exports.computeFileHash = void 0;
39
+ exports.diffAttributes = exports.attributesEqual = exports.computeDirectoryHash = exports.computeZipContentHash = exports.computeFileHash = void 0;
7
40
  const node_crypto_1 = __importDefault(require("node:crypto"));
8
41
  const node_fs_1 = __importDefault(require("node:fs"));
9
42
  const node_path_1 = __importDefault(require("node:path"));
@@ -13,6 +46,30 @@ const computeFileHash = (filePath) => {
13
46
  return node_crypto_1.default.createHash('sha256').update(fileBuffer).digest('hex');
14
47
  };
15
48
  exports.computeFileHash = computeFileHash;
49
+ /**
50
+ * Content-based hash of a ZIP archive: hashes each entry's path + bytes in
51
+ * sorted order, ignoring the archive binary itself. ZIP binaries embed file
52
+ * timestamps and ordering, so hashing the raw file yields a different value
53
+ * every time the same sources are repackaged — which makes every deploy plan
54
+ * show a phantom code update. Entry paths are sorted so archive ordering does
55
+ * not affect the result either.
56
+ */
57
+ const computeZipContentHash = async (zipPath) => {
58
+ const { default: JSZip } = await Promise.resolve().then(() => __importStar(require('jszip')));
59
+ const data = await node_fs_1.default.promises.readFile(zipPath);
60
+ const zip = await JSZip.loadAsync(data);
61
+ const entries = Object.values(zip.files)
62
+ .filter((entry) => !entry.dir)
63
+ .map((entry) => ({ path: entry.name, content: entry.async('nodebuffer') }));
64
+ entries.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
65
+ const hash = node_crypto_1.default.createHash('sha256');
66
+ for (const entry of entries) {
67
+ hash.update(entry.path);
68
+ hash.update(await entry.content);
69
+ }
70
+ return hash.digest('hex');
71
+ };
72
+ exports.computeZipContentHash = computeZipContentHash;
16
73
  /* istanbul ignore next */
17
74
  const computeDirectoryHash = (dirPath) => {
18
75
  const files = [];
@@ -47,7 +104,18 @@ exports.computeDirectoryHash = computeDirectoryHash;
47
104
  * @param b - Second value
48
105
  * @returns True if values are deeply equal, false otherwise
49
106
  */
50
- const deepEqual = (a, b) => {
107
+ const deepEqual = (a, b, options) => {
108
+ const { nullEqualsUndefined = false } = options ?? {};
109
+ // null and undefined both represent "unset" — treat them as equal when
110
+ // requested. Resource attribute comparison (plans, drift detection) relies
111
+ // on this because provider APIs return `null` for unset fields while
112
+ // desired definitions carry `undefined`.
113
+ if (nullEqualsUndefined) {
114
+ if (a === null && b === undefined)
115
+ return true;
116
+ if (a === undefined && b === null)
117
+ return true;
118
+ }
51
119
  // Handle primitives and null/undefined
52
120
  if (a === b) {
53
121
  return true;
@@ -73,7 +141,7 @@ const deepEqual = (a, b) => {
73
141
  return false;
74
142
  }
75
143
  for (let i = 0; i < objA.length; i++) {
76
- if (!deepEqual(objA[i], objB[i])) {
144
+ if (!deepEqual(objA[i], objB[i], options)) {
77
145
  return false;
78
146
  }
79
147
  }
@@ -83,9 +151,13 @@ const deepEqual = (a, b) => {
83
151
  if (Array.isArray(objA) || Array.isArray(objB)) {
84
152
  return false;
85
153
  }
86
- // Compare object keys
87
- const keysA = Object.keys(objA);
88
- const keysB = Object.keys(objB);
154
+ // Compare object keys. With nullEqualsUndefined, keys whose value is
155
+ // undefined (or null, which the option treats as equivalent) are treated as
156
+ // absent — JSON serialization drops undefined keys, so a state round-trip
157
+ // would otherwise look like a phantom added/removed.
158
+ const normalizeKey = (key, obj) => nullEqualsUndefined && (obj[key] === undefined || obj[key] === null);
159
+ const keysA = Object.keys(objA).filter((k) => !normalizeKey(k, objA));
160
+ const keysB = Object.keys(objB).filter((k) => !normalizeKey(k, objB));
89
161
  if (keysA.length !== keysB.length) {
90
162
  return false;
91
163
  }
@@ -94,7 +166,7 @@ const deepEqual = (a, b) => {
94
166
  if (!Object.prototype.hasOwnProperty.call(objB, key)) {
95
167
  return false;
96
168
  }
97
- if (!deepEqual(objA[key], objB[key])) {
169
+ if (!deepEqual(objA[key], objB[key], options)) {
98
170
  return false;
99
171
  }
100
172
  }
@@ -109,7 +181,7 @@ const deepEqual = (a, b) => {
109
181
  */
110
182
  /* istanbul ignore next */
111
183
  const attributesEqual = (a, b) => {
112
- return deepEqual(a, b);
184
+ return deepEqual(a, b, { nullEqualsUndefined: true });
113
185
  };
114
186
  exports.attributesEqual = attributesEqual;
115
187
  /**
@@ -129,14 +201,18 @@ const diffAttributes = (before, after) => {
129
201
  const beforeVal = before[key];
130
202
  const afterVal = after[key];
131
203
  if (!(key in before)) {
132
- added[key] = afterVal;
204
+ // JSON serialization drops undefined keys — a key absent on one side
205
+ // whose counterpart is undefined/null is not a real difference.
206
+ if (afterVal !== undefined && afterVal !== null)
207
+ added[key] = afterVal;
133
208
  }
134
209
  else if (!(key in after)) {
135
- removed[key] = beforeVal;
210
+ if (beforeVal !== undefined && beforeVal !== null)
211
+ removed[key] = beforeVal;
136
212
  }
137
213
  else {
138
214
  // Both exist - check if they're different using deep equality
139
- if (!deepEqual(beforeVal, afterVal)) {
215
+ if (!deepEqual(beforeVal, afterVal, { nullEqualsUndefined: true })) {
140
216
  changed[key] = { before: beforeVal, after: afterVal };
141
217
  }
142
218
  }
@@ -46,6 +46,7 @@ const getIamInfo = async (context) => {
46
46
  accessKeyId: context.accessKeyId,
47
47
  accessKeySecret: context.accessKeySecret,
48
48
  regionId: context.region,
49
+ endpoint: 'ims.aliyuncs.com',
49
50
  });
50
51
  imsConfig.connectTimeout = constants_1.ALIYUN_FC3_CONNECT_TIMEOUT_MS;
51
52
  imsConfig.readTimeout = constants_1.ALIYUN_FC3_READ_TIMEOUT_MS;
@@ -33,3 +33,6 @@ __exportStar(require("./dependencyGraph"), exports);
33
33
  __exportStar(require("./sidUtils"), exports);
34
34
  __exportStar(require("./certUtils"), exports);
35
35
  __exportStar(require("./planFormatter"), exports);
36
+ __exportStar(require("./credentialStore"), exports);
37
+ __exportStar(require("./apiClient"), exports);
38
+ __exportStar(require("./triggerMapper"), exports);