@geek-fun/serverlessinsight 0.9.3 → 0.9.5

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 (82) hide show
  1. package/AGENTS.md +5 -2
  2. package/CHANGELOG.md +56 -0
  3. package/README.md +266 -179
  4. package/README.zh-CN.md +264 -147
  5. package/codecov +0 -0
  6. package/codecov.SHA256SUM +1 -1
  7. package/codecov.SHA256SUM.sig +13 -13
  8. package/dist/package.json +22 -19
  9. package/dist/src/commands/deploy.js +7 -2
  10. package/dist/src/commands/destroy.js +6 -3
  11. package/dist/src/commands/forceUnlock.js +16 -21
  12. package/dist/src/commands/index.js +26 -63
  13. package/dist/src/commands/migrate.js +105 -132
  14. package/dist/src/commands/plan.js +27 -3
  15. package/dist/src/commands/show.js +17 -6
  16. package/dist/src/common/aggregateState.js +185 -0
  17. package/dist/src/common/aggregateStore.js +247 -0
  18. package/dist/src/common/aliyunClient/apigwOperations.js +32 -9
  19. package/dist/src/common/apiClient.js +35 -12
  20. package/dist/src/common/constants.js +2 -1
  21. package/dist/src/common/context.js +22 -15
  22. package/dist/src/common/effectiveConfig.js +48 -0
  23. package/dist/src/common/index.js +5 -0
  24. package/dist/src/common/jsonOutput.js +2 -13
  25. package/dist/src/common/migrationMarker.js +0 -7
  26. package/dist/src/common/nameBuilder.js +2 -3
  27. package/dist/src/common/regionalMigration.js +261 -0
  28. package/dist/src/common/saasProtocol.js +41 -0
  29. package/dist/src/common/stateBackend/cosStateBackend.js +88 -8
  30. package/dist/src/common/stateBackend/index.js +42 -18
  31. package/dist/src/common/stateBackend/localStateBackend.js +61 -26
  32. package/dist/src/common/stateBackend/ossStateBackend.js +62 -9
  33. package/dist/src/common/stateBackend/remoteStateBackend.js +94 -94
  34. package/dist/src/common/stateBackend/saasStateBackend.js +327 -92
  35. package/dist/src/common/stateBackend/types.js +9 -0
  36. package/dist/src/common/stateManager.js +38 -11
  37. package/dist/src/common/stateScope.js +34 -0
  38. package/dist/src/common/stateStorageIO.js +31 -0
  39. package/dist/src/lang/en.js +48 -6
  40. package/dist/src/lang/index.js +28 -14
  41. package/dist/src/lang/zh-CN.js +48 -6
  42. package/dist/src/parser/index.js +25 -4
  43. package/dist/src/stack/aliyunStack/apigwDomainPlan.js +82 -0
  44. package/dist/src/stack/aliyunStack/apigwExecutor.js +4 -1
  45. package/dist/src/stack/aliyunStack/apigwPlanner.js +115 -55
  46. package/dist/src/stack/aliyunStack/apigwResource.js +169 -124
  47. package/dist/src/stack/aliyunStack/deployer.js +5 -5
  48. package/dist/src/stack/aliyunStack/destroyer.js +5 -5
  49. package/dist/src/stack/aliyunStack/fc3Planner.js +1 -1
  50. package/dist/src/stack/aliyunStack/fc3Resource.js +2 -2
  51. package/dist/src/stack/aliyunStack/planner.js +1 -1
  52. package/dist/src/stack/aliyunStack/sharedLogProject.js +2 -2
  53. package/dist/src/stack/ownershipTag.js +34 -26
  54. package/dist/src/stack/scfStack/deployer.js +5 -5
  55. package/dist/src/stack/scfStack/destroyer.js +5 -6
  56. package/dist/src/stack/scfStack/planner.js +1 -1
  57. package/dist/src/stack/scfStack/scfResource.js +1 -1
  58. package/dist/src/stack/scfStack/sharedLogset.js +5 -2
  59. package/dist/src/stack/volcengineStack/deployer.js +3 -3
  60. package/dist/src/stack/volcengineStack/destroyer.js +2 -3
  61. package/dist/src/stack/volcengineStack/planner.js +1 -1
  62. package/dist/src/stack/volcengineStack/sharedLogProject.js +4 -4
  63. package/dist/src/stack/volcengineStack/vefaasResource.js +1 -1
  64. package/dist/src/types/domains/state.js +28 -2
  65. package/dist/src/validator/rootSchema.js +8 -0
  66. package/dist/tsconfig.tsbuildinfo +1 -1
  67. package/package.json +22 -19
  68. package/release-notes.md +27 -56
  69. package/samples/README_TENCENT_COS.md +68 -26
  70. package/samples/README_TENCENT_SCF.md +47 -29
  71. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +0 -14
  72. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +0 -32
  73. package/.serverlessinsight/state-insight-poc-app-insight-poc-tencent.json.backup +0 -90
  74. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +0 -118
  75. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +0 -215
  76. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +0 -14
  77. package/.serverlessinsight/state-insight-poc-timer-app-insight-poc-timer.json.backup +0 -132
  78. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +0 -55
  79. package/.serverlessinsight/state-insight-volc-destroy-app-insight-volc-destroy.json.backup +0 -1
  80. package/.serverlessinsight/state-insight-volc-nested-app-insight-volc-nested.json.backup +0 -93
  81. package/.serverlessinsight/state-nested-drift-app-nested-drift-service.json.backup +0 -163
  82. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +0 -148
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateApigwPlan = void 0;
4
- const certUtils_1 = require("../../common/certUtils");
5
- const domainUtils_1 = require("../../common/domainUtils");
4
+ const hashUtils_1 = require("../../common/hashUtils");
5
+ const apigwDomainPlan_1 = require("./apigwDomainPlan");
6
6
  const planCapabilities_1 = require("../../common/planCapabilities");
7
7
  const planCompare_1 = require("../../common/planCompare");
8
8
  const aliyunClient_1 = require("../../common/aliyunClient");
@@ -16,7 +16,7 @@ const concurrency_1 = require("../../common/concurrency");
16
16
  const ownershipTag_1 = require("../ownershipTag");
17
17
  const lang_1 = require("../../lang");
18
18
  const DNS_SUB_RESOURCE_SUFFIXES = ['.dns_verification', '.dns_txt_verification'];
19
- const isDnsSubResource = (logicalId) => DNS_SUB_RESOURCE_SUFFIXES.some((suffix) => logicalId.endsWith(suffix));
19
+ const isDnsSubResource = (logicalId) => DNS_SUB_RESOURCE_SUFFIXES.some((suffix) => logicalId.endsWith(suffix) || logicalId.includes(`${suffix}.`));
20
20
  const planEventDeletion = (logicalId, definition) => ({
21
21
  logicalId,
22
22
  action: 'delete',
@@ -104,7 +104,16 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
104
104
  try {
105
105
  const groupInstance = currentState.instances.find((i) => i.type === 'ALIYUN_APIGW_GROUP');
106
106
  const currentDefinition = currentState.definition || {};
107
- const definitionChanged = (0, planCompare_1.definitionsDiffer)(currentDefinition, desiredDefinition);
107
+ const previousDomain = currentDefinition.domain;
108
+ const domainRemoved = !!currentDefinition.domain && !desiredDefinition.domain;
109
+ const certificateRemoved = !!desiredDefinition.domain &&
110
+ !!(previousDomain?.certificateId || previousDomain?.certificateBody) &&
111
+ !(desiredDefinition.domain.certificateId || desiredDefinition.domain.certificateBody);
112
+ const logRemoved = !!currentDefinition.log && !logSnapshot;
113
+ const definitionChanged = (0, planCompare_1.definitionsDiffer)(currentDefinition, desiredDefinition) ||
114
+ domainRemoved ||
115
+ logRemoved ||
116
+ certificateRemoved;
108
117
  if (context.refresh === false) {
109
118
  return definitionChanged
110
119
  ? {
@@ -112,8 +121,17 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
112
121
  action: 'update',
113
122
  resourceType: 'ALIYUN_APIGW',
114
123
  changes: {
115
- before: (0, planCompare_1.managedDefinition)(currentDefinition, desiredDefinition),
116
- after: (0, planCompare_1.managedDefinition)(desiredDefinition),
124
+ before: {
125
+ ...(0, planCompare_1.managedDefinition)(currentDefinition, desiredDefinition),
126
+ ...(domainRemoved || certificateRemoved
127
+ ? { domain: currentDefinition.domain }
128
+ : {}),
129
+ ...(logRemoved ? { log: currentDefinition.log } : {}),
130
+ },
131
+ after: {
132
+ ...(0, planCompare_1.managedDefinition)(desiredDefinition),
133
+ ...(certificateRemoved ? { domain: desiredDefinition.domain } : {}),
134
+ },
117
135
  },
118
136
  }
119
137
  : { logicalId, action: 'noop', resourceType: 'ALIYUN_APIGW' };
@@ -121,6 +139,7 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
121
139
  let groupRemoteDiffers = false;
122
140
  let triggersDiffer = false;
123
141
  let domainDiffers = false;
142
+ let domainPlan;
124
143
  // Issue #246: live group attributes become the diff baseline when the
125
144
  // group was readable; trigger-level drift has no attribute mapping and
126
145
  // is surfaced as a drift reason instead.
@@ -138,51 +157,17 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
138
157
  };
139
158
  }
140
159
  liveGroupAttrs = (0, apigwTypes_1.cloudApigwGroupToDefinition)(remoteGroup);
141
- if (event.domain &&
142
- desiredDefinition.domain?.cdnEnabled !== true &&
143
- remoteGroup.customDomains !== undefined) {
144
- const names = [
145
- String(event.domain.domain_name),
146
- ...(event.domain.www_bind_apex === true
147
- ? [(0, domainUtils_1.deriveWwwDomain)(String(event.domain.domain_name))].filter((name) => name !== null)
148
- : []),
149
- ];
150
- const expectedRedirect = (0, apigwTypes_1.inferProtocolConfig)(event.domain.protocol)
151
- .isHttpRedirectToHttps ?? false;
152
- const desiredCertificate = event.domain.certificate_id
153
- ? (await (0, refreshCache_1.cachedRefreshRead)(context, `cas.getCertificate:${event.domain.certificate_id}`, () => client.cas.getCertificate(String(event.domain.certificate_id))))?.cert
154
- : event.domain.certificate_body
155
- ? (0, certUtils_1.readPemContent)(String(event.domain.certificate_body))
156
- : undefined;
157
- if (event.domain.certificate_id && !desiredCertificate)
158
- throw new Error(lang_1.lang.__('CERT_REFERENCE_NOT_FOUND', {
159
- reference: String(event.domain.certificate_id),
160
- }));
161
- const certificateValue = (value) => (value ?? '').replace(/\s/g, '');
162
- for (const name of names) {
163
- const summary = remoteGroup.customDomains.find((domain) => domain.domainName === name);
164
- if (!summary) {
165
- domainDiffers = true;
166
- continue;
167
- }
168
- if (expectedRedirect !== undefined &&
169
- summary.isHttpRedirectToHttps !== undefined &&
170
- expectedRedirect !== summary.isHttpRedirectToHttps)
171
- domainDiffers = true;
172
- if (desiredCertificate) {
173
- const detail = await (0, refreshCache_1.cachedRefreshRead)(context, `apigw.getDomain:${groupInstance.id}:${name}`, () => client.apigw.getDomain(groupInstance.id, name));
174
- if (!detail ||
175
- certificateValue(detail.certificateBody) !== certificateValue(desiredCertificate))
176
- domainDiffers = true;
177
- }
178
- }
179
- const cloudDomain = remoteGroup.customDomains.find((domain) => domain.domainName === event.domain.domain_name);
180
- liveGroupAttrs.domain = cloudDomain
181
- ? {
160
+ if (event.domain && desiredDefinition.domain?.cdnEnabled !== true) {
161
+ domainPlan = await (0, apigwDomainPlan_1.planApigwDomains)(context, client, groupInstance.id, event.domain, remoteGroup.customDomains, certificateRemoved);
162
+ domainDiffers = Object.keys(domainPlan.updates).length > 0;
163
+ if (domainPlan.certificateVerified && currentDefinition.domain) {
164
+ liveGroupAttrs.domain = {
182
165
  ...currentDefinition.domain,
183
- domainName: cloudDomain.domainName,
184
- }
185
- : null;
166
+ certificateId: desiredDefinition.domain?.certificateId,
167
+ certificateBody: desiredDefinition.domain?.certificateBody,
168
+ certificatePrivateKey: desiredDefinition.domain?.certificatePrivateKey,
169
+ };
170
+ }
186
171
  }
187
172
  if (event.log) {
188
173
  const log = await (0, refreshCache_1.cachedRefreshRead)(context, 'apigw.describeGatewayLogConfig', () => client.apigw.describeGatewayLogConfig());
@@ -233,7 +218,10 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
233
218
  }
234
219
  }
235
220
  }
236
- const effectiveChanged = (0, planCompare_1.definitionsDiffer)((0, planCompare_2.mergeLiveBefore)(currentDefinition, liveGroupAttrs ?? {}, desiredDefinition), desiredDefinition);
221
+ const effectiveChanged = domainRemoved ||
222
+ logRemoved ||
223
+ (certificateRemoved && !domainPlan?.certificateVerified) ||
224
+ (0, planCompare_1.definitionsDiffer)((0, planCompare_2.mergeLiveBefore)(currentDefinition, liveGroupAttrs ?? {}, desiredDefinition), desiredDefinition);
237
225
  if (definitionChanged && !effectiveChanged && !triggersDiffer && !domainDiffers) {
238
226
  return {
239
227
  logicalId,
@@ -243,16 +231,88 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
243
231
  };
244
232
  }
245
233
  if (effectiveChanged || groupRemoteDiffers || triggersDiffer || domainDiffers) {
234
+ const certificateIntentChanged = !(0, hashUtils_1.attributesEqual)({
235
+ id: previousDomain?.certificateId ?? null,
236
+ body: previousDomain?.certificateBody ?? null,
237
+ }, {
238
+ id: desiredDefinition.domain?.certificateId ?? null,
239
+ body: desiredDefinition.domain?.certificateBody ?? null,
240
+ });
241
+ const domainUpdates = { ...domainPlan?.updates };
242
+ if (domainPlan && certificateIntentChanged && !domainPlan.certificateVerified) {
243
+ Object.keys(domainPlan.after).forEach((name) => {
244
+ if (domainPlan.before[name].certificateFingerprint !== undefined)
245
+ return;
246
+ domainUpdates[name] = {
247
+ exists: domainPlan.before[name].exists === true,
248
+ binding: domainPlan.updates[name]?.binding ?? false,
249
+ certificate: true,
250
+ };
251
+ });
252
+ }
253
+ const domainProtocolChanged = !(0, hashUtils_1.attributesEqual)({ protocol: previousDomain?.protocol ?? 'HTTP' }, { protocol: desiredDefinition.domain?.protocol ?? 'HTTP' });
254
+ const bindingIntentChanged = domainProtocolChanged ||
255
+ !(0, hashUtils_1.attributesEqual)({ name: previousDomain?.domainName, www: previousDomain?.wwwBindApex ?? false }, {
256
+ name: desiredDefinition.domain?.domainName,
257
+ www: desiredDefinition.domain?.wwwBindApex ?? false,
258
+ });
259
+ if (domainPlan && bindingIntentChanged) {
260
+ Object.keys(domainPlan.after).forEach((name) => {
261
+ if (domainPlan.before[name].redirectToHttps === undefined) {
262
+ domainUpdates[name] = {
263
+ exists: domainPlan.before[name].exists === true,
264
+ binding: true,
265
+ certificate: domainUpdates[name]?.certificate ?? false,
266
+ };
267
+ }
268
+ });
269
+ }
270
+ const before = liveGroupAttrs
271
+ ? (0, planCompare_2.mergeLiveBefore)(currentDefinition, liveGroupAttrs, desiredDefinition)
272
+ : (0, planCompare_1.managedDefinition)(currentDefinition, desiredDefinition);
273
+ const after = (0, planCompare_1.managedDefinition)(desiredDefinition);
274
+ if (domainRemoved || certificateRemoved)
275
+ before.domain = currentDefinition.domain;
276
+ if (certificateRemoved)
277
+ after.domain = desiredDefinition.domain;
278
+ if (logRemoved)
279
+ before.log = currentDefinition.log;
280
+ const revertKeys = [
281
+ ...(0, planCompare_2.computeRevertKeys)(currentDefinition, liveGroupAttrs ?? {}, desiredDefinition),
282
+ ...(domainPlan &&
283
+ (0, hashUtils_1.attributesEqual)({ domain: currentDefinition.domain ?? null }, { domain: desiredDefinition.domain })
284
+ ? (0, planCompare_2.computeRevertKeys)({ domainBindings: domainPlan.after }, { domainBindings: domainPlan.before }, { domainBindings: domainPlan.after })
285
+ : []),
286
+ ];
246
287
  return {
247
288
  logicalId,
248
289
  action: 'update',
249
290
  resourceType: 'ALIYUN_APIGW',
291
+ ...(revertKeys.length ? { revertKeys } : {}),
250
292
  changes: {
251
- before: liveGroupAttrs
252
- ? (0, planCompare_2.mergeLiveBefore)(currentDefinition, liveGroupAttrs, desiredDefinition)
253
- : (0, planCompare_1.managedDefinition)(currentDefinition, desiredDefinition),
254
- after: (0, planCompare_1.managedDefinition)(desiredDefinition),
293
+ before: { ...before, ...(domainPlan ? { domainBindings: domainPlan.before } : {}) },
294
+ after: { ...after, ...(domainPlan ? { domainBindings: domainPlan.after } : {}) },
255
295
  },
296
+ ...(liveGroupAttrs &&
297
+ desiredDefinition.domain?.cdnEnabled !== true &&
298
+ previousDomain?.cdnEnabled !== true
299
+ ? {
300
+ gatewayUpdate: {
301
+ group: (0, planCompare_1.definitionsDiffer)(liveGroupAttrs, groupDefinition),
302
+ apis: triggersDiffer ||
303
+ (0, planCompare_1.definitionsDiffer)(currentDefinition, {
304
+ triggers: desiredDefinition.triggers,
305
+ }) ||
306
+ domainProtocolChanged,
307
+ logging: logRemoved ||
308
+ (0, planCompare_1.definitionsDiffer)(currentDefinition, { log: desiredDefinition.log }) ||
309
+ (0, planCompare_2.remoteDiffersFromDesired)(liveGroupAttrs, {
310
+ log: desiredDefinition.log,
311
+ }),
312
+ domains: domainUpdates,
313
+ },
314
+ }
315
+ : {}),
256
316
  ...((0, planCompare_2.remoteDiffersFromDesired)(liveGroupAttrs ?? {}, currentDefinition) ||
257
317
  (domainDiffers &&
258
318
  !(0, planCompare_1.definitionsDiffer)({ domain: currentDefinition.domain }, { domain: desiredDefinition.domain })) ||
@@ -373,6 +373,26 @@ const buildDomainBindingConfig = async (domain, groupId, serviceName, eventKey,
373
373
  ...certConfig,
374
374
  };
375
375
  };
376
+ const removeOwnedDomainDns = async (client, state, logicalId, domains) => Object.entries(state.resources)
377
+ .filter(([key, resource]) => key.startsWith(`${logicalId}.dns_`) &&
378
+ resource.mode === 'managed' &&
379
+ domains.includes(String(resource.definition.domainName)) &&
380
+ resource.instances.every((instance) => (instance.type === 'CNAME' || instance.type === 'TXT') &&
381
+ instance.id &&
382
+ instance.id !== 'existing'))
383
+ .reduce(async (previous, [key, resource]) => {
384
+ const current = await previous;
385
+ await Promise.all(resource.instances.map(async (instance) => {
386
+ try {
387
+ await client.dns.deleteDomainRecord(instance.id);
388
+ }
389
+ catch (error) {
390
+ if (!(0, aliyunClient_1.isApigwNotFoundError)(error))
391
+ throw error;
392
+ }
393
+ }));
394
+ return (0, stateManager_1.removeResource)(current, key);
395
+ }, Promise.resolve(state));
376
396
  const createApigwResource = async (context, event, serviceName, resolveRoleArn, state) => {
377
397
  const logicalId = `events.${event.key}`;
378
398
  const client = (0, aliyunClient_1.createAliyunClient)(context);
@@ -695,7 +715,8 @@ const updateApigwResource = async (context, event, serviceName, resolveRoleArn,
695
715
  }
696
716
  }
697
717
  const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName, context.stage);
698
- await client.apigw.updateApiGroup(groupId, groupConfig);
718
+ if (options?.scope?.group !== false)
719
+ await client.apigw.updateApiGroup(groupId, groupConfig);
699
720
  const groupInfo = await client.apigw.getApiGroup(groupId);
700
721
  if (!groupInfo) {
701
722
  throw new Error(lang_1.lang.__('APIGW_GROUP_INFO_AFTER_UPDATE_FAILED', { error: groupId }));
@@ -704,56 +725,64 @@ const updateApigwResource = async (context, event, serviceName, resolveRoleArn,
704
725
  buildApigwGroupInstanceFromProvider(groupInfo, context.stage),
705
726
  ];
706
727
  const existingApis = existingInstances.filter((i) => i.type === 'ALIYUN_APIGW_API');
707
- const neededApiKeys = new Set();
708
- for (const trigger of event.triggers) {
709
- const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, context.stage, roleArnFor(String(trigger.backend)));
710
- const apiKey = (0, apigwTypes_1.generateApiKey)(trigger.method, trigger.path);
711
- neededApiKeys.add(apiKey);
712
- const existingApi = existingApis.find((a) => {
713
- return a.id && a.apiName === apiConfig.apiName;
714
- });
715
- let apiId;
716
- if (existingApi) {
717
- apiId = existingApi.id;
718
- await client.apigw.updateApi(apiId, apiConfig);
719
- }
720
- else {
721
- apiId = await client.apigw.createApi(apiConfig);
722
- }
723
- const apiInfo = await client.apigw.getApi(groupId, apiId);
724
- if (apiInfo) {
725
- instances.push(buildApigwApiInstanceFromProvider(apiInfo, context.stage, groupId));
726
- }
727
- const deploymentConfig = {
728
- groupId,
729
- apiId,
730
- stageName: 'RELEASE',
731
- description: `${serviceName} API deployment for ${trigger.method} ${trigger.path}`,
732
- };
733
- await client.apigw.deployApi(deploymentConfig);
734
- instances.push(buildApigwDeploymentInstance(groupId, apiId, 'RELEASE', context.stage));
735
- }
736
- for (const existingApi of existingApis) {
737
- const apiInfo = await client.apigw.getApi(groupId, existingApi.id);
738
- if (apiInfo) {
739
- const isNeeded = event.triggers.some((t) => {
740
- const expectedName = (0, apigwTypes_1.triggerToApigwApiConfig)(event, t, groupId, serviceName, context.region, context.stage, roleArnFor(String(t.backend))).apiName;
741
- return apiInfo.apiName === expectedName;
728
+ if (options?.scope?.apis !== false) {
729
+ const neededApiKeys = new Set();
730
+ for (const trigger of event.triggers) {
731
+ const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, context.stage, roleArnFor(String(trigger.backend)));
732
+ const apiKey = (0, apigwTypes_1.generateApiKey)(trigger.method, trigger.path);
733
+ neededApiKeys.add(apiKey);
734
+ const existingApi = existingApis.find((a) => {
735
+ return a.id && a.apiName === apiConfig.apiName;
742
736
  });
743
- if (!isNeeded) {
744
- try {
745
- await client.apigw.abolishApi(groupId, existingApi.id, 'RELEASE');
746
- }
747
- catch {
748
- // API might not be deployed
737
+ let apiId;
738
+ if (existingApi) {
739
+ apiId = existingApi.id;
740
+ await client.apigw.updateApi(apiId, apiConfig);
741
+ }
742
+ else {
743
+ apiId = await client.apigw.createApi(apiConfig);
744
+ }
745
+ const apiInfo = await client.apigw.getApi(groupId, apiId);
746
+ if (apiInfo) {
747
+ instances.push(buildApigwApiInstanceFromProvider(apiInfo, context.stage, groupId));
748
+ }
749
+ const deploymentConfig = {
750
+ groupId,
751
+ apiId,
752
+ stageName: 'RELEASE',
753
+ description: `${serviceName} API deployment for ${trigger.method} ${trigger.path}`,
754
+ };
755
+ await client.apigw.deployApi(deploymentConfig);
756
+ instances.push(buildApigwDeploymentInstance(groupId, apiId, 'RELEASE', context.stage));
757
+ }
758
+ for (const existingApi of existingApis) {
759
+ const apiInfo = await client.apigw.getApi(groupId, existingApi.id);
760
+ if (apiInfo) {
761
+ const isNeeded = event.triggers.some((t) => {
762
+ const expectedName = (0, apigwTypes_1.triggerToApigwApiConfig)(event, t, groupId, serviceName, context.region, context.stage, roleArnFor(String(t.backend))).apiName;
763
+ return apiInfo.apiName === expectedName;
764
+ });
765
+ if (!isNeeded) {
766
+ try {
767
+ await client.apigw.abolishApi(groupId, existingApi.id, 'RELEASE');
768
+ }
769
+ catch {
770
+ // API might not be deployed
771
+ }
772
+ await client.apigw.deleteApi(groupId, existingApi.id);
749
773
  }
750
- await client.apigw.deleteApi(groupId, existingApi.id);
751
774
  }
752
775
  }
753
776
  }
777
+ else {
778
+ instances.push(...existingInstances.filter((instance) => instance.type === 'ALIYUN_APIGW_API' || instance.type === 'ALIYUN_APIGW_DEPLOYMENT'));
779
+ }
754
780
  const logSnapshot = (0, apigwTypes_1.buildEventLogSnapshot)(event, context);
755
781
  let sharedProjectState;
756
- if (event.log) {
782
+ if (options?.scope?.logging === false) {
783
+ instances.push(...existingInstances.filter((instance) => instance.type === 'ALIYUN_APIGW_LOG_CONFIG'));
784
+ }
785
+ else if (event.log) {
757
786
  const logResult = await ensureGatewayLogConfig(context, client, state);
758
787
  if (logResult?.sharedProject) {
759
788
  sharedProjectState = logResult.sharedProject;
@@ -782,98 +811,108 @@ const updateApigwResource = async (context, event, serviceName, resolveRoleArn,
782
811
  Object.keys(state.resources ?? {}).some((k) => k.startsWith(`${logicalId}.dns_`) &&
783
812
  k !== `${logicalId}.dns_verification` &&
784
813
  k !== `${logicalId}.dns_txt_verification`);
785
- if (!options?.repairDomain &&
814
+ const skipDomainBinding = !options?.repairDomain &&
786
815
  previousDomainDef &&
787
816
  desiredDomainDef &&
788
817
  hasBoundDomains &&
789
- (0, hashUtils_1.attributesEqual)(previousDomainDef, desiredDomainDef)) {
818
+ (0, hashUtils_1.attributesEqual)(previousDomainDef, desiredDomainDef);
819
+ if (skipDomainBinding)
790
820
  logger_1.logger.info(lang_1.lang.__('APIGW_DOMAIN_UNCHANGED_SKIP'));
791
- // Still include existing domain instances for state consistency
792
- const existingDomainInstances = existingState?.instances?.filter((i) => i.type === 'ALIYUN_APIGW_GROUP' ||
793
- i.type === 'ALIYUN_APIGW_API' ||
794
- i.type === 'ALIYUN_APIGW_DEPLOYMENT') ?? [];
795
- instances.push(...existingDomainInstances);
796
- return (0, stateManager_1.setResource)(state, logicalId, {
797
- mode: 'managed',
798
- region: context.region,
799
- definition: { ...(existingState?.definition ?? {}), domain: desiredDomainDef },
800
- instances: [...instances, ...existingDomainInstances],
801
- lastUpdated: new Date().toISOString(),
802
- });
803
- }
804
- const primaryDomain = event.domain.domain_name;
805
- const wwwBindApex = event.domain.www_bind_apex === true;
806
- const wwwDomain = wwwBindApex ? (0, domainUtils_1.deriveWwwDomain)(primaryDomain) : null;
807
- const isCdnEnabled = getIsCdnEnabled(event);
808
- const previousWwwBindApex = previousDomainDef?.wwwBindApex === true;
809
- const previousDomainName = previousDomainDef?.domainName;
810
- const previousCdnEnabled = previousDomainDef?.cdnEnabled === true;
811
- const previousTrackedDomains = getApigwTrackedDomains(previousDomainName, previousWwwBindApex);
812
- const originDomain = groupInfo.subDomain;
813
- if (isCdnEnabled && !originDomain) {
814
- throw new Error(lang_1.lang.__('APIGW_GROUP_NO_SUBDOMAIN_CDN', { groupName: groupId }));
815
- }
816
- const domainConfig = await buildDomainBindingConfig(event.domain, groupId, serviceName, event.key, context.stage, client);
817
- if (isCdnEnabled) {
818
- const desiredDomains = [primaryDomain, ...(wwwDomain ? [wwwDomain] : [])];
819
- const cdnDomainsToCleanup = previousCdnEnabled
820
- ? previousTrackedDomains.filter((domain) => !desiredDomains.includes(domain))
821
- : [];
822
- if (cdnDomainsToCleanup.length > 0) {
823
- await cleanupApigwCdnResources(client, existingInstances, cdnDomainsToCleanup);
821
+ if (!skipDomainBinding) {
822
+ const primaryDomain = event.domain.domain_name;
823
+ const wwwBindApex = event.domain.www_bind_apex === true;
824
+ const wwwDomain = wwwBindApex ? (0, domainUtils_1.deriveWwwDomain)(primaryDomain) : null;
825
+ const isCdnEnabled = getIsCdnEnabled(event);
826
+ const previousWwwBindApex = previousDomainDef?.wwwBindApex === true;
827
+ const previousDomainName = previousDomainDef?.domainName;
828
+ const previousCdnEnabled = previousDomainDef?.cdnEnabled === true;
829
+ const previousTrackedDomains = getApigwTrackedDomains(previousDomainName, previousWwwBindApex);
830
+ const originDomain = groupInfo.subDomain;
831
+ if (isCdnEnabled && !originDomain) {
832
+ throw new Error(lang_1.lang.__('APIGW_GROUP_NO_SUBDOMAIN_CDN', { groupName: groupId }));
824
833
  }
825
- await updateApigwCdnDistribution(context, client, event, primaryDomain, originDomain, existingInstances, instances, {
826
- certificateBody: domainConfig.certificateBody,
827
- certificatePrivateKey: domainConfig.certificatePrivateKey,
828
- });
829
- if (wwwDomain) {
830
- logger_1.logger.info(lang_1.lang.__('APIGW_BINDING_DOMAIN', { domain: wwwDomain }));
831
- const wwwDomainConfig = {
832
- ...domainConfig,
833
- domainName: wwwDomain,
834
- certificateName: domainConfig.certificateName
835
- ? `${domainConfig.certificateName}-www`
836
- : undefined,
837
- };
838
- await updateApigwCdnDistribution(context, client, event, wwwDomain, originDomain, existingInstances, instances, {
839
- certificateBody: wwwDomainConfig.certificateBody,
840
- certificatePrivateKey: wwwDomainConfig.certificatePrivateKey,
834
+ const domainConfig = await buildDomainBindingConfig(event.domain, groupId, serviceName, event.key, context.stage, client);
835
+ if (isCdnEnabled) {
836
+ const desiredDomains = [primaryDomain, ...(wwwDomain ? [wwwDomain] : [])];
837
+ const cdnDomainsToCleanup = previousCdnEnabled
838
+ ? previousTrackedDomains.filter((domain) => !desiredDomains.includes(domain))
839
+ : [];
840
+ if (cdnDomainsToCleanup.length > 0) {
841
+ await cleanupApigwCdnResources(client, existingInstances, cdnDomainsToCleanup);
842
+ }
843
+ await updateApigwCdnDistribution(context, client, event, primaryDomain, originDomain, existingInstances, instances, {
844
+ certificateBody: domainConfig.certificateBody,
845
+ certificatePrivateKey: domainConfig.certificatePrivateKey,
841
846
  });
847
+ if (wwwDomain) {
848
+ logger_1.logger.info(lang_1.lang.__('APIGW_BINDING_DOMAIN', { domain: wwwDomain }));
849
+ const wwwDomainConfig = {
850
+ ...domainConfig,
851
+ domainName: wwwDomain,
852
+ certificateName: domainConfig.certificateName
853
+ ? `${domainConfig.certificateName}-www`
854
+ : undefined,
855
+ };
856
+ await updateApigwCdnDistribution(context, client, event, wwwDomain, originDomain, existingInstances, instances, {
857
+ certificateBody: wwwDomainConfig.certificateBody,
858
+ certificatePrivateKey: wwwDomainConfig.certificatePrivateKey,
859
+ });
860
+ }
842
861
  }
843
- }
844
- else {
845
- if (previousCdnEnabled && previousTrackedDomains.length > 0) {
846
- await cleanupApigwCdnResources(client, existingInstances, previousTrackedDomains);
847
- }
848
- state = await client.apigw.bindCustomDomain(domainConfig, state, logicalId);
849
- if (wwwDomain) {
850
- logger_1.logger.info(lang_1.lang.__('APIGW_BINDING_DOMAIN', { domain: wwwDomain }));
851
- const wwwDomainConfig = {
852
- ...domainConfig,
853
- domainName: wwwDomain,
854
- certificateName: domainConfig.certificateName
855
- ? `${domainConfig.certificateName}-www`
856
- : undefined,
862
+ else {
863
+ if (previousCdnEnabled && previousTrackedDomains.length > 0) {
864
+ await cleanupApigwCdnResources(client, existingInstances, previousTrackedDomains);
865
+ }
866
+ const reconcileDomain = async (config) => {
867
+ const update = options?.scope?.domains[config.domainName];
868
+ if (options?.scope && !update)
869
+ return;
870
+ if (update?.exists && !update.binding && update.certificate) {
871
+ if (config.certificateBody)
872
+ await client.apigw.setDomainCertificate(config);
873
+ }
874
+ else {
875
+ state = update?.exists
876
+ ? await client.apigw.bindCustomDomain(config, state, logicalId, true)
877
+ : await client.apigw.bindCustomDomain(config, state, logicalId);
878
+ }
879
+ if (!config.certificateBody &&
880
+ (previousDomainDef?.certificateId || previousDomainDef?.certificateBody)) {
881
+ await client.apigw.deleteDomainCertificate(groupId, config.domainName);
882
+ }
857
883
  };
858
- state = await client.apigw.bindCustomDomain(wwwDomainConfig, state, logicalId);
859
- }
860
- }
861
- if (previousWwwBindApex && previousDomainName) {
862
- const previousWwwDomain = (0, domainUtils_1.deriveWwwDomain)(previousDomainName);
863
- if (previousWwwDomain && previousWwwDomain !== wwwDomain && !previousCdnEnabled) {
864
- try {
865
- await client.apigw.unbindCustomDomain(groupId, previousWwwDomain);
884
+ await reconcileDomain(domainConfig);
885
+ if (wwwDomain) {
886
+ const wwwDomainConfig = {
887
+ ...domainConfig,
888
+ domainName: wwwDomain,
889
+ certificateName: domainConfig.certificateName
890
+ ? `${domainConfig.certificateName}-www`
891
+ : undefined,
892
+ };
893
+ await reconcileDomain(wwwDomainConfig);
866
894
  }
867
- catch (error) {
868
- if (!(0, aliyunClient_1.isApigwNotFoundError)(error)) {
869
- throw error;
895
+ }
896
+ if (previousWwwBindApex && previousDomainName) {
897
+ const previousWwwDomain = (0, domainUtils_1.deriveWwwDomain)(previousDomainName);
898
+ if (previousWwwDomain && previousWwwDomain !== wwwDomain && !previousCdnEnabled) {
899
+ try {
900
+ await client.apigw.unbindCustomDomain(groupId, previousWwwDomain);
901
+ }
902
+ catch (error) {
903
+ if (!(0, aliyunClient_1.isApigwNotFoundError)(error)) {
904
+ throw error;
905
+ }
906
+ logger_1.logger.warn(lang_1.lang.__('APIGW_WWW_DOMAIN_UNBIND_FAILED', {
907
+ domain: previousWwwDomain,
908
+ error: String(error),
909
+ }));
870
910
  }
871
- logger_1.logger.warn(lang_1.lang.__('APIGW_WWW_DOMAIN_UNBIND_FAILED', {
872
- domain: previousWwwDomain,
873
- error: String(error),
874
- }));
875
911
  }
876
912
  }
913
+ if (previousDomainName && previousDomainName !== primaryDomain && !previousCdnEnabled) {
914
+ await client.apigw.unbindCustomDomain(groupId, previousDomainName);
915
+ }
877
916
  }
878
917
  }
879
918
  else {
@@ -914,6 +953,12 @@ const updateApigwResource = async (context, event, serviceName, resolveRoleArn,
914
953
  }
915
954
  }
916
955
  }
956
+ const previousDomain = existingState?.definition.domain;
957
+ const desiredNames = event.domain
958
+ ? getApigwTrackedDomains(String(event.domain.domain_name), event.domain.www_bind_apex === true)
959
+ : [];
960
+ const removedDomains = getApigwTrackedDomains(previousDomain?.domainName, previousDomain?.wwwBindApex === true).filter((name) => !desiredNames.includes(name));
961
+ state = await removeOwnedDomainDns(client, state, logicalId, removedDomains);
917
962
  const groupDefinition = (0, apigwTypes_1.extractApigwGroupDefinition)(groupConfig);
918
963
  const resourceState = {
919
964
  mode: 'managed',
@@ -14,8 +14,8 @@ const tablestorePlanner_1 = require("./tablestorePlanner");
14
14
  const tablestoreExecutor_1 = require("./tablestoreExecutor");
15
15
  const apigwPlanner_1 = require("./apigwPlanner");
16
16
  const apigwExecutor_1 = require("./apigwExecutor");
17
- const createSaveStateFn = (backend, iac, stage) => async (state) => {
18
- await backend.saveState(state, iac.app, iac.service, stage);
17
+ const createSaveStateFn = (backend) => async (state) => {
18
+ await backend.saveState(state);
19
19
  };
20
20
  const handlePartialFailure = (failure) => {
21
21
  const error = failure.error;
@@ -84,8 +84,8 @@ const deployAliyunStack = async (iac, backend, approvedPlan) => {
84
84
  // Cache IAC for access throughout the deployment
85
85
  (0, common_1.setIac)(iac);
86
86
  common_1.logger.info(lang_1.lang.__('DEPLOYING_STACK_PUBLISHING_ASSETS'));
87
- let state = await backend.loadState(iac.provider.name, iac.app, iac.service, context.stage);
88
- const onStateChange = createSaveStateFn(backend, iac, context.stage);
87
+ let state = await backend.loadState();
88
+ const onStateChange = createSaveStateFn(backend);
89
89
  common_1.logger.info(lang_1.lang.__('GENERATING_PLAN'));
90
90
  const functionPlan = approvedPlan
91
91
  ? partitionPlan(approvedPlan, ['ALIYUN_FC3'])
@@ -184,7 +184,7 @@ const deployAliyunStack = async (iac, backend, approvedPlan) => {
184
184
  ],
185
185
  });
186
186
  }
187
- await backend.saveState(state, iac.app, iac.service, context.stage);
187
+ await backend.saveState(state);
188
188
  common_1.logger.info(lang_1.lang.__('STACK_DEPLOYED'));
189
189
  };
190
190
  exports.deployAliyunStack = deployAliyunStack;
@@ -16,8 +16,8 @@ const tablestoreExecutor_1 = require("./tablestoreExecutor");
16
16
  const apigwPlanner_1 = require("./apigwPlanner");
17
17
  const apigwExecutor_1 = require("./apigwExecutor");
18
18
  const sharedLogProject_1 = require("./sharedLogProject");
19
- const createSaveStateFn = (backend, app, service, stage) => async (state) => {
20
- await backend.saveState(state, app, service, stage);
19
+ const createSaveStateFn = (backend) => async (state) => {
20
+ await backend.saveState(state);
21
21
  };
22
22
  const handlePartialFailure = (failure) => {
23
23
  const error = failure.error;
@@ -36,8 +36,8 @@ const collectSuccessfulItems = (results) => results.flatMap((result) => result.p
36
36
  const destroyAliyunStack = async (backend) => {
37
37
  const context = (0, common_1.getContext)();
38
38
  const providerName = common_1.ProviderEnum.ALIYUN;
39
- let state = await backend.loadState(providerName, context.app, context.service, context.stage);
40
- const onStateChange = createSaveStateFn(backend, context.app, context.service, context.stage);
39
+ let state = await backend.loadState();
40
+ const onStateChange = createSaveStateFn(backend);
41
41
  // Set minimal IAC for destruction (function resolution not needed)
42
42
  (0, common_1.setIac)({
43
43
  version: '1.0',
@@ -142,6 +142,6 @@ const destroyAliyunStack = async (backend) => {
142
142
  }
143
143
  }
144
144
  }
145
- await backend.saveState(state, context.app, context.service, context.stage);
145
+ await backend.saveState(state);
146
146
  };
147
147
  exports.destroyAliyunStack = destroyAliyunStack;