@go-to-k/cdkd 0.74.0 → 0.75.0

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.
package/dist/cli.js CHANGED
@@ -4374,16 +4374,16 @@ var require_printer = __commonJS({
4374
4374
  },
4375
4375
  // Document
4376
4376
  Document: {
4377
- leave: (node) => join9(node.definitions, "\n\n")
4377
+ leave: (node) => join11(node.definitions, "\n\n")
4378
4378
  },
4379
4379
  OperationDefinition: {
4380
4380
  leave(node) {
4381
- const varDefs = hasMultilineItems(node.variableDefinitions) ? wrap("(\n", join9(node.variableDefinitions, "\n"), "\n)") : wrap("(", join9(node.variableDefinitions, ", "), ")");
4382
- const prefix = wrap("", node.description, "\n") + join9(
4381
+ const varDefs = hasMultilineItems(node.variableDefinitions) ? wrap("(\n", join11(node.variableDefinitions, "\n"), "\n)") : wrap("(", join11(node.variableDefinitions, ", "), ")");
4382
+ const prefix = wrap("", node.description, "\n") + join11(
4383
4383
  [
4384
4384
  node.operation,
4385
- join9([node.name, varDefs]),
4386
- join9(node.directives, " ")
4385
+ join11([node.name, varDefs]),
4386
+ join11(node.directives, " ")
4387
4387
  ],
4388
4388
  " "
4389
4389
  );
@@ -4391,7 +4391,7 @@ var require_printer = __commonJS({
4391
4391
  }
4392
4392
  },
4393
4393
  VariableDefinition: {
4394
- leave: ({ variable, type, defaultValue, directives, description }) => wrap("", description, "\n") + variable + ": " + type + wrap(" = ", defaultValue) + wrap(" ", join9(directives, " "))
4394
+ leave: ({ variable, type, defaultValue, directives, description }) => wrap("", description, "\n") + variable + ": " + type + wrap(" = ", defaultValue) + wrap(" ", join11(directives, " "))
4395
4395
  },
4396
4396
  SelectionSet: {
4397
4397
  leave: ({ selections }) => block(selections)
@@ -4399,11 +4399,11 @@ var require_printer = __commonJS({
4399
4399
  Field: {
4400
4400
  leave({ alias, name, arguments: args, directives, selectionSet }) {
4401
4401
  const prefix = wrap("", alias, ": ") + name;
4402
- let argsLine = prefix + wrap("(", join9(args, ", "), ")");
4402
+ let argsLine = prefix + wrap("(", join11(args, ", "), ")");
4403
4403
  if (argsLine.length > MAX_LINE_LENGTH) {
4404
- argsLine = prefix + wrap("(\n", indent(join9(args, "\n")), "\n)");
4404
+ argsLine = prefix + wrap("(\n", indent(join11(args, "\n")), "\n)");
4405
4405
  }
4406
- return join9([argsLine, join9(directives, " "), selectionSet], " ");
4406
+ return join11([argsLine, join11(directives, " "), selectionSet], " ");
4407
4407
  }
4408
4408
  },
4409
4409
  Argument: {
@@ -4411,14 +4411,14 @@ var require_printer = __commonJS({
4411
4411
  },
4412
4412
  // Fragments
4413
4413
  FragmentSpread: {
4414
- leave: ({ name, directives }) => "..." + name + wrap(" ", join9(directives, " "))
4414
+ leave: ({ name, directives }) => "..." + name + wrap(" ", join11(directives, " "))
4415
4415
  },
4416
4416
  InlineFragment: {
4417
- leave: ({ typeCondition, directives, selectionSet }) => join9(
4417
+ leave: ({ typeCondition, directives, selectionSet }) => join11(
4418
4418
  [
4419
4419
  "...",
4420
4420
  wrap("on ", typeCondition),
4421
- join9(directives, " "),
4421
+ join11(directives, " "),
4422
4422
  selectionSet
4423
4423
  ],
4424
4424
  " "
@@ -4434,7 +4434,7 @@ var require_printer = __commonJS({
4434
4434
  description
4435
4435
  }) => wrap("", description, "\n") + // Note: fragment variable definitions are experimental and may be changed
4436
4436
  // or removed in the future.
4437
- `fragment ${name}${wrap("(", join9(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap("", join9(directives, " "), " ")}` + selectionSet
4437
+ `fragment ${name}${wrap("(", join11(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap("", join11(directives, " "), " ")}` + selectionSet
4438
4438
  },
4439
4439
  // Value
4440
4440
  IntValue: {
@@ -4456,17 +4456,17 @@ var require_printer = __commonJS({
4456
4456
  leave: ({ value }) => value
4457
4457
  },
4458
4458
  ListValue: {
4459
- leave: ({ values }) => "[" + join9(values, ", ") + "]"
4459
+ leave: ({ values }) => "[" + join11(values, ", ") + "]"
4460
4460
  },
4461
4461
  ObjectValue: {
4462
- leave: ({ fields }) => "{" + join9(fields, ", ") + "}"
4462
+ leave: ({ fields }) => "{" + join11(fields, ", ") + "}"
4463
4463
  },
4464
4464
  ObjectField: {
4465
4465
  leave: ({ name, value }) => name + ": " + value
4466
4466
  },
4467
4467
  // Directive
4468
4468
  Directive: {
4469
- leave: ({ name, arguments: args }) => "@" + name + wrap("(", join9(args, ", "), ")")
4469
+ leave: ({ name, arguments: args }) => "@" + name + wrap("(", join11(args, ", "), ")")
4470
4470
  },
4471
4471
  // Type
4472
4472
  NamedType: {
@@ -4480,61 +4480,61 @@ var require_printer = __commonJS({
4480
4480
  },
4481
4481
  // Type System Definitions
4482
4482
  SchemaDefinition: {
4483
- leave: ({ description, directives, operationTypes }) => wrap("", description, "\n") + join9(["schema", join9(directives, " "), block(operationTypes)], " ")
4483
+ leave: ({ description, directives, operationTypes }) => wrap("", description, "\n") + join11(["schema", join11(directives, " "), block(operationTypes)], " ")
4484
4484
  },
4485
4485
  OperationTypeDefinition: {
4486
4486
  leave: ({ operation, type }) => operation + ": " + type
4487
4487
  },
4488
4488
  ScalarTypeDefinition: {
4489
- leave: ({ description, name, directives }) => wrap("", description, "\n") + join9(["scalar", name, join9(directives, " ")], " ")
4489
+ leave: ({ description, name, directives }) => wrap("", description, "\n") + join11(["scalar", name, join11(directives, " ")], " ")
4490
4490
  },
4491
4491
  ObjectTypeDefinition: {
4492
- leave: ({ description, name, interfaces, directives, fields }) => wrap("", description, "\n") + join9(
4492
+ leave: ({ description, name, interfaces, directives, fields }) => wrap("", description, "\n") + join11(
4493
4493
  [
4494
4494
  "type",
4495
4495
  name,
4496
- wrap("implements ", join9(interfaces, " & ")),
4497
- join9(directives, " "),
4496
+ wrap("implements ", join11(interfaces, " & ")),
4497
+ join11(directives, " "),
4498
4498
  block(fields)
4499
4499
  ],
4500
4500
  " "
4501
4501
  )
4502
4502
  },
4503
4503
  FieldDefinition: {
4504
- leave: ({ description, name, arguments: args, type, directives }) => wrap("", description, "\n") + name + (hasMultilineItems(args) ? wrap("(\n", indent(join9(args, "\n")), "\n)") : wrap("(", join9(args, ", "), ")")) + ": " + type + wrap(" ", join9(directives, " "))
4504
+ leave: ({ description, name, arguments: args, type, directives }) => wrap("", description, "\n") + name + (hasMultilineItems(args) ? wrap("(\n", indent(join11(args, "\n")), "\n)") : wrap("(", join11(args, ", "), ")")) + ": " + type + wrap(" ", join11(directives, " "))
4505
4505
  },
4506
4506
  InputValueDefinition: {
4507
- leave: ({ description, name, type, defaultValue, directives }) => wrap("", description, "\n") + join9(
4508
- [name + ": " + type, wrap("= ", defaultValue), join9(directives, " ")],
4507
+ leave: ({ description, name, type, defaultValue, directives }) => wrap("", description, "\n") + join11(
4508
+ [name + ": " + type, wrap("= ", defaultValue), join11(directives, " ")],
4509
4509
  " "
4510
4510
  )
4511
4511
  },
4512
4512
  InterfaceTypeDefinition: {
4513
- leave: ({ description, name, interfaces, directives, fields }) => wrap("", description, "\n") + join9(
4513
+ leave: ({ description, name, interfaces, directives, fields }) => wrap("", description, "\n") + join11(
4514
4514
  [
4515
4515
  "interface",
4516
4516
  name,
4517
- wrap("implements ", join9(interfaces, " & ")),
4518
- join9(directives, " "),
4517
+ wrap("implements ", join11(interfaces, " & ")),
4518
+ join11(directives, " "),
4519
4519
  block(fields)
4520
4520
  ],
4521
4521
  " "
4522
4522
  )
4523
4523
  },
4524
4524
  UnionTypeDefinition: {
4525
- leave: ({ description, name, directives, types }) => wrap("", description, "\n") + join9(
4526
- ["union", name, join9(directives, " "), wrap("= ", join9(types, " | "))],
4525
+ leave: ({ description, name, directives, types }) => wrap("", description, "\n") + join11(
4526
+ ["union", name, join11(directives, " "), wrap("= ", join11(types, " | "))],
4527
4527
  " "
4528
4528
  )
4529
4529
  },
4530
4530
  EnumTypeDefinition: {
4531
- leave: ({ description, name, directives, values }) => wrap("", description, "\n") + join9(["enum", name, join9(directives, " "), block(values)], " ")
4531
+ leave: ({ description, name, directives, values }) => wrap("", description, "\n") + join11(["enum", name, join11(directives, " "), block(values)], " ")
4532
4532
  },
4533
4533
  EnumValueDefinition: {
4534
- leave: ({ description, name, directives }) => wrap("", description, "\n") + join9([name, join9(directives, " ")], " ")
4534
+ leave: ({ description, name, directives }) => wrap("", description, "\n") + join11([name, join11(directives, " ")], " ")
4535
4535
  },
4536
4536
  InputObjectTypeDefinition: {
4537
- leave: ({ description, name, directives, fields }) => wrap("", description, "\n") + join9(["input", name, join9(directives, " "), block(fields)], " ")
4537
+ leave: ({ description, name, directives, fields }) => wrap("", description, "\n") + join11(["input", name, join11(directives, " "), block(fields)], " ")
4538
4538
  },
4539
4539
  DirectiveDefinition: {
4540
4540
  leave: ({
@@ -4544,84 +4544,84 @@ var require_printer = __commonJS({
4544
4544
  directives,
4545
4545
  repeatable,
4546
4546
  locations
4547
- }) => wrap("", description, "\n") + "directive @" + name + (hasMultilineItems(args) ? wrap("(\n", indent(join9(args, "\n")), "\n)") : wrap("(", join9(args, ", "), ")")) + wrap(" ", join9(directives, " ")) + (repeatable ? " repeatable" : "") + " on " + join9(locations, " | ")
4547
+ }) => wrap("", description, "\n") + "directive @" + name + (hasMultilineItems(args) ? wrap("(\n", indent(join11(args, "\n")), "\n)") : wrap("(", join11(args, ", "), ")")) + wrap(" ", join11(directives, " ")) + (repeatable ? " repeatable" : "") + " on " + join11(locations, " | ")
4548
4548
  },
4549
4549
  SchemaExtension: {
4550
- leave: ({ directives, operationTypes }) => join9(
4551
- ["extend schema", join9(directives, " "), block(operationTypes)],
4550
+ leave: ({ directives, operationTypes }) => join11(
4551
+ ["extend schema", join11(directives, " "), block(operationTypes)],
4552
4552
  " "
4553
4553
  )
4554
4554
  },
4555
4555
  ScalarTypeExtension: {
4556
- leave: ({ name, directives }) => join9(["extend scalar", name, join9(directives, " ")], " ")
4556
+ leave: ({ name, directives }) => join11(["extend scalar", name, join11(directives, " ")], " ")
4557
4557
  },
4558
4558
  ObjectTypeExtension: {
4559
- leave: ({ name, interfaces, directives, fields }) => join9(
4559
+ leave: ({ name, interfaces, directives, fields }) => join11(
4560
4560
  [
4561
4561
  "extend type",
4562
4562
  name,
4563
- wrap("implements ", join9(interfaces, " & ")),
4564
- join9(directives, " "),
4563
+ wrap("implements ", join11(interfaces, " & ")),
4564
+ join11(directives, " "),
4565
4565
  block(fields)
4566
4566
  ],
4567
4567
  " "
4568
4568
  )
4569
4569
  },
4570
4570
  InterfaceTypeExtension: {
4571
- leave: ({ name, interfaces, directives, fields }) => join9(
4571
+ leave: ({ name, interfaces, directives, fields }) => join11(
4572
4572
  [
4573
4573
  "extend interface",
4574
4574
  name,
4575
- wrap("implements ", join9(interfaces, " & ")),
4576
- join9(directives, " "),
4575
+ wrap("implements ", join11(interfaces, " & ")),
4576
+ join11(directives, " "),
4577
4577
  block(fields)
4578
4578
  ],
4579
4579
  " "
4580
4580
  )
4581
4581
  },
4582
4582
  UnionTypeExtension: {
4583
- leave: ({ name, directives, types }) => join9(
4583
+ leave: ({ name, directives, types }) => join11(
4584
4584
  [
4585
4585
  "extend union",
4586
4586
  name,
4587
- join9(directives, " "),
4588
- wrap("= ", join9(types, " | "))
4587
+ join11(directives, " "),
4588
+ wrap("= ", join11(types, " | "))
4589
4589
  ],
4590
4590
  " "
4591
4591
  )
4592
4592
  },
4593
4593
  EnumTypeExtension: {
4594
- leave: ({ name, directives, values }) => join9(["extend enum", name, join9(directives, " "), block(values)], " ")
4594
+ leave: ({ name, directives, values }) => join11(["extend enum", name, join11(directives, " "), block(values)], " ")
4595
4595
  },
4596
4596
  InputObjectTypeExtension: {
4597
- leave: ({ name, directives, fields }) => join9(["extend input", name, join9(directives, " "), block(fields)], " ")
4597
+ leave: ({ name, directives, fields }) => join11(["extend input", name, join11(directives, " "), block(fields)], " ")
4598
4598
  },
4599
4599
  DirectiveExtension: {
4600
- leave: ({ name, directives }) => join9(["extend directive @" + name, join9(directives, " ")], " ")
4600
+ leave: ({ name, directives }) => join11(["extend directive @" + name, join11(directives, " ")], " ")
4601
4601
  },
4602
4602
  // Schema Coordinates
4603
4603
  TypeCoordinate: {
4604
4604
  leave: ({ name }) => name
4605
4605
  },
4606
4606
  MemberCoordinate: {
4607
- leave: ({ name, memberName }) => join9([name, wrap(".", memberName)])
4607
+ leave: ({ name, memberName }) => join11([name, wrap(".", memberName)])
4608
4608
  },
4609
4609
  ArgumentCoordinate: {
4610
- leave: ({ name, fieldName, argumentName }) => join9([name, wrap(".", fieldName), wrap("(", argumentName, ":)")])
4610
+ leave: ({ name, fieldName, argumentName }) => join11([name, wrap(".", fieldName), wrap("(", argumentName, ":)")])
4611
4611
  },
4612
4612
  DirectiveCoordinate: {
4613
- leave: ({ name }) => join9(["@", name])
4613
+ leave: ({ name }) => join11(["@", name])
4614
4614
  },
4615
4615
  DirectiveArgumentCoordinate: {
4616
- leave: ({ name, argumentName }) => join9(["@", name, wrap("(", argumentName, ":)")])
4616
+ leave: ({ name, argumentName }) => join11(["@", name, wrap("(", argumentName, ":)")])
4617
4617
  }
4618
4618
  };
4619
- function join9(maybeArray, separator = "") {
4619
+ function join11(maybeArray, separator = "") {
4620
4620
  var _maybeArray$filter$jo;
4621
4621
  return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter((x) => x).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : "";
4622
4622
  }
4623
4623
  function block(array) {
4624
- return wrap("{\n", indent(join9(array, "\n")), "\n}");
4624
+ return wrap("{\n", indent(join11(array, "\n")), "\n}");
4625
4625
  }
4626
4626
  function wrap(start, maybeString, end = "") {
4627
4627
  return maybeString != null && maybeString !== "" ? start + maybeString + end : "";
@@ -12448,7 +12448,7 @@ var require_graphql = __commonJS({
12448
12448
  var _validate2 = require_validate2();
12449
12449
  var _execute = require_execute();
12450
12450
  function graphql(args) {
12451
- return new Promise((resolve6) => resolve6(graphqlImpl(args)));
12451
+ return new Promise((resolve8) => resolve8(graphqlImpl(args)));
12452
12452
  }
12453
12453
  function graphqlSync(args) {
12454
12454
  const result = graphqlImpl(args);
@@ -18869,7 +18869,7 @@ var IntrinsicFunctionResolver = class {
18869
18869
  this.logger.debug(
18870
18870
  `VPC ${physicalId} IPv6 CIDR still associating (attempt ${attempt}/${maxAttempts}), waiting...`
18871
18871
  );
18872
- await new Promise((resolve6) => setTimeout(resolve6, 2e3));
18872
+ await new Promise((resolve8) => setTimeout(resolve8, 2e3));
18873
18873
  }
18874
18874
  this.logger.warn(
18875
18875
  `VPC ${physicalId} IPv6 CIDR did not reach 'associated' state after ${maxAttempts} attempts`
@@ -19754,7 +19754,7 @@ var DagExecutor = class {
19754
19754
  async execute(concurrency, fn, cancelled = () => false) {
19755
19755
  let active = 0;
19756
19756
  const errors = [];
19757
- return new Promise((resolve6, reject) => {
19757
+ return new Promise((resolve8, reject) => {
19758
19758
  const dispatch = () => {
19759
19759
  let changed = true;
19760
19760
  while (changed) {
@@ -19816,7 +19816,7 @@ var DagExecutor = class {
19816
19816
  );
19817
19817
  return;
19818
19818
  }
19819
- resolve6();
19819
+ resolve8();
19820
19820
  }
19821
19821
  };
19822
19822
  dispatch();
@@ -20497,7 +20497,7 @@ Error: ${err.message || "Unknown error"}`,
20497
20497
  * Sleep for specified milliseconds
20498
20498
  */
20499
20499
  sleep(ms) {
20500
- return new Promise((resolve6) => setTimeout(resolve6, ms));
20500
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
20501
20501
  }
20502
20502
  /**
20503
20503
  * Check if a resource type is supported by Cloud Control API
@@ -21231,7 +21231,7 @@ var CustomResourceProvider = class _CustomResourceProvider {
21231
21231
  return result;
21232
21232
  }
21233
21233
  sleep(ms) {
21234
- return new Promise((resolve6) => setTimeout(resolve6, ms));
21234
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
21235
21235
  }
21236
21236
  /**
21237
21237
  * Adopt an existing custom resource into cdkd state.
@@ -21661,7 +21661,7 @@ function isRetryableTransientError(error, message) {
21661
21661
  }
21662
21662
 
21663
21663
  // src/deployment/retry.ts
21664
- var defaultSleep = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
21664
+ var defaultSleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
21665
21665
  async function withRetry(operation, logicalId, opts = {}) {
21666
21666
  const maxRetries = opts.maxRetries ?? 8;
21667
21667
  const initialDelayMs = opts.initialDelayMs ?? 1e3;
@@ -21716,7 +21716,7 @@ function validateOptions(opts) {
21716
21716
  async function withResourceDeadline(operation, opts) {
21717
21717
  validateOptions(opts);
21718
21718
  const startedAt = Date.now();
21719
- return new Promise((resolve6, reject) => {
21719
+ return new Promise((resolve8, reject) => {
21720
21720
  let settled = false;
21721
21721
  let warnTimer;
21722
21722
  let timeoutTimer;
@@ -21756,7 +21756,7 @@ async function withResourceDeadline(operation, opts) {
21756
21756
  return;
21757
21757
  settled = true;
21758
21758
  cleanup();
21759
- resolve6(value);
21759
+ resolve8(value);
21760
21760
  },
21761
21761
  (err) => {
21762
21762
  if (settled)
@@ -23791,7 +23791,7 @@ var AppExecutor = class {
23791
23791
  * Spawn subprocess and wait for completion
23792
23792
  */
23793
23793
  spawn(commandLine, env) {
23794
- return new Promise((resolve6, reject) => {
23794
+ return new Promise((resolve8, reject) => {
23795
23795
  const proc = spawn(commandLine, {
23796
23796
  stdio: ["ignore", "pipe", "pipe"],
23797
23797
  shell: true,
@@ -23817,7 +23817,7 @@ var AppExecutor = class {
23817
23817
  });
23818
23818
  proc.on("close", (code) => {
23819
23819
  if (code === 0) {
23820
- resolve6();
23820
+ resolve8();
23821
23821
  } else {
23822
23822
  const stderr = stderrChunks.join("\n");
23823
23823
  reject(
@@ -25323,14 +25323,14 @@ var FileAssetPublisher = class {
25323
25323
  * Upload a single file to S3
25324
25324
  */
25325
25325
  async uploadFile(client, filePath, bucket, key) {
25326
- const stat = statSync2(filePath);
25326
+ const stat4 = statSync2(filePath);
25327
25327
  const stream = createReadStream(filePath);
25328
25328
  await client.send(
25329
25329
  new PutObjectCommand2({
25330
25330
  Bucket: bucket,
25331
25331
  Key: key,
25332
25332
  Body: stream,
25333
- ContentLength: stat.size
25333
+ ContentLength: stat4.size
25334
25334
  })
25335
25335
  );
25336
25336
  }
@@ -25339,14 +25339,14 @@ var FileAssetPublisher = class {
25339
25339
  */
25340
25340
  async uploadZip(client, dirPath, bucket, key) {
25341
25341
  const archiver = await import("archiver");
25342
- const body = await new Promise((resolve6, reject) => {
25342
+ const body = await new Promise((resolve8, reject) => {
25343
25343
  const chunks = [];
25344
25344
  const archive = archiver.default("zip", { zlib: { level: 9 } });
25345
25345
  archive.on("data", (chunk) => chunks.push(chunk));
25346
- archive.on("end", () => resolve6(Buffer.concat(chunks)));
25346
+ archive.on("end", () => resolve8(Buffer.concat(chunks)));
25347
25347
  archive.on("error", reject);
25348
- const stat = statSync2(dirPath);
25349
- if (stat.isDirectory()) {
25348
+ const stat4 = statSync2(dirPath);
25349
+ if (stat4.isDirectory()) {
25350
25350
  archive.directory(dirPath, false);
25351
25351
  } else {
25352
25352
  archive.file(dirPath, { name: basename(dirPath) });
@@ -25528,7 +25528,7 @@ var DockerAssetPublisher = class {
25528
25528
  const token = Buffer.from(authData.authorizationToken, "base64").toString();
25529
25529
  const [username, password] = token.split(":");
25530
25530
  const endpoint = authData.proxyEndpoint || `https://${accountId}.dkr.ecr.${region}.amazonaws.com`;
25531
- await new Promise((resolve6, reject) => {
25531
+ await new Promise((resolve8, reject) => {
25532
25532
  const proc = spawn2(
25533
25533
  "docker",
25534
25534
  ["login", "--username", username, "--password-stdin", endpoint],
@@ -25542,7 +25542,7 @@ var DockerAssetPublisher = class {
25542
25542
  });
25543
25543
  proc.on("close", (code) => {
25544
25544
  if (code === 0) {
25545
- resolve6();
25545
+ resolve8();
25546
25546
  } else {
25547
25547
  reject(new AssetError(`ECR login failed: ${stderr.trim()}`));
25548
25548
  }
@@ -25595,7 +25595,7 @@ var WorkGraph = class {
25595
25595
  async execute(concurrency, fn) {
25596
25596
  const active = { "asset-build": 0, "asset-publish": 0, stack: 0 };
25597
25597
  const errors = [];
25598
- return new Promise((resolve6, reject) => {
25598
+ return new Promise((resolve8, reject) => {
25599
25599
  const dispatch = () => {
25600
25600
  const ready = [];
25601
25601
  for (const node of this.nodes.values()) {
@@ -25667,7 +25667,7 @@ ${msg}`
25667
25667
  );
25668
25668
  return;
25669
25669
  }
25670
- resolve6();
25670
+ resolve8();
25671
25671
  }
25672
25672
  };
25673
25673
  dispatch();
@@ -26658,7 +26658,7 @@ var LockManager = class {
26658
26658
  this.logger.info(
26659
26659
  `Stack '${stackName}' (${region}) is locked by ${lockInfo2.owner}${lockInfo2.operation ? ` (operation: ${lockInfo2.operation})` : ""}. Lock expires in ${this.formatDuration(remainingMs)}. Retrying in ${this.formatDuration(retryDelay)}... (attempt ${attempt + 1}/${maxRetries})`
26660
26660
  );
26661
- await new Promise((resolve6) => setTimeout(resolve6, retryDelay));
26661
+ await new Promise((resolve8) => setTimeout(resolve8, retryDelay));
26662
26662
  continue;
26663
26663
  }
26664
26664
  }
@@ -28356,8 +28356,8 @@ var IAMRoleProvider = class {
28356
28356
  const statePolicies = properties?.["Policies"] ?? [];
28357
28357
  const remaining = new Set(bodies.keys());
28358
28358
  const inline = [];
28359
- for (const sp of statePolicies) {
28360
- const name = sp?.PolicyName;
28359
+ for (const sp3 of statePolicies) {
28360
+ const name = sp3?.PolicyName;
28361
28361
  if (typeof name !== "string")
28362
28362
  continue;
28363
28363
  if (bodies.has(name)) {
@@ -30439,8 +30439,8 @@ var IAMUserGroupProvider = class {
30439
30439
  );
30440
30440
  const remaining = new Set(bodies.keys());
30441
30441
  const inline = [];
30442
- for (const sp of statePolicies) {
30443
- const name = sp?.PolicyName;
30442
+ for (const sp3 of statePolicies) {
30443
+ const name = sp3?.PolicyName;
30444
30444
  if (typeof name !== "string")
30445
30445
  continue;
30446
30446
  if (bodies.has(name)) {
@@ -30703,7 +30703,7 @@ var S3BucketProvider = class {
30703
30703
  * are equal, we skip the call entirely.
30704
30704
  */
30705
30705
  async applyTagDiff(bucketName, oldTagsRaw, newTagsRaw) {
30706
- const normalize = (tags) => {
30706
+ const normalize2 = (tags) => {
30707
30707
  const out = [];
30708
30708
  for (const t of tags ?? []) {
30709
30709
  if (t.Key !== void 0 && t.Value !== void 0)
@@ -30711,8 +30711,8 @@ var S3BucketProvider = class {
30711
30711
  }
30712
30712
  return out;
30713
30713
  };
30714
- const oldNorm = normalize(oldTagsRaw);
30715
- const newNorm = normalize(newTagsRaw);
30714
+ const oldNorm = normalize2(oldTagsRaw);
30715
+ const newNorm = normalize2(newTagsRaw);
30716
30716
  if (JSON.stringify(oldNorm) === JSON.stringify(newNorm))
30717
30717
  return;
30718
30718
  if (newNorm.length === 0) {
@@ -35152,7 +35152,7 @@ var LambdaFunctionProvider = class {
35152
35152
  return enis;
35153
35153
  }
35154
35154
  sleep(ms) {
35155
- return new Promise((resolve6) => setTimeout(resolve6, ms));
35155
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
35156
35156
  }
35157
35157
  /**
35158
35158
  * Build Lambda Code parameter from CDK properties
@@ -37029,7 +37029,7 @@ var DynamoDBTableProvider = class {
37029
37029
  if (status !== "CREATING") {
37030
37030
  throw new Error(`Unexpected table status: ${status}`);
37031
37031
  }
37032
- await new Promise((resolve6) => setTimeout(resolve6, 1e3));
37032
+ await new Promise((resolve8) => setTimeout(resolve8, 1e3));
37033
37033
  }
37034
37034
  throw new Error(`Table ${tableName} did not reach ACTIVE status within ${maxAttempts} seconds`);
37035
37035
  }
@@ -37049,7 +37049,7 @@ var DynamoDBTableProvider = class {
37049
37049
  if (status === "ACTIVE") {
37050
37050
  return;
37051
37051
  }
37052
- await new Promise((resolve6) => setTimeout(resolve6, 1e3));
37052
+ await new Promise((resolve8) => setTimeout(resolve8, 1e3));
37053
37053
  }
37054
37054
  throw new Error(
37055
37055
  `Table ${tableName} did not reach ACTIVE status within ${maxAttempts} seconds after UpdateTable`
@@ -38021,17 +38021,17 @@ var CloudWatchAlarmProvider = class {
38021
38021
  if (m["Period"] !== void 0)
38022
38022
  entry["Period"] = m["Period"];
38023
38023
  if (m["MetricStat"] !== void 0) {
38024
- const stat = m["MetricStat"];
38025
- const metric = stat["Metric"];
38024
+ const stat4 = m["MetricStat"];
38025
+ const metric = stat4["Metric"];
38026
38026
  entry["MetricStat"] = {
38027
38027
  Metric: {
38028
38028
  MetricName: metric["MetricName"],
38029
38029
  Namespace: metric["Namespace"],
38030
38030
  Dimensions: metric["Dimensions"]
38031
38031
  },
38032
- Period: stat["Period"],
38033
- Stat: stat["Stat"],
38034
- Unit: stat["Unit"]
38032
+ Period: stat4["Period"],
38033
+ Stat: stat4["Stat"],
38034
+ Unit: stat4["Unit"]
38035
38035
  };
38036
38036
  }
38037
38037
  return entry;
@@ -40229,7 +40229,7 @@ var EC2Provider = class {
40229
40229
  this.logger.debug(
40230
40230
  `VPC ${physicalId} has dependencies (attempt ${attempt}/${maxAttempts}), retrying in ${attempt * 5}s...`
40231
40231
  );
40232
- await new Promise((resolve6) => setTimeout(resolve6, attempt * 5e3));
40232
+ await new Promise((resolve8) => setTimeout(resolve8, attempt * 5e3));
40233
40233
  continue;
40234
40234
  }
40235
40235
  const cause = error instanceof Error ? error : void 0;
@@ -40393,7 +40393,7 @@ var EC2Provider = class {
40393
40393
  this.logger.debug(
40394
40394
  `Subnet ${physicalId} has dependencies (attempt ${attempt}/${maxAttempts}), retrying in ${attempt * 5}s...`
40395
40395
  );
40396
- await new Promise((resolve6) => setTimeout(resolve6, attempt * 5e3));
40396
+ await new Promise((resolve8) => setTimeout(resolve8, attempt * 5e3));
40397
40397
  continue;
40398
40398
  }
40399
40399
  const cause = error instanceof Error ? error : void 0;
@@ -41151,7 +41151,7 @@ var EC2Provider = class {
41151
41151
  this.logger.debug(
41152
41152
  `SecurityGroup ${physicalId} has dependent objects (attempt ${attempt}/${maxAttempts}), retrying in ${attempt * 5}s...`
41153
41153
  );
41154
- await new Promise((resolve6) => setTimeout(resolve6, attempt * 5e3));
41154
+ await new Promise((resolve8) => setTimeout(resolve8, attempt * 5e3));
41155
41155
  continue;
41156
41156
  }
41157
41157
  const cause = error instanceof Error ? error : void 0;
@@ -42095,7 +42095,7 @@ var EC2Provider = class {
42095
42095
  * `setTimeout` globally.
42096
42096
  */
42097
42097
  sleep(ms) {
42098
- return new Promise((resolve6) => setTimeout(resolve6, ms));
42098
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
42099
42099
  }
42100
42100
  /**
42101
42101
  * Check if an error indicates the resource was not found
@@ -42896,17 +42896,17 @@ function flattenIpPermissions(perms, direction) {
42896
42896
  rule["Description"] = grp.Description;
42897
42897
  out.push(rule);
42898
42898
  }
42899
- for (const pl of p.PrefixListIds ?? []) {
42899
+ for (const pl2 of p.PrefixListIds ?? []) {
42900
42900
  const rule = { ...base };
42901
42901
  if (direction === "ingress") {
42902
- if (pl.PrefixListId !== void 0)
42903
- rule["SourcePrefixListId"] = pl.PrefixListId;
42902
+ if (pl2.PrefixListId !== void 0)
42903
+ rule["SourcePrefixListId"] = pl2.PrefixListId;
42904
42904
  } else {
42905
- if (pl.PrefixListId !== void 0)
42906
- rule["DestinationPrefixListId"] = pl.PrefixListId;
42905
+ if (pl2.PrefixListId !== void 0)
42906
+ rule["DestinationPrefixListId"] = pl2.PrefixListId;
42907
42907
  }
42908
- if (pl.Description !== void 0)
42909
- rule["Description"] = pl.Description;
42908
+ if (pl2.Description !== void 0)
42909
+ rule["Description"] = pl2.Description;
42910
42910
  out.push(rule);
42911
42911
  }
42912
42912
  if ((p.IpRanges?.length ?? 0) === 0 && (p.Ipv6Ranges?.length ?? 0) === 0 && (p.UserIdGroupPairs?.length ?? 0) === 0 && (p.PrefixListIds?.length ?? 0) === 0) {
@@ -44195,7 +44195,7 @@ var ApiGatewayProvider = class _ApiGatewayProvider {
44195
44195
  * Sleep for specified milliseconds
44196
44196
  */
44197
44197
  sleep(ms) {
44198
- return new Promise((resolve6) => setTimeout(resolve6, ms));
44198
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
44199
44199
  }
44200
44200
  /**
44201
44201
  * Convert CloudFormation Tags (Array<{Key, Value}>) to SDK tags (Record<string, string>).
@@ -44850,8 +44850,8 @@ var ApiGatewayV2Provider = class {
44850
44850
  async createRoute(logicalId, resourceType, properties) {
44851
44851
  this.logger.debug(`Creating API Gateway V2 Route ${logicalId}`);
44852
44852
  const apiId = properties["ApiId"];
44853
- const routeKey = properties["RouteKey"];
44854
- if (!apiId || !routeKey) {
44853
+ const routeKey2 = properties["RouteKey"];
44854
+ if (!apiId || !routeKey2) {
44855
44855
  throw new ProvisioningError(
44856
44856
  `ApiId and RouteKey are required for API Gateway V2 Route ${logicalId}`,
44857
44857
  resourceType,
@@ -44862,7 +44862,7 @@ var ApiGatewayV2Provider = class {
44862
44862
  const response = await this.getClient().send(
44863
44863
  new CreateRouteCommand2({
44864
44864
  ApiId: apiId,
44865
- RouteKey: routeKey,
44865
+ RouteKey: routeKey2,
44866
44866
  Target: properties["Target"],
44867
44867
  AuthorizationType: properties["AuthorizationType"],
44868
44868
  AuthorizerId: properties["AuthorizerId"]
@@ -46087,7 +46087,7 @@ var CloudFrontDistributionProvider = class {
46087
46087
  );
46088
46088
  const sleepEnd = Date.now() + delay2;
46089
46089
  while (Date.now() < sleepEnd && !interrupted) {
46090
- await new Promise((resolve6) => setTimeout(resolve6, 1e3));
46090
+ await new Promise((resolve8) => setTimeout(resolve8, 1e3));
46091
46091
  }
46092
46092
  delay2 = Math.min(delay2 * 1.5, maxDelay);
46093
46093
  }
@@ -49899,7 +49899,7 @@ var RDSProvider = class {
49899
49899
  throw new Error(`Timed out waiting for DBInstance ${dbInstanceIdentifier} to be deleted`);
49900
49900
  }
49901
49901
  sleep(ms) {
49902
- return new Promise((resolve6) => setTimeout(resolve6, ms));
49902
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
49903
49903
  }
49904
49904
  /**
49905
49905
  * Adopt an existing RDS resource into cdkd state.
@@ -50884,7 +50884,7 @@ var DocDBProvider = class {
50884
50884
  throw new Error(`Timed out waiting for DocDB DBInstance ${dbInstanceIdentifier} to be deleted`);
50885
50885
  }
50886
50886
  sleep(ms) {
50887
- return new Promise((resolve6) => setTimeout(resolve6, ms));
50887
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
50888
50888
  }
50889
50889
  /**
50890
50890
  * Adopt an existing DocDB resource into cdkd state.
@@ -51874,7 +51874,7 @@ var NeptuneProvider = class {
51874
51874
  );
51875
51875
  }
51876
51876
  sleep(ms) {
51877
- return new Promise((resolve6) => setTimeout(resolve6, ms));
51877
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
51878
51878
  }
51879
51879
  /**
51880
51880
  * Adopt an existing Neptune resource into cdkd state.
@@ -54414,7 +54414,7 @@ var ElastiCacheProvider = class {
54414
54414
  throw new Error(`Timed out waiting for CacheCluster ${cacheClusterId} to be deleted`);
54415
54415
  }
54416
54416
  sleep(ms) {
54417
- return new Promise((resolve6) => setTimeout(resolve6, ms));
54417
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
54418
54418
  }
54419
54419
  /**
54420
54420
  * Read the AWS-current ElastiCache resource configuration in CFn-property shape.
@@ -55129,7 +55129,7 @@ var ServiceDiscoveryProvider = class {
55129
55129
  logicalId
55130
55130
  );
55131
55131
  }
55132
- await new Promise((resolve6) => setTimeout(resolve6, delay2));
55132
+ await new Promise((resolve8) => setTimeout(resolve8, delay2));
55133
55133
  delay2 = Math.min(delay2 * 2, 1e4);
55134
55134
  }
55135
55135
  throw new ProvisioningError(
@@ -59654,7 +59654,7 @@ var KinesisStreamProvider = class {
59654
59654
  if (status !== "CREATING" && status !== "UPDATING") {
59655
59655
  throw new Error(`Unexpected stream status: ${status}`);
59656
59656
  }
59657
- await new Promise((resolve6) => setTimeout(resolve6, 2e3));
59657
+ await new Promise((resolve8) => setTimeout(resolve8, 2e3));
59658
59658
  }
59659
59659
  throw new Error(
59660
59660
  `Stream ${streamName} did not reach ACTIVE status within ${maxAttempts * 2} seconds`
@@ -59987,7 +59987,7 @@ var KinesisStreamConsumerProvider = class {
59987
59987
  if (status !== "CREATING") {
59988
59988
  throw new Error(`Unexpected consumer status: ${status}`);
59989
59989
  }
59990
- await new Promise((resolve6) => setTimeout(resolve6, 1e3));
59990
+ await new Promise((resolve8) => setTimeout(resolve8, 1e3));
59991
59991
  }
59992
59992
  throw new Error(
59993
59993
  `Consumer ${consumerArn} did not reach ACTIVE status within ${maxAttempts} seconds`
@@ -60292,7 +60292,7 @@ var EFSProvider = class {
60292
60292
  this.logger.debug(
60293
60293
  `FileSystem ${fileSystemId} state: ${fs?.LifeCycleState ?? "unknown"}, waiting...`
60294
60294
  );
60295
- await new Promise((resolve6) => setTimeout(resolve6, pollIntervalMs));
60295
+ await new Promise((resolve8) => setTimeout(resolve8, pollIntervalMs));
60296
60296
  }
60297
60297
  throw new ProvisioningError(
60298
60298
  `Timed out waiting for EFS FileSystem ${fileSystemId} to become available (60s)`,
@@ -60370,7 +60370,7 @@ var EFSProvider = class {
60370
60370
  this.logger.debug(
60371
60371
  `MountTarget ${mountTargetId} state: ${mountTarget?.LifeCycleState ?? "unknown"}, waiting...`
60372
60372
  );
60373
- await new Promise((resolve6) => setTimeout(resolve6, pollIntervalMs));
60373
+ await new Promise((resolve8) => setTimeout(resolve8, pollIntervalMs));
60374
60374
  }
60375
60375
  throw new ProvisioningError(
60376
60376
  `Timed out waiting for EFS MountTarget ${mountTargetId} to become available (120s)`,
@@ -60436,7 +60436,7 @@ var EFSProvider = class {
60436
60436
  }
60437
60437
  throw error;
60438
60438
  }
60439
- await new Promise((resolve6) => setTimeout(resolve6, pollIntervalMs));
60439
+ await new Promise((resolve8) => setTimeout(resolve8, pollIntervalMs));
60440
60440
  }
60441
60441
  this.logger.warn(
60442
60442
  `Timed out waiting for EFS MountTarget ${mountTargetId} deletion for ${logicalId} (120s)`
@@ -61394,7 +61394,7 @@ var FirehoseProvider = class {
61394
61394
  this.logger.debug(
61395
61395
  `Firehose ${logicalId} status: ${status} (attempt ${attempt}/${maxAttempts})`
61396
61396
  );
61397
- await new Promise((resolve6) => setTimeout(resolve6, 2e3));
61397
+ await new Promise((resolve8) => setTimeout(resolve8, 2e3));
61398
61398
  }
61399
61399
  this.logger.warn(`Firehose ${logicalId} did not reach ACTIVE after ${maxAttempts} attempts`);
61400
61400
  }
@@ -64864,7 +64864,7 @@ var ASGProvider = class {
64864
64864
  );
64865
64865
  }
64866
64866
  sleep(ms) {
64867
- return new Promise((resolve6) => setTimeout(resolve6, ms));
64867
+ return new Promise((resolve8) => setTimeout(resolve8, ms));
64868
64868
  }
64869
64869
  // ─── Sub-shape diff helpers ───────────────────────────────────────
64870
64870
  // Each helper is a no-op when before/after JSON is identical (the cheap
@@ -66804,7 +66804,7 @@ Acquiring lock for stack ${stackName}...`);
66804
66804
  logger.debug(
66805
66805
  ` \u23F3 Retrying delete ${logicalId} in ${delay2 / 1e3}s (attempt ${attempt + 1}/${maxAttempts})`
66806
66806
  );
66807
- await new Promise((resolve6) => setTimeout(resolve6, delay2));
66807
+ await new Promise((resolve8) => setTimeout(resolve8, delay2));
66808
66808
  }
66809
66809
  }
66810
66810
  if (lastDeleteError)
@@ -70036,7 +70036,7 @@ async function captureObservedForImportedResources(stackState, providerRegistry,
70036
70036
  // src/cli/commands/local-invoke.ts
70037
70037
  import { cpSync as cpSync2, mkdtempSync as mkdtempSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync7, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "node:fs";
70038
70038
  import { tmpdir as tmpdir3 } from "node:os";
70039
- import { dirname as dirname3 } from "node:path";
70039
+ import { dirname as dirname5 } from "node:path";
70040
70040
  import * as path2 from "node:path";
70041
70041
  import { Command as Command15, Option as Option8 } from "commander";
70042
70042
 
@@ -70855,7 +70855,7 @@ async function ecrLogin(client, accountId, region) {
70855
70855
  const token = Buffer.from(authData.authorizationToken, "base64").toString();
70856
70856
  const [username, password] = token.split(":");
70857
70857
  const endpoint = authData.proxyEndpoint || `https://${accountId}.dkr.ecr.${region}.amazonaws.com`;
70858
- await new Promise((resolve6, reject) => {
70858
+ await new Promise((resolve8, reject) => {
70859
70859
  const proc = spawn4("docker", ["login", "--username", username, "--password-stdin", endpoint], {
70860
70860
  stdio: ["pipe", "pipe", "pipe"]
70861
70861
  });
@@ -70865,7 +70865,7 @@ async function ecrLogin(client, accountId, region) {
70865
70865
  });
70866
70866
  proc.on("close", (code) => {
70867
70867
  if (code === 0)
70868
- resolve6();
70868
+ resolve8();
70869
70869
  else
70870
70870
  reject(new LocalInvokeBuildError(`ECR login failed: ${stderr.trim()}`));
70871
70871
  });
@@ -70894,12 +70894,12 @@ async function isImageInLocalCache(imageRef) {
70894
70894
  }
70895
70895
  }
70896
70896
  function runForeground2(cmd, args) {
70897
- return new Promise((resolve6, reject) => {
70897
+ return new Promise((resolve8, reject) => {
70898
70898
  const proc = spawn4(cmd, args, { stdio: "inherit" });
70899
70899
  proc.on("error", (err) => reject(new LocalInvokeBuildError(`${cmd} failed: ${err.message}`)));
70900
70900
  proc.on("close", (code) => {
70901
70901
  if (code === 0)
70902
- resolve6();
70902
+ resolve8();
70903
70903
  else
70904
70904
  reject(new LocalInvokeBuildError(`${cmd} exited with code ${code}`));
70905
70905
  });
@@ -71246,6 +71246,7 @@ function discoverRestV1Method(logicalId, resource, template, stackName) {
71246
71246
  source: "rest-v1",
71247
71247
  apiVersion: "v1",
71248
71248
  stage,
71249
+ apiLogicalId: restApiLogicalId,
71249
71250
  declaredAt: `${stackName}/${logicalId}`
71250
71251
  }
71251
71252
  ];
@@ -71342,8 +71343,8 @@ function discoverHttpApiRoute(logicalId, resource, template, stackName) {
71342
71343
  );
71343
71344
  }
71344
71345
  }
71345
- const routeKey = props["RouteKey"];
71346
- if (typeof routeKey !== "string" || routeKey.length === 0) {
71346
+ const routeKey2 = props["RouteKey"];
71347
+ if (typeof routeKey2 !== "string" || routeKey2.length === 0) {
71347
71348
  throw new Error(
71348
71349
  `${stackName}/${logicalId} (AWS::ApiGatewayV2::Route): RouteKey must be a string`
71349
71350
  );
@@ -71379,7 +71380,7 @@ function discoverHttpApiRoute(logicalId, resource, template, stackName) {
71379
71380
  integrationProps["IntegrationUri"],
71380
71381
  `${stackName}/${integrationLogicalId}.IntegrationUri`
71381
71382
  );
71382
- const { method, pathPattern } = parseRouteKey(routeKey);
71383
+ const { method, pathPattern } = parseRouteKey(routeKey2);
71383
71384
  return [
71384
71385
  {
71385
71386
  method,
@@ -71388,6 +71389,7 @@ function discoverHttpApiRoute(logicalId, resource, template, stackName) {
71388
71389
  source: "http-api",
71389
71390
  apiVersion: "v2",
71390
71391
  stage: "$default",
71392
+ apiLogicalId,
71391
71393
  declaredAt: `${stackName}/${logicalId}`
71392
71394
  }
71393
71395
  ];
@@ -71438,9 +71440,9 @@ function resolveLambdaArnIntrinsic(value, location) {
71438
71440
  }
71439
71441
  }
71440
71442
  if ("Fn::Join" in obj) {
71441
- const join9 = obj["Fn::Join"];
71442
- if (Array.isArray(join9) && join9.length === 2 && Array.isArray(join9[1])) {
71443
- const parts = join9[1];
71443
+ const join11 = obj["Fn::Join"];
71444
+ if (Array.isArray(join11) && join11.length === 2 && Array.isArray(join11[1])) {
71445
+ const parts = join11[1];
71444
71446
  const literalParts = parts.filter((p) => typeof p === "string").join("");
71445
71447
  if (literalParts.includes(":lambda:path/2015-03-31/functions/")) {
71446
71448
  for (const p of parts) {
@@ -71471,10 +71473,10 @@ function parseHttpApiTargetIntegration(target, location) {
71471
71473
  }
71472
71474
  if (target && typeof target === "object" && !Array.isArray(target)) {
71473
71475
  const obj = target;
71474
- const join9 = obj["Fn::Join"];
71475
- if (Array.isArray(join9) && join9.length === 2 && Array.isArray(join9[1])) {
71476
- const sep = join9[0];
71477
- const parts = join9[1];
71476
+ const join11 = obj["Fn::Join"];
71477
+ if (Array.isArray(join11) && join11.length === 2 && Array.isArray(join11[1])) {
71478
+ const sep = join11[0];
71479
+ const parts = join11[1];
71478
71480
  if (sep === "/" && parts.length === 2 && parts[0] === "integrations") {
71479
71481
  const ref = pickRefLogicalId(parts[1]);
71480
71482
  if (ref)
@@ -71493,14 +71495,14 @@ function parseHttpApiTargetIntegration(target, location) {
71493
71495
  )}).`
71494
71496
  );
71495
71497
  }
71496
- function parseRouteKey(routeKey) {
71497
- if (routeKey === "$default") {
71498
+ function parseRouteKey(routeKey2) {
71499
+ if (routeKey2 === "$default") {
71498
71500
  return { method: "ANY", pathPattern: "$default" };
71499
71501
  }
71500
- const m = /^([A-Za-z]+)\s+(\S+)$/.exec(routeKey);
71502
+ const m = /^([A-Za-z]+)\s+(\S+)$/.exec(routeKey2);
71501
71503
  if (!m) {
71502
71504
  throw new Error(
71503
- `RouteKey '${routeKey}' is malformed: expected '<METHOD> <path>' (e.g. 'GET /items/{id}') or '$default'.`
71505
+ `RouteKey '${routeKey2}' is malformed: expected '<METHOD> <path>' (e.g. 'GET /items/{id}') or '$default'.`
71504
71506
  );
71505
71507
  }
71506
71508
  return { method: m[1].toUpperCase(), pathPattern: m[2] };
@@ -71532,6 +71534,7 @@ function createContainerPool(specs, options) {
71532
71534
  const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
71533
71535
  const streamingEnabled = options.streamLogs !== false;
71534
71536
  const entries = /* @__PURE__ */ new Map();
71537
+ let disposed = false;
71535
71538
  const inFlightStarts = /* @__PURE__ */ new Set();
71536
71539
  for (const logicalId of specs.keys()) {
71537
71540
  entries.set(logicalId, emptyEntry(logicalId));
@@ -71543,7 +71546,8 @@ function createContainerPool(specs, options) {
71543
71546
  inUse: /* @__PURE__ */ new Set(),
71544
71547
  waitQueue: [],
71545
71548
  idleTimer: null,
71546
- growthMutex: Promise.resolve()
71549
+ growthMutex: Promise.resolve(),
71550
+ drainResolvers: []
71547
71551
  };
71548
71552
  }
71549
71553
  async function startOne(spec) {
@@ -71680,6 +71684,18 @@ function createContainerPool(specs, options) {
71680
71684
  if (!entry)
71681
71685
  return;
71682
71686
  entry.inUse.delete(handle);
71687
+ if (disposed) {
71688
+ entry.warm.push(handle);
71689
+ if (entry.inUse.size === 0) {
71690
+ for (const resolve8 of entry.drainResolvers.splice(0, entry.drainResolvers.length)) {
71691
+ try {
71692
+ resolve8();
71693
+ } catch {
71694
+ }
71695
+ }
71696
+ }
71697
+ return;
71698
+ }
71683
71699
  const waiter = entry.waitQueue.shift();
71684
71700
  if (waiter) {
71685
71701
  entry.inUse.add(handle);
@@ -71688,10 +71704,22 @@ function createContainerPool(specs, options) {
71688
71704
  }
71689
71705
  entry.warm.push(handle);
71690
71706
  resetIdleTimer(entry);
71707
+ if (entry.inUse.size === 0 && entry.drainResolvers.length > 0) {
71708
+ for (const resolve8 of entry.drainResolvers.splice(0, entry.drainResolvers.length)) {
71709
+ try {
71710
+ resolve8();
71711
+ } catch {
71712
+ }
71713
+ }
71714
+ }
71691
71715
  },
71692
71716
  async dispose() {
71717
+ if (disposed) {
71718
+ logger.debug("Container pool dispose() called more than once; ignoring");
71719
+ return;
71720
+ }
71721
+ disposed = true;
71693
71722
  logger.debug("Disposing container pool");
71694
- const allHandles = [];
71695
71723
  for (const entry of entries.values()) {
71696
71724
  if (entry.idleTimer) {
71697
71725
  clearTimeout(entry.idleTimer);
@@ -71705,6 +71733,43 @@ function createContainerPool(specs, options) {
71705
71733
  } catch {
71706
71734
  }
71707
71735
  }
71736
+ }
71737
+ const drainTimeoutMs = 3e4;
71738
+ const drainStart = Date.now();
71739
+ const entryDrains = [];
71740
+ for (const entry of entries.values()) {
71741
+ if (entry.inUse.size === 0)
71742
+ continue;
71743
+ entryDrains.push(
71744
+ new Promise((resolveDrain) => {
71745
+ entry.drainResolvers.push(() => resolveDrain({ entry, timedOut: false }));
71746
+ const t = setTimeout(() => {
71747
+ resolveDrain({ entry, timedOut: true });
71748
+ }, drainTimeoutMs);
71749
+ t.unref?.();
71750
+ })
71751
+ );
71752
+ }
71753
+ if (entryDrains.length > 0) {
71754
+ logger.debug(
71755
+ `Waiting for ${entryDrains.length} entry/entries' in-flight handle(s) to drain before teardown`
71756
+ );
71757
+ const drainResults = await Promise.all(entryDrains);
71758
+ let anyTimedOut = false;
71759
+ for (const r of drainResults) {
71760
+ if (r.timedOut) {
71761
+ anyTimedOut = true;
71762
+ logger.warn(
71763
+ `Container pool dispose timed out waiting for ${r.entry.inUse.size} in-flight handle(s) on ${r.entry.logicalId} after ${drainTimeoutMs}ms; tearing down anyway. The verify.sh \`docker rm -f cdkd-local-*\` sweep is the safety net.`
71764
+ );
71765
+ }
71766
+ }
71767
+ if (!anyTimedOut) {
71768
+ logger.debug(`In-flight drain completed in ${Date.now() - drainStart}ms`);
71769
+ }
71770
+ }
71771
+ const allHandles = [];
71772
+ for (const entry of entries.values()) {
71708
71773
  allHandles.push(...entry.warm.splice(0, entry.warm.length));
71709
71774
  for (const h of entry.inUse)
71710
71775
  allHandles.push(h);
@@ -71715,12 +71780,12 @@ function createContainerPool(specs, options) {
71715
71780
  logger.debug(
71716
71781
  `Waiting for ${startPromises.length} in-flight container start(s) to settle before teardown`
71717
71782
  );
71718
- const drainTimeoutMs = 5e3;
71783
+ const drainTimeoutMs2 = 5e3;
71719
71784
  const wrapped = startPromises.map(
71720
71785
  (p) => Promise.race([
71721
71786
  p.then((h) => ({ kind: "ok", handle: h })),
71722
71787
  new Promise((r) => {
71723
- const t = setTimeout(() => r({ kind: "timeout" }), drainTimeoutMs);
71788
+ const t = setTimeout(() => r({ kind: "timeout" }), drainTimeoutMs2);
71724
71789
  t.unref?.();
71725
71790
  })
71726
71791
  ]).catch((err) => {
@@ -71741,7 +71806,7 @@ function createContainerPool(specs, options) {
71741
71806
  }
71742
71807
  if (timedOut > 0) {
71743
71808
  logger.warn(
71744
- `Container pool disposed with ${timedOut} in-flight start(s) still pending after ${drainTimeoutMs}ms; relying on docker --rm + the verify.sh sweep to clean up.`
71809
+ `Container pool disposed with ${timedOut} in-flight start(s) still pending after ${drainTimeoutMs2}ms; relying on docker --rm + the verify.sh sweep to clean up.`
71745
71810
  );
71746
71811
  }
71747
71812
  inFlightStarts.clear();
@@ -71777,17 +71842,20 @@ function buildHttpApiV2Event(req, ctx, opts = {}) {
71777
71842
  const contentType = headers["content-type"] ?? "";
71778
71843
  const { body, isBase64Encoded } = encodeBody(req.body, contentType);
71779
71844
  const now = opts.now ? opts.now() : /* @__PURE__ */ new Date();
71780
- const routeKey = ctx.route.pathPattern === "$default" ? "$default" : `${ctx.route.method} ${ctx.route.pathPattern}`;
71845
+ const routeKey2 = ctx.route.pathPattern === "$default" ? "$default" : `${ctx.route.method} ${ctx.route.pathPattern}`;
71781
71846
  const event = {
71782
71847
  version: "2.0",
71783
- routeKey,
71848
+ routeKey: routeKey2,
71784
71849
  rawPath,
71785
71850
  rawQueryString,
71786
71851
  cookies,
71787
71852
  headers,
71788
71853
  queryStringParameters,
71789
71854
  pathParameters: decodePathParameters(ctx.pathParameters),
71790
- stageVariables: null,
71855
+ // PR 8c: surface the route's resolved Stage Variables (or `null`
71856
+ // for routes without a Stage — Function URLs, plus HTTP API routes
71857
+ // when no Stage with matching variables was attached).
71858
+ stageVariables: ctx.route.stageVariables ?? null,
71791
71859
  requestContext: {
71792
71860
  accountId: MOCK_ACCOUNT_ID,
71793
71861
  apiId: MOCK_API_ID,
@@ -71801,7 +71869,7 @@ function buildHttpApiV2Event(req, ctx, opts = {}) {
71801
71869
  userAgent
71802
71870
  },
71803
71871
  requestId: randomUUID(),
71804
- routeKey,
71872
+ routeKey: routeKey2,
71805
71873
  stage: ctx.route.stage,
71806
71874
  time: formatRequestTime(now),
71807
71875
  timeEpoch: now.getTime(),
@@ -71830,7 +71898,10 @@ function buildRestV1Event(req, ctx, opts = {}) {
71830
71898
  queryStringParameters: Object.keys(queryStringParameters).length > 0 ? queryStringParameters : null,
71831
71899
  multiValueQueryStringParameters: Object.keys(multiValueQueryStringParameters).length > 0 ? multiValueQueryStringParameters : null,
71832
71900
  pathParameters: Object.keys(pathParams).length > 0 ? pathParams : null,
71833
- stageVariables: null,
71901
+ // PR 8c: surface the route's resolved Stage Variables (or `null`).
71902
+ // REST v1 hardcoded `null` pre-PR; with `attachStageContext` the
71903
+ // route now carries the deployed Stage's `Variables` map.
71904
+ stageVariables: ctx.route.stageVariables ?? null,
71834
71905
  requestContext: {
71835
71906
  accountId: MOCK_ACCOUNT_ID,
71836
71907
  apiId: MOCK_API_ID,
@@ -72263,6 +72334,143 @@ function isPlaceholder(segment) {
72263
72334
  return /^\{[^/{}+]+\}$/.test(segment);
72264
72335
  }
72265
72336
 
72337
+ // src/local/cors-handler.ts
72338
+ function buildCorsConfigByApiId(template) {
72339
+ const out = /* @__PURE__ */ new Map();
72340
+ const resources = template.Resources ?? {};
72341
+ for (const [logicalId, resource] of Object.entries(resources)) {
72342
+ if (resource.Type !== "AWS::ApiGatewayV2::Api")
72343
+ continue;
72344
+ const props = resource.Properties ?? {};
72345
+ const raw = props["CorsConfiguration"];
72346
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
72347
+ continue;
72348
+ const parsed = parseCorsConfiguration(raw);
72349
+ if (parsed)
72350
+ out.set(logicalId, parsed);
72351
+ }
72352
+ return out;
72353
+ }
72354
+ function parseCorsConfiguration(raw) {
72355
+ const allowOrigins = pickStringArray(raw["AllowOrigins"]);
72356
+ const allowMethods = pickStringArray(raw["AllowMethods"]);
72357
+ const allowHeaders = pickStringArray(raw["AllowHeaders"]);
72358
+ const exposeHeaders = pickStringArray(raw["ExposeHeaders"]);
72359
+ const maxAgeRaw = raw["MaxAge"];
72360
+ const allowCreds = raw["AllowCredentials"];
72361
+ if (allowOrigins.length === 0 && allowMethods.length === 0 && allowHeaders.length === 0 && exposeHeaders.length === 0 && maxAgeRaw === void 0 && allowCreds === void 0) {
72362
+ return void 0;
72363
+ }
72364
+ const config = {
72365
+ AllowOrigins: allowOrigins,
72366
+ AllowMethods: allowMethods,
72367
+ AllowHeaders: allowHeaders,
72368
+ ExposeHeaders: exposeHeaders
72369
+ };
72370
+ if (typeof maxAgeRaw === "number" && Number.isFinite(maxAgeRaw)) {
72371
+ config.MaxAge = Math.trunc(maxAgeRaw);
72372
+ }
72373
+ if (typeof allowCreds === "boolean") {
72374
+ config.AllowCredentials = allowCreds;
72375
+ }
72376
+ return config;
72377
+ }
72378
+ function pickStringArray(value) {
72379
+ if (!Array.isArray(value))
72380
+ return [];
72381
+ const out = [];
72382
+ for (const v of value)
72383
+ if (typeof v === "string")
72384
+ out.push(v);
72385
+ return out;
72386
+ }
72387
+ function matchPreflight(req, config) {
72388
+ if (req.method.toUpperCase() !== "OPTIONS")
72389
+ return null;
72390
+ const headersLower = {};
72391
+ for (const [name, values] of Object.entries(req.headers)) {
72392
+ if (values.length === 0)
72393
+ continue;
72394
+ headersLower[name.toLowerCase()] = values.join(",");
72395
+ }
72396
+ const origin = headersLower["origin"];
72397
+ const requestedMethod = headersLower["access-control-request-method"];
72398
+ if (!origin || !requestedMethod) {
72399
+ return null;
72400
+ }
72401
+ const originMatch = matchOrigin(origin, config.AllowOrigins);
72402
+ if (!originMatch)
72403
+ return null;
72404
+ const methodMatch = matchToken(requestedMethod, config.AllowMethods);
72405
+ if (!methodMatch)
72406
+ return null;
72407
+ const requestedHeaders = headersLower["access-control-request-headers"] ?? "";
72408
+ if (!matchHeaderList(requestedHeaders, config.AllowHeaders))
72409
+ return null;
72410
+ const responseHeaders = {
72411
+ "access-control-allow-origin": originMatch === "*" ? "*" : origin,
72412
+ "access-control-allow-methods": methodMatch === "*" ? requestedMethod : methodMatch
72413
+ };
72414
+ if (requestedHeaders.length > 0) {
72415
+ responseHeaders["access-control-allow-headers"] = requestedHeaders;
72416
+ } else if (config.AllowHeaders.length > 0 && !config.AllowHeaders.includes("*")) {
72417
+ responseHeaders["access-control-allow-headers"] = config.AllowHeaders.join(",");
72418
+ }
72419
+ if (config.ExposeHeaders.length > 0) {
72420
+ responseHeaders["access-control-expose-headers"] = config.ExposeHeaders.join(",");
72421
+ }
72422
+ if (config.MaxAge !== void 0) {
72423
+ responseHeaders["access-control-max-age"] = String(config.MaxAge);
72424
+ }
72425
+ if (config.AllowCredentials === true) {
72426
+ responseHeaders["access-control-allow-origin"] = origin;
72427
+ responseHeaders["access-control-allow-credentials"] = "true";
72428
+ }
72429
+ responseHeaders["vary"] = "Origin";
72430
+ return { statusCode: 204, headers: responseHeaders };
72431
+ }
72432
+ function matchOrigin(requestOrigin, allowOrigins) {
72433
+ if (allowOrigins.length === 0)
72434
+ return null;
72435
+ if (allowOrigins.includes("*"))
72436
+ return "*";
72437
+ for (const allowed of allowOrigins) {
72438
+ if (allowed === requestOrigin)
72439
+ return allowed;
72440
+ }
72441
+ return null;
72442
+ }
72443
+ function matchToken(token, allowed) {
72444
+ if (allowed.length === 0)
72445
+ return null;
72446
+ if (allowed.includes("*"))
72447
+ return "*";
72448
+ const lower = token.toLowerCase();
72449
+ for (const a of allowed) {
72450
+ if (a.toLowerCase() === lower)
72451
+ return a;
72452
+ }
72453
+ return null;
72454
+ }
72455
+ function matchHeaderList(headerList, allowed) {
72456
+ const trimmed = headerList.trim();
72457
+ if (trimmed.length === 0)
72458
+ return true;
72459
+ if (allowed.includes("*"))
72460
+ return true;
72461
+ if (allowed.length === 0)
72462
+ return false;
72463
+ const allowedLower = new Set(allowed.map((s) => s.toLowerCase()));
72464
+ for (const entry of trimmed.split(",")) {
72465
+ const e = entry.trim().toLowerCase();
72466
+ if (e.length === 0)
72467
+ return false;
72468
+ if (!allowedLower.has(e))
72469
+ return false;
72470
+ }
72471
+ return true;
72472
+ }
72473
+
72266
72474
  // src/local/authorizer-resolver.ts
72267
72475
  function resolveRestV1Authorizer(authorizerLogicalId, template, stackName, declaredAt) {
72268
72476
  const authResource = template.Resources?.[authorizerLogicalId];
@@ -72399,9 +72607,9 @@ function resolveLambdaArn(value, location) {
72399
72607
  }
72400
72608
  }
72401
72609
  if ("Fn::Join" in obj) {
72402
- const join9 = obj["Fn::Join"];
72403
- if (Array.isArray(join9) && join9.length === 2 && Array.isArray(join9[1])) {
72404
- const parts = join9[1];
72610
+ const join11 = obj["Fn::Join"];
72611
+ if (Array.isArray(join11) && join11.length === 2 && Array.isArray(join11[1])) {
72612
+ const parts = join11[1];
72405
72613
  const literal = parts.filter((p) => typeof p === "string").join("");
72406
72614
  if (literal.includes(":lambda:path/2015-03-31/functions/")) {
72407
72615
  for (const p of parts) {
@@ -73075,8 +73283,9 @@ function base64UrlDecodeToBuffer(input) {
73075
73283
  // src/local/http-server.ts
73076
73284
  async function startApiServer(opts) {
73077
73285
  const logger = getLogger().child("start-api");
73286
+ let currentState = opts.state;
73078
73287
  const server = createServer2((req, res) => {
73079
- handleRequest(req, res, opts).catch((err) => {
73288
+ handleRequest(req, res, currentState, opts).catch((err) => {
73080
73289
  logger.error(
73081
73290
  `Unhandled request error: ${err instanceof Error ? err.stack ?? err.message : String(err)}`
73082
73291
  );
@@ -73114,22 +73323,31 @@ async function startApiServer(opts) {
73114
73323
  server.close(() => resolveClose());
73115
73324
  server.closeAllConnections?.();
73116
73325
  });
73117
- }
73326
+ },
73327
+ setServerState: (next) => {
73328
+ const prev = currentState;
73329
+ currentState = next;
73330
+ return prev;
73331
+ },
73332
+ getServerState: () => currentState
73118
73333
  };
73119
73334
  }
73120
- async function handleRequest(req, res, opts) {
73335
+ async function handleRequest(req, res, state, opts) {
73121
73336
  const logger = getLogger().child("start-api");
73122
73337
  const bodyBuf = await readBody(req);
73123
73338
  const rawUrl = req.url ?? "/";
73124
73339
  const method = (req.method ?? "GET").toUpperCase();
73125
73340
  const requestPath = rawUrl.split("?")[0] ?? "/";
73126
- const flatRoutes = opts.routes.map((r) => r.route);
73341
+ const preflightHandled = method === "OPTIONS" ? maybeHandleCorsPreflight(req, res, requestPath, state) : false;
73342
+ if (preflightHandled)
73343
+ return;
73344
+ const flatRoutes = state.routes.map((r) => r.route);
73127
73345
  const match = matchRoute(method, requestPath, flatRoutes);
73128
73346
  if (!match) {
73129
73347
  writeError(res, 404, '{"message":"Not Found"}');
73130
73348
  return;
73131
73349
  }
73132
- const matchedEntry = opts.routes.find(
73350
+ const matchedEntry = state.routes.find(
73133
73351
  (r) => r.route.declaredAt === match.route.declaredAt && r.route.method === match.route.method
73134
73352
  );
73135
73353
  const authorizer = matchedEntry?.authorizer;
@@ -73154,6 +73372,7 @@ async function handleRequest(req, res, opts) {
73154
73372
  authorizer,
73155
73373
  snapshot,
73156
73374
  matchCtx,
73375
+ state,
73157
73376
  opts,
73158
73377
  baseEvent["requestContext"]
73159
73378
  );
@@ -73176,7 +73395,7 @@ async function handleRequest(req, res, opts) {
73176
73395
  }
73177
73396
  let handle;
73178
73397
  try {
73179
- handle = await opts.pool.acquire(match.route.lambdaLogicalId);
73398
+ handle = await state.pool.acquire(match.route.lambdaLogicalId);
73180
73399
  } catch (err) {
73181
73400
  logger.error(
73182
73401
  `Failed to acquire container for ${match.route.lambdaLogicalId}: ${err instanceof Error ? err.message : String(err)}`
@@ -73210,10 +73429,85 @@ async function handleRequest(req, res, opts) {
73210
73429
  res.end();
73211
73430
  }
73212
73431
  } finally {
73213
- opts.pool.release(handle);
73432
+ state.pool.release(handle);
73433
+ }
73434
+ }
73435
+ function maybeHandleCorsPreflight(req, res, requestPath, state) {
73436
+ if (state.corsConfigByApiId.size === 0)
73437
+ return false;
73438
+ const headers = collectHeaders(req);
73439
+ const requestedMethodHeader = pickFirstHeaderValue(headers, "access-control-request-method");
73440
+ if (!requestedMethodHeader)
73441
+ return false;
73442
+ const flatRoutes = state.routes.map((r) => r.route);
73443
+ const surrogateMatch = matchRoute(requestedMethodHeader, requestPath, flatRoutes);
73444
+ if (!surrogateMatch)
73445
+ return false;
73446
+ const route = surrogateMatch.route;
73447
+ if (route.apiVersion !== "v2" || !route.apiLogicalId)
73448
+ return false;
73449
+ const surrogateApiId = route.apiLogicalId;
73450
+ const explicitOptionsRoute = flatRoutes.find(
73451
+ (r) => r.apiLogicalId === surrogateApiId && r.method.toUpperCase() === "OPTIONS" && pathPatternMatchesPath(r.pathPattern, requestPath)
73452
+ );
73453
+ if (explicitOptionsRoute)
73454
+ return false;
73455
+ const cors = state.corsConfigByApiId.get(surrogateApiId);
73456
+ if (!cors)
73457
+ return false;
73458
+ const preflight = matchPreflight({ method: "OPTIONS", headers }, cors);
73459
+ if (!preflight)
73460
+ return false;
73461
+ res.statusCode = preflight.statusCode;
73462
+ for (const [name, value] of Object.entries(preflight.headers)) {
73463
+ res.setHeader(name, value);
73464
+ }
73465
+ res.end();
73466
+ return true;
73467
+ }
73468
+ function pathPatternMatchesPath(pattern, requestPath) {
73469
+ if (pattern === "$default")
73470
+ return true;
73471
+ const requestSegments = requestPath.split("/").filter((s) => s.length > 0);
73472
+ const patternSegments = pattern.split("/").filter((s) => s.length > 0);
73473
+ if (patternSegments.length > 0) {
73474
+ const tail = patternSegments[patternSegments.length - 1];
73475
+ if (/^\{[^/{}]+\+\}$/.test(tail)) {
73476
+ const fixed = patternSegments.length - 1;
73477
+ if (requestSegments.length < fixed)
73478
+ return false;
73479
+ for (let i = 0; i < fixed; i++) {
73480
+ const ps = patternSegments[i];
73481
+ const rs = requestSegments[i];
73482
+ if (/^\{[^/{}+]+\}$/.test(ps))
73483
+ continue;
73484
+ if (ps !== rs)
73485
+ return false;
73486
+ }
73487
+ return true;
73488
+ }
73489
+ }
73490
+ if (patternSegments.length !== requestSegments.length)
73491
+ return false;
73492
+ for (let i = 0; i < patternSegments.length; i++) {
73493
+ const ps = patternSegments[i];
73494
+ const rs = requestSegments[i];
73495
+ if (/^\{[^/{}+]+\}$/.test(ps))
73496
+ continue;
73497
+ if (ps !== rs)
73498
+ return false;
73214
73499
  }
73500
+ return true;
73501
+ }
73502
+ function pickFirstHeaderValue(headers, name) {
73503
+ const lower = name.toLowerCase();
73504
+ for (const [k, v] of Object.entries(headers)) {
73505
+ if (k.toLowerCase() === lower && v.length > 0)
73506
+ return v[0];
73507
+ }
73508
+ return null;
73215
73509
  }
73216
- async function runAuthorizerPass(authorizer, snapshot, matchCtx, opts, requestContextV2) {
73510
+ async function runAuthorizerPass(authorizer, snapshot, matchCtx, state, opts, requestContextV2) {
73217
73511
  const headers = lowercaseSingularHeaders(snapshot.headers);
73218
73512
  const queryStringParameters = parseQueryStringSingular(snapshot.rawUrl);
73219
73513
  const sourceIp = pickSourceIp(matchCtx.route.apiVersion, requestContextV2, snapshot);
@@ -73249,7 +73543,7 @@ async function runAuthorizerPass(authorizer, snapshot, matchCtx, opts, requestCo
73249
73543
  }
73250
73544
  }
73251
73545
  const result2 = await invokeTokenAuthorizer(authorizer, reqSnap, {
73252
- pool: opts.pool,
73546
+ pool: state.pool,
73253
73547
  rieTimeoutMs: opts.rieTimeoutMs,
73254
73548
  methodArn,
73255
73549
  mockAccountId: "123456789012",
@@ -73280,7 +73574,7 @@ async function runAuthorizerPass(authorizer, snapshot, matchCtx, opts, requestCo
73280
73574
  }
73281
73575
  }
73282
73576
  const result2 = await invokeRequestAuthorizer(authorizer, reqSnap, {
73283
- pool: opts.pool,
73577
+ pool: state.pool,
73284
73578
  rieTimeoutMs: opts.rieTimeoutMs,
73285
73579
  methodArn,
73286
73580
  mockAccountId: "123456789012",
@@ -73462,6 +73756,1985 @@ function writeError(res, statusCode, body = '{"message":"Internal server error"}
73462
73756
  res.end(body);
73463
73757
  }
73464
73758
 
73759
+ // src/local/stage-resolver.ts
73760
+ function buildStageMap(template, stageOverride) {
73761
+ const out = /* @__PURE__ */ new Map();
73762
+ const resources = template.Resources ?? {};
73763
+ const restStagesByApi = /* @__PURE__ */ new Map();
73764
+ const v2StagesByApi = /* @__PURE__ */ new Map();
73765
+ for (const [logicalId, resource] of Object.entries(resources)) {
73766
+ if (resource.Type === "AWS::ApiGateway::Stage") {
73767
+ const apiId = pickRefLogicalId3((resource.Properties ?? {})["RestApiId"]);
73768
+ if (apiId)
73769
+ appendByApi(restStagesByApi, apiId, logicalId, resource);
73770
+ } else if (resource.Type === "AWS::ApiGatewayV2::Stage") {
73771
+ const apiId = pickRefLogicalId3((resource.Properties ?? {})["ApiId"]);
73772
+ if (apiId)
73773
+ appendByApi(v2StagesByApi, apiId, logicalId, resource);
73774
+ }
73775
+ }
73776
+ for (const [apiId, stages] of restStagesByApi) {
73777
+ const picked = pickStage(stages, stageOverride);
73778
+ if (picked)
73779
+ out.set(apiId, toResolvedStage(picked, "v1"));
73780
+ }
73781
+ for (const [apiId, stages] of v2StagesByApi) {
73782
+ const picked = pickStage(stages, stageOverride);
73783
+ if (picked)
73784
+ out.set(apiId, toResolvedStage(picked, "v2"));
73785
+ }
73786
+ return out;
73787
+ }
73788
+ function appendByApi(bucket, apiId, stageId, resource) {
73789
+ const list = bucket.get(apiId) ?? [];
73790
+ list.push({ id: stageId, resource });
73791
+ bucket.set(apiId, list);
73792
+ }
73793
+ function pickStage(stages, stageOverride) {
73794
+ if (stages.length === 0)
73795
+ return void 0;
73796
+ if (stageOverride) {
73797
+ for (const s of stages) {
73798
+ const props = s.resource.Properties ?? {};
73799
+ if (props["StageName"] === stageOverride)
73800
+ return s;
73801
+ }
73802
+ return void 0;
73803
+ }
73804
+ return stages[0];
73805
+ }
73806
+ function toResolvedStage(stage, apiVersion) {
73807
+ const props = stage.resource.Properties ?? {};
73808
+ const stageName = typeof props["StageName"] === "string" ? props["StageName"] : "$default";
73809
+ const rawVars = apiVersion === "v1" ? props["Variables"] : props["StageVariables"];
73810
+ let variables = null;
73811
+ if (rawVars && typeof rawVars === "object" && !Array.isArray(rawVars)) {
73812
+ const map = {};
73813
+ for (const [k, v] of Object.entries(rawVars)) {
73814
+ if (typeof v === "string") {
73815
+ map[k] = v;
73816
+ }
73817
+ }
73818
+ variables = Object.keys(map).length > 0 ? map : null;
73819
+ }
73820
+ return { stageLogicalId: stage.id, stageName, apiVersion, variables };
73821
+ }
73822
+ function attachStageContext(routes, stageMap) {
73823
+ for (const route of routes) {
73824
+ if (!route.apiLogicalId) {
73825
+ route.stageVariables = null;
73826
+ continue;
73827
+ }
73828
+ const stage = stageMap.get(route.apiLogicalId);
73829
+ if (!stage) {
73830
+ route.stageVariables = null;
73831
+ continue;
73832
+ }
73833
+ route.stageVariables = stage.variables;
73834
+ if (route.source === "rest-v1") {
73835
+ route.stage = stage.stageName;
73836
+ }
73837
+ }
73838
+ }
73839
+ function pickRefLogicalId3(value) {
73840
+ if (value && typeof value === "object" && !Array.isArray(value)) {
73841
+ const ref = value["Ref"];
73842
+ if (typeof ref === "string")
73843
+ return ref;
73844
+ }
73845
+ return null;
73846
+ }
73847
+
73848
+ // node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/index.js
73849
+ import { EventEmitter } from "node:events";
73850
+ import { stat as statcb, Stats } from "node:fs";
73851
+ import { readdir as readdir2, stat as stat3 } from "node:fs/promises";
73852
+ import * as sp2 from "node:path";
73853
+
73854
+ // node_modules/.pnpm/readdirp@5.0.0/node_modules/readdirp/index.js
73855
+ import { lstat, readdir, realpath, stat } from "node:fs/promises";
73856
+ import { join as pjoin, relative as prelative, resolve as presolve, sep as psep } from "node:path";
73857
+ import { Readable } from "node:stream";
73858
+ var EntryTypes = {
73859
+ FILE_TYPE: "files",
73860
+ DIR_TYPE: "directories",
73861
+ FILE_DIR_TYPE: "files_directories",
73862
+ EVERYTHING_TYPE: "all"
73863
+ };
73864
+ var defaultOptions = {
73865
+ root: ".",
73866
+ fileFilter: (_entryInfo) => true,
73867
+ directoryFilter: (_entryInfo) => true,
73868
+ type: EntryTypes.FILE_TYPE,
73869
+ lstat: false,
73870
+ depth: 2147483648,
73871
+ alwaysStat: false,
73872
+ highWaterMark: 4096
73873
+ };
73874
+ Object.freeze(defaultOptions);
73875
+ var RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
73876
+ var NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
73877
+ var ALL_TYPES = [
73878
+ EntryTypes.DIR_TYPE,
73879
+ EntryTypes.EVERYTHING_TYPE,
73880
+ EntryTypes.FILE_DIR_TYPE,
73881
+ EntryTypes.FILE_TYPE
73882
+ ];
73883
+ var DIR_TYPES = /* @__PURE__ */ new Set([
73884
+ EntryTypes.DIR_TYPE,
73885
+ EntryTypes.EVERYTHING_TYPE,
73886
+ EntryTypes.FILE_DIR_TYPE
73887
+ ]);
73888
+ var FILE_TYPES = /* @__PURE__ */ new Set([
73889
+ EntryTypes.EVERYTHING_TYPE,
73890
+ EntryTypes.FILE_DIR_TYPE,
73891
+ EntryTypes.FILE_TYPE
73892
+ ]);
73893
+ var isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
73894
+ var wantBigintFsStats = process.platform === "win32";
73895
+ var emptyFn = (_entryInfo) => true;
73896
+ var normalizeFilter = (filter) => {
73897
+ if (filter === void 0)
73898
+ return emptyFn;
73899
+ if (typeof filter === "function")
73900
+ return filter;
73901
+ if (typeof filter === "string") {
73902
+ const fl = filter.trim();
73903
+ return (entry) => entry.basename === fl;
73904
+ }
73905
+ if (Array.isArray(filter)) {
73906
+ const trItems = filter.map((item) => item.trim());
73907
+ return (entry) => trItems.some((f) => entry.basename === f);
73908
+ }
73909
+ return emptyFn;
73910
+ };
73911
+ var ReaddirpStream = class extends Readable {
73912
+ parents;
73913
+ reading;
73914
+ parent;
73915
+ _stat;
73916
+ _maxDepth;
73917
+ _wantsDir;
73918
+ _wantsFile;
73919
+ _wantsEverything;
73920
+ _root;
73921
+ _isDirent;
73922
+ _statsProp;
73923
+ _rdOptions;
73924
+ _fileFilter;
73925
+ _directoryFilter;
73926
+ constructor(options = {}) {
73927
+ super({
73928
+ objectMode: true,
73929
+ autoDestroy: true,
73930
+ highWaterMark: options.highWaterMark
73931
+ });
73932
+ const opts = { ...defaultOptions, ...options };
73933
+ const { root, type } = opts;
73934
+ this._fileFilter = normalizeFilter(opts.fileFilter);
73935
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
73936
+ const statMethod = opts.lstat ? lstat : stat;
73937
+ if (wantBigintFsStats) {
73938
+ this._stat = (path3) => statMethod(path3, { bigint: true });
73939
+ } else {
73940
+ this._stat = statMethod;
73941
+ }
73942
+ this._maxDepth = opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;
73943
+ this._wantsDir = type ? DIR_TYPES.has(type) : false;
73944
+ this._wantsFile = type ? FILE_TYPES.has(type) : false;
73945
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
73946
+ this._root = presolve(root);
73947
+ this._isDirent = !opts.alwaysStat;
73948
+ this._statsProp = this._isDirent ? "dirent" : "stats";
73949
+ this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
73950
+ this.parents = [this._exploreDir(root, 1)];
73951
+ this.reading = false;
73952
+ this.parent = void 0;
73953
+ }
73954
+ async _read(batch) {
73955
+ if (this.reading)
73956
+ return;
73957
+ this.reading = true;
73958
+ try {
73959
+ while (!this.destroyed && batch > 0) {
73960
+ const par = this.parent;
73961
+ const fil = par && par.files;
73962
+ if (fil && fil.length > 0) {
73963
+ const { path: path3, depth } = par;
73964
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path3));
73965
+ const awaited = await Promise.all(slice);
73966
+ for (const entry of awaited) {
73967
+ if (!entry)
73968
+ continue;
73969
+ if (this.destroyed)
73970
+ return;
73971
+ const entryType = await this._getEntryType(entry);
73972
+ if (entryType === "directory" && this._directoryFilter(entry)) {
73973
+ if (depth <= this._maxDepth) {
73974
+ this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
73975
+ }
73976
+ if (this._wantsDir) {
73977
+ this.push(entry);
73978
+ batch--;
73979
+ }
73980
+ } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
73981
+ if (this._wantsFile) {
73982
+ this.push(entry);
73983
+ batch--;
73984
+ }
73985
+ }
73986
+ }
73987
+ } else {
73988
+ const parent = this.parents.pop();
73989
+ if (!parent) {
73990
+ this.push(null);
73991
+ break;
73992
+ }
73993
+ this.parent = await parent;
73994
+ if (this.destroyed)
73995
+ return;
73996
+ }
73997
+ }
73998
+ } catch (error) {
73999
+ this.destroy(error);
74000
+ } finally {
74001
+ this.reading = false;
74002
+ }
74003
+ }
74004
+ async _exploreDir(path3, depth) {
74005
+ let files;
74006
+ try {
74007
+ files = await readdir(path3, this._rdOptions);
74008
+ } catch (error) {
74009
+ this._onError(error);
74010
+ }
74011
+ return { files, depth, path: path3 };
74012
+ }
74013
+ async _formatEntry(dirent, path3) {
74014
+ let entry;
74015
+ const basename4 = this._isDirent ? dirent.name : dirent;
74016
+ try {
74017
+ const fullPath = presolve(pjoin(path3, basename4));
74018
+ entry = { path: prelative(this._root, fullPath), fullPath, basename: basename4 };
74019
+ entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
74020
+ } catch (err) {
74021
+ this._onError(err);
74022
+ return;
74023
+ }
74024
+ return entry;
74025
+ }
74026
+ _onError(err) {
74027
+ if (isNormalFlowError(err) && !this.destroyed) {
74028
+ this.emit("warn", err);
74029
+ } else {
74030
+ this.destroy(err);
74031
+ }
74032
+ }
74033
+ async _getEntryType(entry) {
74034
+ if (!entry && this._statsProp in entry) {
74035
+ return "";
74036
+ }
74037
+ const stats = entry[this._statsProp];
74038
+ if (stats.isFile())
74039
+ return "file";
74040
+ if (stats.isDirectory())
74041
+ return "directory";
74042
+ if (stats && stats.isSymbolicLink()) {
74043
+ const full = entry.fullPath;
74044
+ try {
74045
+ const entryRealPath = await realpath(full);
74046
+ const entryRealPathStats = await lstat(entryRealPath);
74047
+ if (entryRealPathStats.isFile()) {
74048
+ return "file";
74049
+ }
74050
+ if (entryRealPathStats.isDirectory()) {
74051
+ const len = entryRealPath.length;
74052
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === psep) {
74053
+ const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
74054
+ recursiveError.code = RECURSIVE_ERROR_CODE;
74055
+ return this._onError(recursiveError);
74056
+ }
74057
+ return "directory";
74058
+ }
74059
+ } catch (error) {
74060
+ this._onError(error);
74061
+ return "";
74062
+ }
74063
+ }
74064
+ }
74065
+ _includeAsFile(entry) {
74066
+ const stats = entry && entry[this._statsProp];
74067
+ return stats && this._wantsEverything && !stats.isDirectory();
74068
+ }
74069
+ };
74070
+ function readdirp(root, options = {}) {
74071
+ let type = options.entryType || options.type;
74072
+ if (type === "both")
74073
+ type = EntryTypes.FILE_DIR_TYPE;
74074
+ if (type)
74075
+ options.type = type;
74076
+ if (!root) {
74077
+ throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
74078
+ } else if (typeof root !== "string") {
74079
+ throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
74080
+ } else if (type && !ALL_TYPES.includes(type)) {
74081
+ throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
74082
+ }
74083
+ options.root = root;
74084
+ return new ReaddirpStream(options);
74085
+ }
74086
+
74087
+ // node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/handler.js
74088
+ import { watch as fs_watch, unwatchFile, watchFile } from "node:fs";
74089
+ import { realpath as fsrealpath, lstat as lstat2, open, stat as stat2 } from "node:fs/promises";
74090
+ import { type as osType } from "node:os";
74091
+ import * as sp from "node:path";
74092
+ var STR_DATA = "data";
74093
+ var STR_END = "end";
74094
+ var STR_CLOSE = "close";
74095
+ var EMPTY_FN = () => {
74096
+ };
74097
+ var pl = process.platform;
74098
+ var isWindows = pl === "win32";
74099
+ var isMacos = pl === "darwin";
74100
+ var isLinux = pl === "linux";
74101
+ var isFreeBSD = pl === "freebsd";
74102
+ var isIBMi = osType() === "OS400";
74103
+ var EVENTS = {
74104
+ ALL: "all",
74105
+ READY: "ready",
74106
+ ADD: "add",
74107
+ CHANGE: "change",
74108
+ ADD_DIR: "addDir",
74109
+ UNLINK: "unlink",
74110
+ UNLINK_DIR: "unlinkDir",
74111
+ RAW: "raw",
74112
+ ERROR: "error"
74113
+ };
74114
+ var EV = EVENTS;
74115
+ var THROTTLE_MODE_WATCH = "watch";
74116
+ var statMethods = { lstat: lstat2, stat: stat2 };
74117
+ var KEY_LISTENERS = "listeners";
74118
+ var KEY_ERR = "errHandlers";
74119
+ var KEY_RAW = "rawEmitters";
74120
+ var HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
74121
+ var binaryExtensions = /* @__PURE__ */ new Set([
74122
+ "3dm",
74123
+ "3ds",
74124
+ "3g2",
74125
+ "3gp",
74126
+ "7z",
74127
+ "a",
74128
+ "aac",
74129
+ "adp",
74130
+ "afdesign",
74131
+ "afphoto",
74132
+ "afpub",
74133
+ "ai",
74134
+ "aif",
74135
+ "aiff",
74136
+ "alz",
74137
+ "ape",
74138
+ "apk",
74139
+ "appimage",
74140
+ "ar",
74141
+ "arj",
74142
+ "asf",
74143
+ "au",
74144
+ "avi",
74145
+ "bak",
74146
+ "baml",
74147
+ "bh",
74148
+ "bin",
74149
+ "bk",
74150
+ "bmp",
74151
+ "btif",
74152
+ "bz2",
74153
+ "bzip2",
74154
+ "cab",
74155
+ "caf",
74156
+ "cgm",
74157
+ "class",
74158
+ "cmx",
74159
+ "cpio",
74160
+ "cr2",
74161
+ "cur",
74162
+ "dat",
74163
+ "dcm",
74164
+ "deb",
74165
+ "dex",
74166
+ "djvu",
74167
+ "dll",
74168
+ "dmg",
74169
+ "dng",
74170
+ "doc",
74171
+ "docm",
74172
+ "docx",
74173
+ "dot",
74174
+ "dotm",
74175
+ "dra",
74176
+ "DS_Store",
74177
+ "dsk",
74178
+ "dts",
74179
+ "dtshd",
74180
+ "dvb",
74181
+ "dwg",
74182
+ "dxf",
74183
+ "ecelp4800",
74184
+ "ecelp7470",
74185
+ "ecelp9600",
74186
+ "egg",
74187
+ "eol",
74188
+ "eot",
74189
+ "epub",
74190
+ "exe",
74191
+ "f4v",
74192
+ "fbs",
74193
+ "fh",
74194
+ "fla",
74195
+ "flac",
74196
+ "flatpak",
74197
+ "fli",
74198
+ "flv",
74199
+ "fpx",
74200
+ "fst",
74201
+ "fvt",
74202
+ "g3",
74203
+ "gh",
74204
+ "gif",
74205
+ "graffle",
74206
+ "gz",
74207
+ "gzip",
74208
+ "h261",
74209
+ "h263",
74210
+ "h264",
74211
+ "icns",
74212
+ "ico",
74213
+ "ief",
74214
+ "img",
74215
+ "ipa",
74216
+ "iso",
74217
+ "jar",
74218
+ "jpeg",
74219
+ "jpg",
74220
+ "jpgv",
74221
+ "jpm",
74222
+ "jxr",
74223
+ "key",
74224
+ "ktx",
74225
+ "lha",
74226
+ "lib",
74227
+ "lvp",
74228
+ "lz",
74229
+ "lzh",
74230
+ "lzma",
74231
+ "lzo",
74232
+ "m3u",
74233
+ "m4a",
74234
+ "m4v",
74235
+ "mar",
74236
+ "mdi",
74237
+ "mht",
74238
+ "mid",
74239
+ "midi",
74240
+ "mj2",
74241
+ "mka",
74242
+ "mkv",
74243
+ "mmr",
74244
+ "mng",
74245
+ "mobi",
74246
+ "mov",
74247
+ "movie",
74248
+ "mp3",
74249
+ "mp4",
74250
+ "mp4a",
74251
+ "mpeg",
74252
+ "mpg",
74253
+ "mpga",
74254
+ "mxu",
74255
+ "nef",
74256
+ "npx",
74257
+ "numbers",
74258
+ "nupkg",
74259
+ "o",
74260
+ "odp",
74261
+ "ods",
74262
+ "odt",
74263
+ "oga",
74264
+ "ogg",
74265
+ "ogv",
74266
+ "otf",
74267
+ "ott",
74268
+ "pages",
74269
+ "pbm",
74270
+ "pcx",
74271
+ "pdb",
74272
+ "pdf",
74273
+ "pea",
74274
+ "pgm",
74275
+ "pic",
74276
+ "png",
74277
+ "pnm",
74278
+ "pot",
74279
+ "potm",
74280
+ "potx",
74281
+ "ppa",
74282
+ "ppam",
74283
+ "ppm",
74284
+ "pps",
74285
+ "ppsm",
74286
+ "ppsx",
74287
+ "ppt",
74288
+ "pptm",
74289
+ "pptx",
74290
+ "psd",
74291
+ "pya",
74292
+ "pyc",
74293
+ "pyo",
74294
+ "pyv",
74295
+ "qt",
74296
+ "rar",
74297
+ "ras",
74298
+ "raw",
74299
+ "resources",
74300
+ "rgb",
74301
+ "rip",
74302
+ "rlc",
74303
+ "rmf",
74304
+ "rmvb",
74305
+ "rpm",
74306
+ "rtf",
74307
+ "rz",
74308
+ "s3m",
74309
+ "s7z",
74310
+ "scpt",
74311
+ "sgi",
74312
+ "shar",
74313
+ "snap",
74314
+ "sil",
74315
+ "sketch",
74316
+ "slk",
74317
+ "smv",
74318
+ "snk",
74319
+ "so",
74320
+ "stl",
74321
+ "suo",
74322
+ "sub",
74323
+ "swf",
74324
+ "tar",
74325
+ "tbz",
74326
+ "tbz2",
74327
+ "tga",
74328
+ "tgz",
74329
+ "thmx",
74330
+ "tif",
74331
+ "tiff",
74332
+ "tlz",
74333
+ "ttc",
74334
+ "ttf",
74335
+ "txz",
74336
+ "udf",
74337
+ "uvh",
74338
+ "uvi",
74339
+ "uvm",
74340
+ "uvp",
74341
+ "uvs",
74342
+ "uvu",
74343
+ "viv",
74344
+ "vob",
74345
+ "war",
74346
+ "wav",
74347
+ "wax",
74348
+ "wbmp",
74349
+ "wdp",
74350
+ "weba",
74351
+ "webm",
74352
+ "webp",
74353
+ "whl",
74354
+ "wim",
74355
+ "wm",
74356
+ "wma",
74357
+ "wmv",
74358
+ "wmx",
74359
+ "woff",
74360
+ "woff2",
74361
+ "wrm",
74362
+ "wvx",
74363
+ "xbm",
74364
+ "xif",
74365
+ "xla",
74366
+ "xlam",
74367
+ "xls",
74368
+ "xlsb",
74369
+ "xlsm",
74370
+ "xlsx",
74371
+ "xlt",
74372
+ "xltm",
74373
+ "xltx",
74374
+ "xm",
74375
+ "xmind",
74376
+ "xpi",
74377
+ "xpm",
74378
+ "xwd",
74379
+ "xz",
74380
+ "z",
74381
+ "zip",
74382
+ "zipx"
74383
+ ]);
74384
+ var isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());
74385
+ var foreach = (val, fn) => {
74386
+ if (val instanceof Set) {
74387
+ val.forEach(fn);
74388
+ } else {
74389
+ fn(val);
74390
+ }
74391
+ };
74392
+ var addAndConvert = (main2, prop, item) => {
74393
+ let container = main2[prop];
74394
+ if (!(container instanceof Set)) {
74395
+ main2[prop] = container = /* @__PURE__ */ new Set([container]);
74396
+ }
74397
+ container.add(item);
74398
+ };
74399
+ var clearItem = (cont) => (key) => {
74400
+ const set = cont[key];
74401
+ if (set instanceof Set) {
74402
+ set.clear();
74403
+ } else {
74404
+ delete cont[key];
74405
+ }
74406
+ };
74407
+ var delFromSet = (main2, prop, item) => {
74408
+ const container = main2[prop];
74409
+ if (container instanceof Set) {
74410
+ container.delete(item);
74411
+ } else if (container === item) {
74412
+ delete main2[prop];
74413
+ }
74414
+ };
74415
+ var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
74416
+ var FsWatchInstances = /* @__PURE__ */ new Map();
74417
+ function createFsWatchInstance(path3, options, listener, errHandler, emitRaw) {
74418
+ const handleEvent = (rawEvent, evPath) => {
74419
+ listener(path3);
74420
+ emitRaw(rawEvent, evPath, { watchedPath: path3 });
74421
+ if (evPath && path3 !== evPath) {
74422
+ fsWatchBroadcast(sp.resolve(path3, evPath), KEY_LISTENERS, sp.join(path3, evPath));
74423
+ }
74424
+ };
74425
+ try {
74426
+ return fs_watch(path3, {
74427
+ persistent: options.persistent
74428
+ }, handleEvent);
74429
+ } catch (error) {
74430
+ errHandler(error);
74431
+ return void 0;
74432
+ }
74433
+ }
74434
+ var fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
74435
+ const cont = FsWatchInstances.get(fullPath);
74436
+ if (!cont)
74437
+ return;
74438
+ foreach(cont[listenerType], (listener) => {
74439
+ listener(val1, val2, val3);
74440
+ });
74441
+ };
74442
+ var setFsWatchListener = (path3, fullPath, options, handlers) => {
74443
+ const { listener, errHandler, rawEmitter } = handlers;
74444
+ let cont = FsWatchInstances.get(fullPath);
74445
+ let watcher;
74446
+ if (!options.persistent) {
74447
+ watcher = createFsWatchInstance(path3, options, listener, errHandler, rawEmitter);
74448
+ if (!watcher)
74449
+ return;
74450
+ return watcher.close.bind(watcher);
74451
+ }
74452
+ if (cont) {
74453
+ addAndConvert(cont, KEY_LISTENERS, listener);
74454
+ addAndConvert(cont, KEY_ERR, errHandler);
74455
+ addAndConvert(cont, KEY_RAW, rawEmitter);
74456
+ } else {
74457
+ watcher = createFsWatchInstance(
74458
+ path3,
74459
+ options,
74460
+ fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
74461
+ errHandler,
74462
+ // no need to use broadcast here
74463
+ fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
74464
+ );
74465
+ if (!watcher)
74466
+ return;
74467
+ watcher.on(EV.ERROR, async (error) => {
74468
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
74469
+ if (cont)
74470
+ cont.watcherUnusable = true;
74471
+ if (isWindows && error.code === "EPERM") {
74472
+ try {
74473
+ const fd = await open(path3, "r");
74474
+ await fd.close();
74475
+ broadcastErr(error);
74476
+ } catch (err) {
74477
+ }
74478
+ } else {
74479
+ broadcastErr(error);
74480
+ }
74481
+ });
74482
+ cont = {
74483
+ listeners: listener,
74484
+ errHandlers: errHandler,
74485
+ rawEmitters: rawEmitter,
74486
+ watcher
74487
+ };
74488
+ FsWatchInstances.set(fullPath, cont);
74489
+ }
74490
+ return () => {
74491
+ delFromSet(cont, KEY_LISTENERS, listener);
74492
+ delFromSet(cont, KEY_ERR, errHandler);
74493
+ delFromSet(cont, KEY_RAW, rawEmitter);
74494
+ if (isEmptySet(cont.listeners)) {
74495
+ cont.watcher.close();
74496
+ FsWatchInstances.delete(fullPath);
74497
+ HANDLER_KEYS.forEach(clearItem(cont));
74498
+ cont.watcher = void 0;
74499
+ Object.freeze(cont);
74500
+ }
74501
+ };
74502
+ };
74503
+ var FsWatchFileInstances = /* @__PURE__ */ new Map();
74504
+ var setFsWatchFileListener = (path3, fullPath, options, handlers) => {
74505
+ const { listener, rawEmitter } = handlers;
74506
+ let cont = FsWatchFileInstances.get(fullPath);
74507
+ const copts = cont && cont.options;
74508
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
74509
+ unwatchFile(fullPath);
74510
+ cont = void 0;
74511
+ }
74512
+ if (cont) {
74513
+ addAndConvert(cont, KEY_LISTENERS, listener);
74514
+ addAndConvert(cont, KEY_RAW, rawEmitter);
74515
+ } else {
74516
+ cont = {
74517
+ listeners: listener,
74518
+ rawEmitters: rawEmitter,
74519
+ options,
74520
+ watcher: watchFile(fullPath, options, (curr, prev) => {
74521
+ foreach(cont.rawEmitters, (rawEmitter2) => {
74522
+ rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
74523
+ });
74524
+ const currmtime = curr.mtimeMs;
74525
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
74526
+ foreach(cont.listeners, (listener2) => listener2(path3, curr));
74527
+ }
74528
+ })
74529
+ };
74530
+ FsWatchFileInstances.set(fullPath, cont);
74531
+ }
74532
+ return () => {
74533
+ delFromSet(cont, KEY_LISTENERS, listener);
74534
+ delFromSet(cont, KEY_RAW, rawEmitter);
74535
+ if (isEmptySet(cont.listeners)) {
74536
+ FsWatchFileInstances.delete(fullPath);
74537
+ unwatchFile(fullPath);
74538
+ cont.options = cont.watcher = void 0;
74539
+ Object.freeze(cont);
74540
+ }
74541
+ };
74542
+ };
74543
+ var NodeFsHandler = class {
74544
+ fsw;
74545
+ _boundHandleError;
74546
+ constructor(fsW) {
74547
+ this.fsw = fsW;
74548
+ this._boundHandleError = (error) => fsW._handleError(error);
74549
+ }
74550
+ /**
74551
+ * Watch file for changes with fs_watchFile or fs_watch.
74552
+ * @param path to file or dir
74553
+ * @param listener on fs change
74554
+ * @returns closer for the watcher instance
74555
+ */
74556
+ _watchWithNodeFs(path3, listener) {
74557
+ const opts = this.fsw.options;
74558
+ const directory = sp.dirname(path3);
74559
+ const basename4 = sp.basename(path3);
74560
+ const parent = this.fsw._getWatchedDir(directory);
74561
+ parent.add(basename4);
74562
+ const absolutePath = sp.resolve(path3);
74563
+ const options = {
74564
+ persistent: opts.persistent
74565
+ };
74566
+ if (!listener)
74567
+ listener = EMPTY_FN;
74568
+ let closer;
74569
+ if (opts.usePolling) {
74570
+ const enableBin = opts.interval !== opts.binaryInterval;
74571
+ options.interval = enableBin && isBinaryPath(basename4) ? opts.binaryInterval : opts.interval;
74572
+ closer = setFsWatchFileListener(path3, absolutePath, options, {
74573
+ listener,
74574
+ rawEmitter: this.fsw._emitRaw
74575
+ });
74576
+ } else {
74577
+ closer = setFsWatchListener(path3, absolutePath, options, {
74578
+ listener,
74579
+ errHandler: this._boundHandleError,
74580
+ rawEmitter: this.fsw._emitRaw
74581
+ });
74582
+ }
74583
+ return closer;
74584
+ }
74585
+ /**
74586
+ * Watch a file and emit add event if warranted.
74587
+ * @returns closer for the watcher instance
74588
+ */
74589
+ _handleFile(file, stats, initialAdd) {
74590
+ if (this.fsw.closed) {
74591
+ return;
74592
+ }
74593
+ const dirname7 = sp.dirname(file);
74594
+ const basename4 = sp.basename(file);
74595
+ const parent = this.fsw._getWatchedDir(dirname7);
74596
+ let prevStats = stats;
74597
+ if (parent.has(basename4))
74598
+ return;
74599
+ const listener = async (path3, newStats) => {
74600
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5))
74601
+ return;
74602
+ if (!newStats || newStats.mtimeMs === 0) {
74603
+ try {
74604
+ const newStats2 = await stat2(file);
74605
+ if (this.fsw.closed)
74606
+ return;
74607
+ const at = newStats2.atimeMs;
74608
+ const mt = newStats2.mtimeMs;
74609
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
74610
+ this.fsw._emit(EV.CHANGE, file, newStats2);
74611
+ }
74612
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
74613
+ this.fsw._closeFile(path3);
74614
+ prevStats = newStats2;
74615
+ const closer2 = this._watchWithNodeFs(file, listener);
74616
+ if (closer2)
74617
+ this.fsw._addPathCloser(path3, closer2);
74618
+ } else {
74619
+ prevStats = newStats2;
74620
+ }
74621
+ } catch (error) {
74622
+ this.fsw._remove(dirname7, basename4);
74623
+ }
74624
+ } else if (parent.has(basename4)) {
74625
+ const at = newStats.atimeMs;
74626
+ const mt = newStats.mtimeMs;
74627
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
74628
+ this.fsw._emit(EV.CHANGE, file, newStats);
74629
+ }
74630
+ prevStats = newStats;
74631
+ }
74632
+ };
74633
+ const closer = this._watchWithNodeFs(file, listener);
74634
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
74635
+ if (!this.fsw._throttle(EV.ADD, file, 0))
74636
+ return;
74637
+ this.fsw._emit(EV.ADD, file, stats);
74638
+ }
74639
+ return closer;
74640
+ }
74641
+ /**
74642
+ * Handle symlinks encountered while reading a dir.
74643
+ * @param entry returned by readdirp
74644
+ * @param directory path of dir being read
74645
+ * @param path of this item
74646
+ * @param item basename of this item
74647
+ * @returns true if no more processing is needed for this entry.
74648
+ */
74649
+ async _handleSymlink(entry, directory, path3, item) {
74650
+ if (this.fsw.closed) {
74651
+ return;
74652
+ }
74653
+ const full = entry.fullPath;
74654
+ const dir = this.fsw._getWatchedDir(directory);
74655
+ if (!this.fsw.options.followSymlinks) {
74656
+ this.fsw._incrReadyCount();
74657
+ let linkPath;
74658
+ try {
74659
+ linkPath = await fsrealpath(path3);
74660
+ } catch (e) {
74661
+ this.fsw._emitReady();
74662
+ return true;
74663
+ }
74664
+ if (this.fsw.closed)
74665
+ return;
74666
+ if (dir.has(item)) {
74667
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
74668
+ this.fsw._symlinkPaths.set(full, linkPath);
74669
+ this.fsw._emit(EV.CHANGE, path3, entry.stats);
74670
+ }
74671
+ } else {
74672
+ dir.add(item);
74673
+ this.fsw._symlinkPaths.set(full, linkPath);
74674
+ this.fsw._emit(EV.ADD, path3, entry.stats);
74675
+ }
74676
+ this.fsw._emitReady();
74677
+ return true;
74678
+ }
74679
+ if (this.fsw._symlinkPaths.has(full)) {
74680
+ return true;
74681
+ }
74682
+ this.fsw._symlinkPaths.set(full, true);
74683
+ }
74684
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
74685
+ directory = sp.join(directory, "");
74686
+ const throttleKey = target ? `${directory}:${target}` : directory;
74687
+ throttler = this.fsw._throttle("readdir", throttleKey, 1e3);
74688
+ if (!throttler)
74689
+ return;
74690
+ const previous = this.fsw._getWatchedDir(wh.path);
74691
+ const current = /* @__PURE__ */ new Set();
74692
+ let stream = this.fsw._readdirp(directory, {
74693
+ fileFilter: (entry) => wh.filterPath(entry),
74694
+ directoryFilter: (entry) => wh.filterDir(entry)
74695
+ });
74696
+ if (!stream)
74697
+ return;
74698
+ stream.on(STR_DATA, async (entry) => {
74699
+ if (this.fsw.closed) {
74700
+ stream = void 0;
74701
+ return;
74702
+ }
74703
+ const item = entry.path;
74704
+ let path3 = sp.join(directory, item);
74705
+ current.add(item);
74706
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path3, item)) {
74707
+ return;
74708
+ }
74709
+ if (this.fsw.closed) {
74710
+ stream = void 0;
74711
+ return;
74712
+ }
74713
+ if (item === target || !target && !previous.has(item)) {
74714
+ this.fsw._incrReadyCount();
74715
+ path3 = sp.join(dir, sp.relative(dir, path3));
74716
+ this._addToNodeFs(path3, initialAdd, wh, depth + 1);
74717
+ }
74718
+ }).on(EV.ERROR, this._boundHandleError);
74719
+ return new Promise((resolve8, reject) => {
74720
+ if (!stream)
74721
+ return reject();
74722
+ stream.once(STR_END, () => {
74723
+ if (this.fsw.closed) {
74724
+ stream = void 0;
74725
+ return;
74726
+ }
74727
+ const wasThrottled = throttler ? throttler.clear() : false;
74728
+ resolve8(void 0);
74729
+ previous.getChildren().filter((item) => {
74730
+ return item !== directory && !current.has(item);
74731
+ }).forEach((item) => {
74732
+ this.fsw._remove(directory, item);
74733
+ });
74734
+ stream = void 0;
74735
+ if (wasThrottled)
74736
+ this._handleRead(directory, false, wh, target, dir, depth, throttler);
74737
+ });
74738
+ });
74739
+ }
74740
+ /**
74741
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
74742
+ * @param dir fs path
74743
+ * @param stats
74744
+ * @param initialAdd
74745
+ * @param depth relative to user-supplied path
74746
+ * @param target child path targeted for watch
74747
+ * @param wh Common watch helpers for this path
74748
+ * @param realpath
74749
+ * @returns closer for the watcher instance.
74750
+ */
74751
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) {
74752
+ const parentDir = this.fsw._getWatchedDir(sp.dirname(dir));
74753
+ const tracked = parentDir.has(sp.basename(dir));
74754
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
74755
+ this.fsw._emit(EV.ADD_DIR, dir, stats);
74756
+ }
74757
+ parentDir.add(sp.basename(dir));
74758
+ this.fsw._getWatchedDir(dir);
74759
+ let throttler;
74760
+ let closer;
74761
+ const oDepth = this.fsw.options.depth;
74762
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) {
74763
+ if (!target) {
74764
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
74765
+ if (this.fsw.closed)
74766
+ return;
74767
+ }
74768
+ closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
74769
+ if (stats2 && stats2.mtimeMs === 0)
74770
+ return;
74771
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
74772
+ });
74773
+ }
74774
+ return closer;
74775
+ }
74776
+ /**
74777
+ * Handle added file, directory, or glob pattern.
74778
+ * Delegates call to _handleFile / _handleDir after checks.
74779
+ * @param path to file or ir
74780
+ * @param initialAdd was the file added at watch instantiation?
74781
+ * @param priorWh depth relative to user-supplied path
74782
+ * @param depth Child path actually targeted for watch
74783
+ * @param target Child path actually targeted for watch
74784
+ */
74785
+ async _addToNodeFs(path3, initialAdd, priorWh, depth, target) {
74786
+ const ready = this.fsw._emitReady;
74787
+ if (this.fsw._isIgnored(path3) || this.fsw.closed) {
74788
+ ready();
74789
+ return false;
74790
+ }
74791
+ const wh = this.fsw._getWatchHelpers(path3);
74792
+ if (priorWh) {
74793
+ wh.filterPath = (entry) => priorWh.filterPath(entry);
74794
+ wh.filterDir = (entry) => priorWh.filterDir(entry);
74795
+ }
74796
+ try {
74797
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
74798
+ if (this.fsw.closed)
74799
+ return;
74800
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
74801
+ ready();
74802
+ return false;
74803
+ }
74804
+ const follow = this.fsw.options.followSymlinks;
74805
+ let closer;
74806
+ if (stats.isDirectory()) {
74807
+ const absPath = sp.resolve(path3);
74808
+ const targetPath = follow ? await fsrealpath(path3) : path3;
74809
+ if (this.fsw.closed)
74810
+ return;
74811
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
74812
+ if (this.fsw.closed)
74813
+ return;
74814
+ if (absPath !== targetPath && targetPath !== void 0) {
74815
+ this.fsw._symlinkPaths.set(absPath, targetPath);
74816
+ }
74817
+ } else if (stats.isSymbolicLink()) {
74818
+ const targetPath = follow ? await fsrealpath(path3) : path3;
74819
+ if (this.fsw.closed)
74820
+ return;
74821
+ const parent = sp.dirname(wh.watchPath);
74822
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
74823
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
74824
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path3, wh, targetPath);
74825
+ if (this.fsw.closed)
74826
+ return;
74827
+ if (targetPath !== void 0) {
74828
+ this.fsw._symlinkPaths.set(sp.resolve(path3), targetPath);
74829
+ }
74830
+ } else {
74831
+ closer = this._handleFile(wh.watchPath, stats, initialAdd);
74832
+ }
74833
+ ready();
74834
+ if (closer)
74835
+ this.fsw._addPathCloser(path3, closer);
74836
+ return false;
74837
+ } catch (error) {
74838
+ if (this.fsw._handleError(error)) {
74839
+ ready();
74840
+ return path3;
74841
+ }
74842
+ }
74843
+ }
74844
+ };
74845
+
74846
+ // node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/index.js
74847
+ var SLASH = "/";
74848
+ var SLASH_SLASH = "//";
74849
+ var ONE_DOT = ".";
74850
+ var TWO_DOTS = "..";
74851
+ var STRING_TYPE = "string";
74852
+ var BACK_SLASH_RE = /\\/g;
74853
+ var DOUBLE_SLASH_RE = /\/\//g;
74854
+ var DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
74855
+ var REPLACER_RE = /^\.[/\\]/;
74856
+ function arrify(item) {
74857
+ return Array.isArray(item) ? item : [item];
74858
+ }
74859
+ var isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
74860
+ function createPattern(matcher) {
74861
+ if (typeof matcher === "function")
74862
+ return matcher;
74863
+ if (typeof matcher === "string")
74864
+ return (string) => matcher === string;
74865
+ if (matcher instanceof RegExp)
74866
+ return (string) => matcher.test(string);
74867
+ if (typeof matcher === "object" && matcher !== null) {
74868
+ return (string) => {
74869
+ if (matcher.path === string)
74870
+ return true;
74871
+ if (matcher.recursive) {
74872
+ const relative3 = sp2.relative(matcher.path, string);
74873
+ if (!relative3) {
74874
+ return false;
74875
+ }
74876
+ return !relative3.startsWith("..") && !sp2.isAbsolute(relative3);
74877
+ }
74878
+ return false;
74879
+ };
74880
+ }
74881
+ return () => false;
74882
+ }
74883
+ function normalizePath(path3) {
74884
+ if (typeof path3 !== "string")
74885
+ throw new Error("string expected");
74886
+ path3 = sp2.normalize(path3);
74887
+ path3 = path3.replace(/\\/g, "/");
74888
+ let prepend = false;
74889
+ if (path3.startsWith("//"))
74890
+ prepend = true;
74891
+ path3 = path3.replace(DOUBLE_SLASH_RE, "/");
74892
+ if (prepend)
74893
+ path3 = "/" + path3;
74894
+ return path3;
74895
+ }
74896
+ function matchPatterns(patterns, testString, stats) {
74897
+ const path3 = normalizePath(testString);
74898
+ for (let index = 0; index < patterns.length; index++) {
74899
+ const pattern = patterns[index];
74900
+ if (pattern(path3, stats)) {
74901
+ return true;
74902
+ }
74903
+ }
74904
+ return false;
74905
+ }
74906
+ function anymatch(matchers, testString) {
74907
+ if (matchers == null) {
74908
+ throw new TypeError("anymatch: specify first argument");
74909
+ }
74910
+ const matchersArray = arrify(matchers);
74911
+ const patterns = matchersArray.map((matcher) => createPattern(matcher));
74912
+ if (testString == null) {
74913
+ return (testString2, stats) => {
74914
+ return matchPatterns(patterns, testString2, stats);
74915
+ };
74916
+ }
74917
+ return matchPatterns(patterns, testString);
74918
+ }
74919
+ var unifyPaths = (paths_) => {
74920
+ const paths = arrify(paths_).flat();
74921
+ if (!paths.every((p) => typeof p === STRING_TYPE)) {
74922
+ throw new TypeError(`Non-string provided as watch path: ${paths}`);
74923
+ }
74924
+ return paths.map(normalizePathToUnix);
74925
+ };
74926
+ var toUnix = (string) => {
74927
+ let str = string.replace(BACK_SLASH_RE, SLASH);
74928
+ let prepend = false;
74929
+ if (str.startsWith(SLASH_SLASH)) {
74930
+ prepend = true;
74931
+ }
74932
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
74933
+ if (prepend) {
74934
+ str = SLASH + str;
74935
+ }
74936
+ return str;
74937
+ };
74938
+ var normalizePathToUnix = (path3) => toUnix(sp2.normalize(toUnix(path3)));
74939
+ var normalizeIgnored = (cwd = "") => (path3) => {
74940
+ if (typeof path3 === "string") {
74941
+ return normalizePathToUnix(sp2.isAbsolute(path3) ? path3 : sp2.join(cwd, path3));
74942
+ } else {
74943
+ return path3;
74944
+ }
74945
+ };
74946
+ var getAbsolutePath = (path3, cwd) => {
74947
+ if (sp2.isAbsolute(path3)) {
74948
+ return path3;
74949
+ }
74950
+ return sp2.join(cwd, path3);
74951
+ };
74952
+ var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
74953
+ var DirEntry = class {
74954
+ path;
74955
+ _removeWatcher;
74956
+ items;
74957
+ constructor(dir, removeWatcher) {
74958
+ this.path = dir;
74959
+ this._removeWatcher = removeWatcher;
74960
+ this.items = /* @__PURE__ */ new Set();
74961
+ }
74962
+ add(item) {
74963
+ const { items } = this;
74964
+ if (!items)
74965
+ return;
74966
+ if (item !== ONE_DOT && item !== TWO_DOTS)
74967
+ items.add(item);
74968
+ }
74969
+ async remove(item) {
74970
+ const { items } = this;
74971
+ if (!items)
74972
+ return;
74973
+ items.delete(item);
74974
+ if (items.size > 0)
74975
+ return;
74976
+ const dir = this.path;
74977
+ try {
74978
+ await readdir2(dir);
74979
+ } catch (err) {
74980
+ if (this._removeWatcher) {
74981
+ this._removeWatcher(sp2.dirname(dir), sp2.basename(dir));
74982
+ }
74983
+ }
74984
+ }
74985
+ has(item) {
74986
+ const { items } = this;
74987
+ if (!items)
74988
+ return;
74989
+ return items.has(item);
74990
+ }
74991
+ getChildren() {
74992
+ const { items } = this;
74993
+ if (!items)
74994
+ return [];
74995
+ return [...items.values()];
74996
+ }
74997
+ dispose() {
74998
+ this.items.clear();
74999
+ this.path = "";
75000
+ this._removeWatcher = EMPTY_FN;
75001
+ this.items = EMPTY_SET;
75002
+ Object.freeze(this);
75003
+ }
75004
+ };
75005
+ var STAT_METHOD_F = "stat";
75006
+ var STAT_METHOD_L = "lstat";
75007
+ var WatchHelper = class {
75008
+ fsw;
75009
+ path;
75010
+ watchPath;
75011
+ fullWatchPath;
75012
+ dirParts;
75013
+ followSymlinks;
75014
+ statMethod;
75015
+ constructor(path3, follow, fsw) {
75016
+ this.fsw = fsw;
75017
+ const watchPath = path3;
75018
+ this.path = path3 = path3.replace(REPLACER_RE, "");
75019
+ this.watchPath = watchPath;
75020
+ this.fullWatchPath = sp2.resolve(watchPath);
75021
+ this.dirParts = [];
75022
+ this.dirParts.forEach((parts) => {
75023
+ if (parts.length > 1)
75024
+ parts.pop();
75025
+ });
75026
+ this.followSymlinks = follow;
75027
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
75028
+ }
75029
+ entryPath(entry) {
75030
+ return sp2.join(this.watchPath, sp2.relative(this.watchPath, entry.fullPath));
75031
+ }
75032
+ filterPath(entry) {
75033
+ const { stats } = entry;
75034
+ if (stats && stats.isSymbolicLink())
75035
+ return this.filterDir(entry);
75036
+ const resolvedPath = this.entryPath(entry);
75037
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
75038
+ }
75039
+ filterDir(entry) {
75040
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
75041
+ }
75042
+ };
75043
+ var FSWatcher = class extends EventEmitter {
75044
+ closed;
75045
+ options;
75046
+ _closers;
75047
+ _ignoredPaths;
75048
+ _throttled;
75049
+ _streams;
75050
+ _symlinkPaths;
75051
+ _watched;
75052
+ _pendingWrites;
75053
+ _pendingUnlinks;
75054
+ _readyCount;
75055
+ _emitReady;
75056
+ _closePromise;
75057
+ _userIgnored;
75058
+ _readyEmitted;
75059
+ _emitRaw;
75060
+ _boundRemove;
75061
+ _nodeFsHandler;
75062
+ // Not indenting methods for history sake; for now.
75063
+ constructor(_opts = {}) {
75064
+ super();
75065
+ this.closed = false;
75066
+ this._closers = /* @__PURE__ */ new Map();
75067
+ this._ignoredPaths = /* @__PURE__ */ new Set();
75068
+ this._throttled = /* @__PURE__ */ new Map();
75069
+ this._streams = /* @__PURE__ */ new Set();
75070
+ this._symlinkPaths = /* @__PURE__ */ new Map();
75071
+ this._watched = /* @__PURE__ */ new Map();
75072
+ this._pendingWrites = /* @__PURE__ */ new Map();
75073
+ this._pendingUnlinks = /* @__PURE__ */ new Map();
75074
+ this._readyCount = 0;
75075
+ this._readyEmitted = false;
75076
+ const awf = _opts.awaitWriteFinish;
75077
+ const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 };
75078
+ const opts = {
75079
+ // Defaults
75080
+ persistent: true,
75081
+ ignoreInitial: false,
75082
+ ignorePermissionErrors: false,
75083
+ interval: 100,
75084
+ binaryInterval: 300,
75085
+ followSymlinks: true,
75086
+ usePolling: false,
75087
+ // useAsync: false,
75088
+ atomic: true,
75089
+ // NOTE: overwritten later (depends on usePolling)
75090
+ ..._opts,
75091
+ // Change format
75092
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
75093
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
75094
+ };
75095
+ if (isIBMi)
75096
+ opts.usePolling = true;
75097
+ if (opts.atomic === void 0)
75098
+ opts.atomic = !opts.usePolling;
75099
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
75100
+ if (envPoll !== void 0) {
75101
+ const envLower = envPoll.toLowerCase();
75102
+ if (envLower === "false" || envLower === "0")
75103
+ opts.usePolling = false;
75104
+ else if (envLower === "true" || envLower === "1")
75105
+ opts.usePolling = true;
75106
+ else
75107
+ opts.usePolling = !!envLower;
75108
+ }
75109
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
75110
+ if (envInterval)
75111
+ opts.interval = Number.parseInt(envInterval, 10);
75112
+ let readyCalls = 0;
75113
+ this._emitReady = () => {
75114
+ readyCalls++;
75115
+ if (readyCalls >= this._readyCount) {
75116
+ this._emitReady = EMPTY_FN;
75117
+ this._readyEmitted = true;
75118
+ process.nextTick(() => this.emit(EVENTS.READY));
75119
+ }
75120
+ };
75121
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
75122
+ this._boundRemove = this._remove.bind(this);
75123
+ this.options = opts;
75124
+ this._nodeFsHandler = new NodeFsHandler(this);
75125
+ Object.freeze(opts);
75126
+ }
75127
+ _addIgnoredPath(matcher) {
75128
+ if (isMatcherObject(matcher)) {
75129
+ for (const ignored of this._ignoredPaths) {
75130
+ if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
75131
+ return;
75132
+ }
75133
+ }
75134
+ }
75135
+ this._ignoredPaths.add(matcher);
75136
+ }
75137
+ _removeIgnoredPath(matcher) {
75138
+ this._ignoredPaths.delete(matcher);
75139
+ if (typeof matcher === "string") {
75140
+ for (const ignored of this._ignoredPaths) {
75141
+ if (isMatcherObject(ignored) && ignored.path === matcher) {
75142
+ this._ignoredPaths.delete(ignored);
75143
+ }
75144
+ }
75145
+ }
75146
+ }
75147
+ // Public methods
75148
+ /**
75149
+ * Adds paths to be watched on an existing FSWatcher instance.
75150
+ * @param paths_ file or file list. Other arguments are unused
75151
+ */
75152
+ add(paths_, _origAdd, _internal) {
75153
+ const { cwd } = this.options;
75154
+ this.closed = false;
75155
+ this._closePromise = void 0;
75156
+ let paths = unifyPaths(paths_);
75157
+ if (cwd) {
75158
+ paths = paths.map((path3) => {
75159
+ const absPath = getAbsolutePath(path3, cwd);
75160
+ return absPath;
75161
+ });
75162
+ }
75163
+ paths.forEach((path3) => {
75164
+ this._removeIgnoredPath(path3);
75165
+ });
75166
+ this._userIgnored = void 0;
75167
+ if (!this._readyCount)
75168
+ this._readyCount = 0;
75169
+ this._readyCount += paths.length;
75170
+ Promise.all(paths.map(async (path3) => {
75171
+ const res = await this._nodeFsHandler._addToNodeFs(path3, !_internal, void 0, 0, _origAdd);
75172
+ if (res)
75173
+ this._emitReady();
75174
+ return res;
75175
+ })).then((results) => {
75176
+ if (this.closed)
75177
+ return;
75178
+ results.forEach((item) => {
75179
+ if (item)
75180
+ this.add(sp2.dirname(item), sp2.basename(_origAdd || item));
75181
+ });
75182
+ });
75183
+ return this;
75184
+ }
75185
+ /**
75186
+ * Close watchers or start ignoring events from specified paths.
75187
+ */
75188
+ unwatch(paths_) {
75189
+ if (this.closed)
75190
+ return this;
75191
+ const paths = unifyPaths(paths_);
75192
+ const { cwd } = this.options;
75193
+ paths.forEach((path3) => {
75194
+ if (!sp2.isAbsolute(path3) && !this._closers.has(path3)) {
75195
+ if (cwd)
75196
+ path3 = sp2.join(cwd, path3);
75197
+ path3 = sp2.resolve(path3);
75198
+ }
75199
+ this._closePath(path3);
75200
+ this._addIgnoredPath(path3);
75201
+ if (this._watched.has(path3)) {
75202
+ this._addIgnoredPath({
75203
+ path: path3,
75204
+ recursive: true
75205
+ });
75206
+ }
75207
+ this._userIgnored = void 0;
75208
+ });
75209
+ return this;
75210
+ }
75211
+ /**
75212
+ * Close watchers and remove all listeners from watched paths.
75213
+ */
75214
+ close() {
75215
+ if (this._closePromise) {
75216
+ return this._closePromise;
75217
+ }
75218
+ this.closed = true;
75219
+ this.removeAllListeners();
75220
+ const closers = [];
75221
+ this._closers.forEach((closerList) => closerList.forEach((closer) => {
75222
+ const promise = closer();
75223
+ if (promise instanceof Promise)
75224
+ closers.push(promise);
75225
+ }));
75226
+ this._streams.forEach((stream) => stream.destroy());
75227
+ this._userIgnored = void 0;
75228
+ this._readyCount = 0;
75229
+ this._readyEmitted = false;
75230
+ this._watched.forEach((dirent) => dirent.dispose());
75231
+ this._closers.clear();
75232
+ this._watched.clear();
75233
+ this._streams.clear();
75234
+ this._symlinkPaths.clear();
75235
+ this._throttled.clear();
75236
+ this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
75237
+ return this._closePromise;
75238
+ }
75239
+ /**
75240
+ * Expose list of watched paths
75241
+ * @returns for chaining
75242
+ */
75243
+ getWatched() {
75244
+ const watchList = {};
75245
+ this._watched.forEach((entry, dir) => {
75246
+ const key = this.options.cwd ? sp2.relative(this.options.cwd, dir) : dir;
75247
+ const index = key || ONE_DOT;
75248
+ watchList[index] = entry.getChildren().sort();
75249
+ });
75250
+ return watchList;
75251
+ }
75252
+ emitWithAll(event, args) {
75253
+ this.emit(event, ...args);
75254
+ if (event !== EVENTS.ERROR)
75255
+ this.emit(EVENTS.ALL, event, ...args);
75256
+ }
75257
+ // Common helpers
75258
+ // --------------
75259
+ /**
75260
+ * Normalize and emit events.
75261
+ * Calling _emit DOES NOT MEAN emit() would be called!
75262
+ * @param event Type of event
75263
+ * @param path File or directory path
75264
+ * @param stats arguments to be passed with event
75265
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
75266
+ */
75267
+ async _emit(event, path3, stats) {
75268
+ if (this.closed)
75269
+ return;
75270
+ const opts = this.options;
75271
+ if (isWindows)
75272
+ path3 = sp2.normalize(path3);
75273
+ if (opts.cwd)
75274
+ path3 = sp2.relative(opts.cwd, path3);
75275
+ const args = [path3];
75276
+ if (stats != null)
75277
+ args.push(stats);
75278
+ const awf = opts.awaitWriteFinish;
75279
+ let pw;
75280
+ if (awf && (pw = this._pendingWrites.get(path3))) {
75281
+ pw.lastChange = /* @__PURE__ */ new Date();
75282
+ return this;
75283
+ }
75284
+ if (opts.atomic) {
75285
+ if (event === EVENTS.UNLINK) {
75286
+ this._pendingUnlinks.set(path3, [event, ...args]);
75287
+ setTimeout(() => {
75288
+ this._pendingUnlinks.forEach((entry, path4) => {
75289
+ this.emit(...entry);
75290
+ this.emit(EVENTS.ALL, ...entry);
75291
+ this._pendingUnlinks.delete(path4);
75292
+ });
75293
+ }, typeof opts.atomic === "number" ? opts.atomic : 100);
75294
+ return this;
75295
+ }
75296
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path3)) {
75297
+ event = EVENTS.CHANGE;
75298
+ this._pendingUnlinks.delete(path3);
75299
+ }
75300
+ }
75301
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
75302
+ const awfEmit = (err, stats2) => {
75303
+ if (err) {
75304
+ event = EVENTS.ERROR;
75305
+ args[0] = err;
75306
+ this.emitWithAll(event, args);
75307
+ } else if (stats2) {
75308
+ if (args.length > 1) {
75309
+ args[1] = stats2;
75310
+ } else {
75311
+ args.push(stats2);
75312
+ }
75313
+ this.emitWithAll(event, args);
75314
+ }
75315
+ };
75316
+ this._awaitWriteFinish(path3, awf.stabilityThreshold, event, awfEmit);
75317
+ return this;
75318
+ }
75319
+ if (event === EVENTS.CHANGE) {
75320
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path3, 50);
75321
+ if (isThrottled)
75322
+ return this;
75323
+ }
75324
+ if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
75325
+ const fullPath = opts.cwd ? sp2.join(opts.cwd, path3) : path3;
75326
+ let stats2;
75327
+ try {
75328
+ stats2 = await stat3(fullPath);
75329
+ } catch (err) {
75330
+ }
75331
+ if (!stats2 || this.closed)
75332
+ return;
75333
+ args.push(stats2);
75334
+ }
75335
+ this.emitWithAll(event, args);
75336
+ return this;
75337
+ }
75338
+ /**
75339
+ * Common handler for errors
75340
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
75341
+ */
75342
+ _handleError(error) {
75343
+ const code = error && error.code;
75344
+ if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
75345
+ this.emit(EVENTS.ERROR, error);
75346
+ }
75347
+ return error || this.closed;
75348
+ }
75349
+ /**
75350
+ * Helper utility for throttling
75351
+ * @param actionType type being throttled
75352
+ * @param path being acted upon
75353
+ * @param timeout duration of time to suppress duplicate actions
75354
+ * @returns tracking object or false if action should be suppressed
75355
+ */
75356
+ _throttle(actionType, path3, timeout) {
75357
+ if (!this._throttled.has(actionType)) {
75358
+ this._throttled.set(actionType, /* @__PURE__ */ new Map());
75359
+ }
75360
+ const action = this._throttled.get(actionType);
75361
+ if (!action)
75362
+ throw new Error("invalid throttle");
75363
+ const actionPath = action.get(path3);
75364
+ if (actionPath) {
75365
+ actionPath.count++;
75366
+ return false;
75367
+ }
75368
+ let timeoutObject;
75369
+ const clear = () => {
75370
+ const item = action.get(path3);
75371
+ const count = item ? item.count : 0;
75372
+ action.delete(path3);
75373
+ clearTimeout(timeoutObject);
75374
+ if (item)
75375
+ clearTimeout(item.timeoutObject);
75376
+ return count;
75377
+ };
75378
+ timeoutObject = setTimeout(clear, timeout);
75379
+ const thr = { timeoutObject, clear, count: 0 };
75380
+ action.set(path3, thr);
75381
+ return thr;
75382
+ }
75383
+ _incrReadyCount() {
75384
+ return this._readyCount++;
75385
+ }
75386
+ /**
75387
+ * Awaits write operation to finish.
75388
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
75389
+ * @param path being acted upon
75390
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
75391
+ * @param event
75392
+ * @param awfEmit Callback to be called when ready for event to be emitted.
75393
+ */
75394
+ _awaitWriteFinish(path3, threshold, event, awfEmit) {
75395
+ const awf = this.options.awaitWriteFinish;
75396
+ if (typeof awf !== "object")
75397
+ return;
75398
+ const pollInterval = awf.pollInterval;
75399
+ let timeoutHandler;
75400
+ let fullPath = path3;
75401
+ if (this.options.cwd && !sp2.isAbsolute(path3)) {
75402
+ fullPath = sp2.join(this.options.cwd, path3);
75403
+ }
75404
+ const now = /* @__PURE__ */ new Date();
75405
+ const writes = this._pendingWrites;
75406
+ function awaitWriteFinishFn(prevStat) {
75407
+ statcb(fullPath, (err, curStat) => {
75408
+ if (err || !writes.has(path3)) {
75409
+ if (err && err.code !== "ENOENT")
75410
+ awfEmit(err);
75411
+ return;
75412
+ }
75413
+ const now2 = Number(/* @__PURE__ */ new Date());
75414
+ if (prevStat && curStat.size !== prevStat.size) {
75415
+ writes.get(path3).lastChange = now2;
75416
+ }
75417
+ const pw = writes.get(path3);
75418
+ const df = now2 - pw.lastChange;
75419
+ if (df >= threshold) {
75420
+ writes.delete(path3);
75421
+ awfEmit(void 0, curStat);
75422
+ } else {
75423
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
75424
+ }
75425
+ });
75426
+ }
75427
+ if (!writes.has(path3)) {
75428
+ writes.set(path3, {
75429
+ lastChange: now,
75430
+ cancelWait: () => {
75431
+ writes.delete(path3);
75432
+ clearTimeout(timeoutHandler);
75433
+ return event;
75434
+ }
75435
+ });
75436
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
75437
+ }
75438
+ }
75439
+ /**
75440
+ * Determines whether user has asked to ignore this path.
75441
+ */
75442
+ _isIgnored(path3, stats) {
75443
+ if (this.options.atomic && DOT_RE.test(path3))
75444
+ return true;
75445
+ if (!this._userIgnored) {
75446
+ const { cwd } = this.options;
75447
+ const ign = this.options.ignored;
75448
+ const ignored = (ign || []).map(normalizeIgnored(cwd));
75449
+ const ignoredPaths = [...this._ignoredPaths];
75450
+ const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
75451
+ this._userIgnored = anymatch(list, void 0);
75452
+ }
75453
+ return this._userIgnored(path3, stats);
75454
+ }
75455
+ _isntIgnored(path3, stat4) {
75456
+ return !this._isIgnored(path3, stat4);
75457
+ }
75458
+ /**
75459
+ * Provides a set of common helpers and properties relating to symlink handling.
75460
+ * @param path file or directory pattern being watched
75461
+ */
75462
+ _getWatchHelpers(path3) {
75463
+ return new WatchHelper(path3, this.options.followSymlinks, this);
75464
+ }
75465
+ // Directory helpers
75466
+ // -----------------
75467
+ /**
75468
+ * Provides directory tracking objects
75469
+ * @param directory path of the directory
75470
+ */
75471
+ _getWatchedDir(directory) {
75472
+ const dir = sp2.resolve(directory);
75473
+ if (!this._watched.has(dir))
75474
+ this._watched.set(dir, new DirEntry(dir, this._boundRemove));
75475
+ return this._watched.get(dir);
75476
+ }
75477
+ // File helpers
75478
+ // ------------
75479
+ /**
75480
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
75481
+ */
75482
+ _hasReadPermissions(stats) {
75483
+ if (this.options.ignorePermissionErrors)
75484
+ return true;
75485
+ return Boolean(Number(stats.mode) & 256);
75486
+ }
75487
+ /**
75488
+ * Handles emitting unlink events for
75489
+ * files and directories, and via recursion, for
75490
+ * files and directories within directories that are unlinked
75491
+ * @param directory within which the following item is located
75492
+ * @param item base path of item/directory
75493
+ */
75494
+ _remove(directory, item, isDirectory) {
75495
+ const path3 = sp2.join(directory, item);
75496
+ const fullPath = sp2.resolve(path3);
75497
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path3) || this._watched.has(fullPath);
75498
+ if (!this._throttle("remove", path3, 100))
75499
+ return;
75500
+ if (!isDirectory && this._watched.size === 1) {
75501
+ this.add(directory, item, true);
75502
+ }
75503
+ const wp = this._getWatchedDir(path3);
75504
+ const nestedDirectoryChildren = wp.getChildren();
75505
+ nestedDirectoryChildren.forEach((nested) => this._remove(path3, nested));
75506
+ const parent = this._getWatchedDir(directory);
75507
+ const wasTracked = parent.has(item);
75508
+ parent.remove(item);
75509
+ if (this._symlinkPaths.has(fullPath)) {
75510
+ this._symlinkPaths.delete(fullPath);
75511
+ }
75512
+ let relPath = path3;
75513
+ if (this.options.cwd)
75514
+ relPath = sp2.relative(this.options.cwd, path3);
75515
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
75516
+ const event = this._pendingWrites.get(relPath).cancelWait();
75517
+ if (event === EVENTS.ADD)
75518
+ return;
75519
+ }
75520
+ this._watched.delete(path3);
75521
+ this._watched.delete(fullPath);
75522
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
75523
+ if (wasTracked && !this._isIgnored(path3))
75524
+ this._emit(eventName, path3);
75525
+ this._closePath(path3);
75526
+ }
75527
+ /**
75528
+ * Closes all watchers for a path
75529
+ */
75530
+ _closePath(path3) {
75531
+ this._closeFile(path3);
75532
+ const dir = sp2.dirname(path3);
75533
+ this._getWatchedDir(dir).remove(sp2.basename(path3));
75534
+ }
75535
+ /**
75536
+ * Closes only file-specific watchers
75537
+ */
75538
+ _closeFile(path3) {
75539
+ const closers = this._closers.get(path3);
75540
+ if (!closers)
75541
+ return;
75542
+ closers.forEach((closer) => closer());
75543
+ this._closers.delete(path3);
75544
+ }
75545
+ _addPathCloser(path3, closer) {
75546
+ if (!closer)
75547
+ return;
75548
+ let list = this._closers.get(path3);
75549
+ if (!list) {
75550
+ list = [];
75551
+ this._closers.set(path3, list);
75552
+ }
75553
+ list.push(closer);
75554
+ }
75555
+ _readdirp(root, opts) {
75556
+ if (this.closed)
75557
+ return;
75558
+ const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
75559
+ let stream = readdirp(root, options);
75560
+ this._streams.add(stream);
75561
+ stream.once(STR_CLOSE, () => {
75562
+ stream = void 0;
75563
+ });
75564
+ stream.once(STR_END, () => {
75565
+ if (stream) {
75566
+ this._streams.delete(stream);
75567
+ stream = void 0;
75568
+ }
75569
+ });
75570
+ return stream;
75571
+ }
75572
+ };
75573
+ function watch(paths, options = {}) {
75574
+ const watcher = new FSWatcher(options);
75575
+ watcher.add(paths);
75576
+ return watcher;
75577
+ }
75578
+
75579
+ // src/local/file-watcher.ts
75580
+ var DEFAULT_DEBOUNCE_MS = 500;
75581
+ function createFileWatcher(options) {
75582
+ const logger = getLogger().child("start-api-watch");
75583
+ const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
75584
+ const ignoreInitial = options.ignoreInitial !== false;
75585
+ const watcher = watch([...options.paths], {
75586
+ ignoreInitial,
75587
+ // Don't follow symlinks — asset directories under `cdk.out/asset.<hash>/`
75588
+ // are real directories; following symlinks would risk cycling into
75589
+ // `node_modules` or similar.
75590
+ followSymlinks: false,
75591
+ // Don't crash on permission errors.
75592
+ ignorePermissionErrors: true
75593
+ });
75594
+ let timer = null;
75595
+ let closed = false;
75596
+ const fire = () => {
75597
+ if (closed)
75598
+ return;
75599
+ if (timer)
75600
+ clearTimeout(timer);
75601
+ timer = setTimeout(() => {
75602
+ timer = null;
75603
+ if (closed)
75604
+ return;
75605
+ try {
75606
+ options.onChange();
75607
+ } catch (err) {
75608
+ logger.warn(`onChange callback threw: ${err instanceof Error ? err.message : String(err)}`);
75609
+ }
75610
+ }, debounceMs);
75611
+ timer.unref?.();
75612
+ };
75613
+ watcher.on("add", fire);
75614
+ watcher.on("change", fire);
75615
+ watcher.on("unlink", fire);
75616
+ watcher.on("error", (err) => {
75617
+ logger.debug(
75618
+ `chokidar error: ${err instanceof Error ? err.message : String(err)}. Continuing.`
75619
+ );
75620
+ });
75621
+ let currentPaths = new Set(options.paths);
75622
+ return {
75623
+ update: (paths) => {
75624
+ if (closed)
75625
+ return;
75626
+ const next = new Set(paths);
75627
+ const toAdd = [];
75628
+ const toRemove = [];
75629
+ for (const p of next)
75630
+ if (!currentPaths.has(p))
75631
+ toAdd.push(p);
75632
+ for (const p of currentPaths)
75633
+ if (!next.has(p))
75634
+ toRemove.push(p);
75635
+ if (toAdd.length > 0)
75636
+ watcher.add(toAdd);
75637
+ if (toRemove.length > 0)
75638
+ watcher.unwatch(toRemove);
75639
+ currentPaths = next;
75640
+ },
75641
+ close: async () => {
75642
+ closed = true;
75643
+ if (timer) {
75644
+ clearTimeout(timer);
75645
+ timer = null;
75646
+ }
75647
+ await watcher.close();
75648
+ }
75649
+ };
75650
+ }
75651
+
75652
+ // src/local/reload-orchestrator.ts
75653
+ function createReloadOrchestrator(deps) {
75654
+ const logger = getLogger().child("start-api-reload");
75655
+ let chain = Promise.resolve();
75656
+ return {
75657
+ reload() {
75658
+ const next = chain.then(() => runOneReload(deps, logger));
75659
+ chain = next.catch(() => void 0);
75660
+ return next;
75661
+ }
75662
+ };
75663
+ }
75664
+ async function runOneReload(deps, logger) {
75665
+ const previousState = deps.getServerState();
75666
+ const start = Date.now();
75667
+ let material;
75668
+ try {
75669
+ material = await deps.synthesizeAndBuild();
75670
+ } catch (err) {
75671
+ const reason = err instanceof Error ? err.message : String(err);
75672
+ logger.warn(`cdk synth failed during reload; keeping previous version. (${reason})`);
75673
+ return { ok: false, reason, added: [], removed: [], rebuiltLambdas: [] };
75674
+ }
75675
+ const oldRoutes = previousState.routes;
75676
+ const newRoutes = material.routes;
75677
+ const oldKeys = new Set(oldRoutes.map((r) => routeKey(r.route)));
75678
+ const newKeys = new Set(newRoutes.map((r) => routeKey(r.route)));
75679
+ const added = newRoutes.filter((r) => !oldKeys.has(routeKey(r.route)));
75680
+ const removed = oldRoutes.filter((r) => !newKeys.has(routeKey(r.route)));
75681
+ const previousSpecs = pickSpecsFromState(previousState);
75682
+ const rebuiltLambdas = [];
75683
+ for (const [logicalId, newSpec] of material.specs) {
75684
+ const oldSpec = previousSpecs.get(logicalId);
75685
+ if (!oldSpec)
75686
+ continue;
75687
+ if (specSignature(oldSpec) !== specSignature(newSpec)) {
75688
+ rebuiltLambdas.push(logicalId);
75689
+ }
75690
+ }
75691
+ const newPool = deps.buildPool(material.specs);
75692
+ Object.defineProperty(newPool, "__cdkdSpecs", {
75693
+ value: material.specs,
75694
+ enumerable: false,
75695
+ configurable: true
75696
+ });
75697
+ const newState = {
75698
+ routes: material.routes,
75699
+ pool: newPool,
75700
+ corsConfigByApiId: material.corsConfigByApiId
75701
+ };
75702
+ deps.setServerState(newState);
75703
+ void previousState.pool.dispose().catch(
75704
+ (err) => logger.debug(
75705
+ `Previous pool dispose() failed: ${err instanceof Error ? err.message : String(err)}`
75706
+ )
75707
+ );
75708
+ const elapsed = Date.now() - start;
75709
+ logger.info(
75710
+ `Reloaded in ${elapsed}ms: +${added.length} route(s), -${removed.length} route(s), ${rebuiltLambdas.length} Lambda(s) rebuilt.`
75711
+ );
75712
+ return {
75713
+ ok: true,
75714
+ added,
75715
+ removed,
75716
+ rebuiltLambdas,
75717
+ newState
75718
+ };
75719
+ }
75720
+ function routeKey(route) {
75721
+ return [route.method, route.pathPattern, route.lambdaLogicalId, route.source, route.apiVersion].map((s) => String(s)).join("|");
75722
+ }
75723
+ function specSignature(spec) {
75724
+ return JSON.stringify({
75725
+ codeDir: spec.codeDir,
75726
+ env: spec.env,
75727
+ handler: spec.lambda.handler,
75728
+ runtime: spec.lambda.runtime,
75729
+ containerHost: spec.containerHost,
75730
+ debugPort: spec.debugPort ?? null
75731
+ });
75732
+ }
75733
+ function pickSpecsFromState(state) {
75734
+ const tagged = state.pool.__cdkdSpecs;
75735
+ return tagged ?? /* @__PURE__ */ new Map();
75736
+ }
75737
+
73465
75738
  // src/local/authorizer-cache.ts
73466
75739
  function createAuthorizerCache(opts = {}) {
73467
75740
  const now = opts.now ?? (() => Date.now());
@@ -73515,67 +75788,123 @@ async function localStartApiCommand(options) {
73515
75788
  if (!appCmd) {
73516
75789
  throw new Error('No CDK app specified. Pass --app, set CDKD_APP, or add "app" to cdk.json.');
73517
75790
  }
73518
- logger.info("Synthesizing CDK app...");
73519
- const synthesizer = new Synthesizer();
73520
- const context = parseContextOptions(options.context);
73521
- const synthOpts = {
73522
- app: appCmd,
73523
- output: options.output,
73524
- ...options.region && { region: options.region },
73525
- ...options.profile && { profile: options.profile },
73526
- ...Object.keys(context).length > 0 && { context }
73527
- };
73528
- const { stacks } = await synthesizer.synthesize(synthOpts);
73529
- const targetStacks = pickTargetStacks(stacks, options.stack);
73530
- if (targetStacks.length === 0) {
73531
- throw new Error("No stacks matched. Pass --stack <name> or run from a single-stack app.");
73532
- }
73533
- const routes = discoverRoutes(targetStacks);
73534
- if (routes.length === 0) {
73535
- throw new Error(
73536
- "No supported API routes were discovered. cdkd local start-api supports AWS::ApiGateway::* (REST v1), AWS::ApiGatewayV2::* (HTTP), and AWS::Lambda::Url (Function URL) with AWS_PROXY integrations only."
73537
- );
73538
- }
73539
- const routesWithAuth = attachAuthorizers(targetStacks, routes);
73540
- const lambdaIds = uniqueLambdaIds(routes, routesWithAuth);
73541
75791
  const overrides = readEnvOverridesFile(options.envVars);
73542
75792
  const debugPortBase = options.debugPortBase ? parseDebugPort(options.debugPortBase) : void 0;
73543
- const specs = /* @__PURE__ */ new Map();
75793
+ const perLambdaConcurrency = parsePerLambdaConcurrency(options.perLambdaConcurrency);
73544
75794
  const inlineTmpDirs = /* @__PURE__ */ new Set();
73545
75795
  const layerTmpDirs = /* @__PURE__ */ new Set();
73546
- for (let i = 0; i < lambdaIds.length; i++) {
73547
- const logicalId = lambdaIds[i];
73548
- const spec = await buildContainerSpec({
73549
- logicalId,
73550
- stacks: targetStacks,
73551
- overrides,
73552
- assumeRole: options.assumeRole,
73553
- containerHost: options.containerHost,
73554
- ...debugPortBase !== void 0 && { debugPort: debugPortBase + i },
73555
- stsRegion: options.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"],
73556
- inlineTmpDirs,
73557
- layerTmpDirs
75796
+ const lastAssetPaths = { value: [] };
75797
+ const authorizerCache = createAuthorizerCache();
75798
+ const jwksCache = createJwksCache();
75799
+ const jwksWarnedUrls = /* @__PURE__ */ new Set();
75800
+ const synthesizeAndBuild = async () => {
75801
+ logger.info("Synthesizing CDK app...");
75802
+ const synthesizer = new Synthesizer();
75803
+ const context = parseContextOptions(options.context);
75804
+ const synthOpts = {
75805
+ app: appCmd,
75806
+ output: options.output,
75807
+ ...options.region && { region: options.region },
75808
+ ...options.profile && { profile: options.profile },
75809
+ ...Object.keys(context).length > 0 && { context }
75810
+ };
75811
+ const { stacks } = await synthesizer.synthesize(synthOpts);
75812
+ const targetStacks = pickTargetStacks(stacks, options.stack);
75813
+ if (targetStacks.length === 0) {
75814
+ throw new Error("No stacks matched. Pass --stack <name> or run from a single-stack app.");
75815
+ }
75816
+ const routes = discoverRoutes(targetStacks);
75817
+ if (routes.length === 0) {
75818
+ throw new Error(
75819
+ "No supported API routes were discovered. cdkd local start-api supports AWS::ApiGateway::* (REST v1), AWS::ApiGatewayV2::* (HTTP), and AWS::Lambda::Url (Function URL) with AWS_PROXY integrations only."
75820
+ );
75821
+ }
75822
+ const stageMap = /* @__PURE__ */ new Map();
75823
+ for (const stack of targetStacks) {
75824
+ const m = buildStageMap(stack.template, options.stage);
75825
+ for (const [k, v] of m)
75826
+ stageMap.set(k, v);
75827
+ }
75828
+ if (options.stage) {
75829
+ const missingApis = /* @__PURE__ */ new Set();
75830
+ for (const r of routes) {
75831
+ if (!r.apiLogicalId)
75832
+ continue;
75833
+ if (!stageMap.has(r.apiLogicalId))
75834
+ missingApis.add(r.apiLogicalId);
75835
+ }
75836
+ for (const apiId of missingApis) {
75837
+ logger.warn(
75838
+ `--stage '${options.stage}' did not match any Stage on API '${apiId}'; routes on that API will get stageVariables: null.`
75839
+ );
75840
+ }
75841
+ }
75842
+ attachStageContext(routes, stageMap);
75843
+ const routesWithAuth = attachAuthorizers(targetStacks, routes);
75844
+ const corsConfigByApiId = /* @__PURE__ */ new Map();
75845
+ for (const stack of targetStacks) {
75846
+ const m = buildCorsConfigByApiId(stack.template);
75847
+ for (const [k, v] of m)
75848
+ corsConfigByApiId.set(k, v);
75849
+ }
75850
+ const lambdaIds = uniqueLambdaIds(routes, routesWithAuth);
75851
+ const specs = /* @__PURE__ */ new Map();
75852
+ for (let i = 0; i < lambdaIds.length; i++) {
75853
+ const logicalId = lambdaIds[i];
75854
+ const spec = await buildContainerSpec({
75855
+ logicalId,
75856
+ stacks: targetStacks,
75857
+ overrides,
75858
+ assumeRole: options.assumeRole,
75859
+ containerHost: options.containerHost,
75860
+ ...debugPortBase !== void 0 && { debugPort: debugPortBase + i },
75861
+ stsRegion: options.region ?? process.env["AWS_REGION"] ?? process.env["AWS_DEFAULT_REGION"],
75862
+ inlineTmpDirs,
75863
+ layerTmpDirs
75864
+ });
75865
+ specs.set(logicalId, spec);
75866
+ }
75867
+ const distinctImages = /* @__PURE__ */ new Set();
75868
+ for (const spec of specs.values()) {
75869
+ distinctImages.add(resolveRuntimeImage(spec.lambda.runtime));
75870
+ }
75871
+ for (const image of distinctImages) {
75872
+ await pullImage(image, options.pull === false);
75873
+ }
75874
+ return { routes: routesWithAuth, specs, corsConfigByApiId, stacks: targetStacks };
75875
+ };
75876
+ const buildPool = (specs) => {
75877
+ const pool = createContainerPool(specs, {
75878
+ perLambdaConcurrency,
75879
+ skipPull: options.pull === false
73558
75880
  });
73559
- specs.set(logicalId, spec);
73560
- }
73561
- const distinctImages = /* @__PURE__ */ new Set();
73562
- for (const spec of specs.values()) {
73563
- distinctImages.add(resolveRuntimeImage(spec.lambda.runtime));
73564
- }
73565
- for (const image of distinctImages) {
73566
- await pullImage(image, options.pull === false);
73567
- }
73568
- const perLambdaConcurrency = parsePerLambdaConcurrency(options.perLambdaConcurrency);
73569
- const pool = createContainerPool(specs, {
73570
- perLambdaConcurrency,
73571
- skipPull: options.pull === false
73572
- });
75881
+ Object.defineProperty(pool, "__cdkdSpecs", {
75882
+ value: specs,
75883
+ enumerable: false,
75884
+ configurable: true
75885
+ });
75886
+ return pool;
75887
+ };
75888
+ const computeAssetPaths = (specs) => {
75889
+ const assetPaths = /* @__PURE__ */ new Set();
75890
+ for (const spec of specs.values()) {
75891
+ assetPaths.add(spec.codeDir);
75892
+ }
75893
+ return [...assetPaths];
75894
+ };
75895
+ const initialMaterial = await synthesizeAndBuild();
75896
+ const initialPool = buildPool(initialMaterial.specs);
75897
+ lastAssetPaths.value = computeAssetPaths(initialMaterial.specs);
75898
+ await prewarmJwks(initialMaterial.routes, jwksCache);
75899
+ warnVpcConfigLambdas(initialMaterial.routes, initialMaterial.stacks ?? []);
73573
75900
  if (options.warm) {
73574
- logger.info(`Pre-warming ${specs.size} container(s)...`);
73575
- const handles = await Promise.allSettled([...specs.keys()].map((id) => pool.acquire(id)));
75901
+ logger.info(`Pre-warming ${initialMaterial.specs.size} container(s)...`);
75902
+ const handles = await Promise.allSettled(
75903
+ [...initialMaterial.specs.keys()].map((id) => initialPool.acquire(id))
75904
+ );
73576
75905
  for (const result of handles) {
73577
75906
  if (result.status === "fulfilled") {
73578
- pool.release(result.value);
75907
+ initialPool.release(result.value);
73579
75908
  } else {
73580
75909
  logger.warn(
73581
75910
  `Pre-warm failed for one Lambda (cold start cost will apply on first request): ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`
@@ -73584,7 +75913,7 @@ async function localStartApiCommand(options) {
73584
75913
  }
73585
75914
  }
73586
75915
  let maxTimeoutSec = 0;
73587
- for (const spec of specs.values()) {
75916
+ for (const spec of initialMaterial.specs.values()) {
73588
75917
  if (spec.lambda.timeoutSec > maxTimeoutSec)
73589
75918
  maxTimeoutSec = spec.lambda.timeoutSec;
73590
75919
  }
@@ -73593,14 +75922,13 @@ async function localStartApiCommand(options) {
73593
75922
  if (!Number.isFinite(port) || port < 0 || port > 65535) {
73594
75923
  throw new Error(`--port must be 0..65535 (got ${options.port}).`);
73595
75924
  }
73596
- const authorizerCache = createAuthorizerCache();
73597
- const jwksCache = createJwksCache();
73598
- const jwksWarnedUrls = /* @__PURE__ */ new Set();
73599
- await prewarmJwks(routesWithAuth, jwksCache);
73600
- warnVpcConfigLambdas(routesWithAuth, targetStacks);
75925
+ const initialState = {
75926
+ routes: initialMaterial.routes,
75927
+ pool: initialPool,
75928
+ corsConfigByApiId: initialMaterial.corsConfigByApiId
75929
+ };
73601
75930
  const server = await startApiServer({
73602
- routes: routesWithAuth,
73603
- pool,
75931
+ state: initialState,
73604
75932
  rieTimeoutMs,
73605
75933
  host: options.host,
73606
75934
  port,
@@ -73608,13 +75936,49 @@ async function localStartApiCommand(options) {
73608
75936
  jwksCache,
73609
75937
  jwksWarnedUrls
73610
75938
  });
73611
- printRouteTable(routes);
75939
+ printRouteTable(initialMaterial.routes);
73612
75940
  logger.info(
73613
75941
  `Per-Lambda concurrency: ${perLambdaConcurrency} (override with --per-lambda-concurrency)`
73614
75942
  );
73615
75943
  process.stdout.write(`Server listening on http://${server.host}:${server.port}
73616
75944
  `);
73617
75945
  process.stdout.write("^C to stop and clean up containers.\n");
75946
+ let watcher;
75947
+ let orchestrator;
75948
+ if (options.watch) {
75949
+ orchestrator = createReloadOrchestrator({
75950
+ synthesizeAndBuild,
75951
+ buildPool,
75952
+ setServerState: server.setServerState,
75953
+ getServerState: server.getServerState
75954
+ });
75955
+ const initialWatchPaths = [options.output, ...lastAssetPaths.value];
75956
+ watcher = createFileWatcher({
75957
+ paths: initialWatchPaths,
75958
+ onChange: () => {
75959
+ if (!orchestrator)
75960
+ return;
75961
+ logger.info("Detected file change; reloading...");
75962
+ void orchestrator.reload().then((result) => {
75963
+ if (result.ok && watcher && result.newState) {
75964
+ const taggedSpecs = result.newState.pool.__cdkdSpecs;
75965
+ if (taggedSpecs) {
75966
+ lastAssetPaths.value = computeAssetPaths(taggedSpecs);
75967
+ }
75968
+ watcher.update([options.output, ...lastAssetPaths.value]);
75969
+ if (result.added.length > 0 || result.removed.length > 0) {
75970
+ printRouteTable(result.newState.routes);
75971
+ }
75972
+ }
75973
+ }).catch((err) => {
75974
+ logger.warn(
75975
+ `Reload failed: ${err instanceof Error ? err.message : String(err)}. Keeping previous version.`
75976
+ );
75977
+ });
75978
+ }
75979
+ });
75980
+ logger.info(`Watching ${options.output} (and ${lastAssetPaths.value.length} asset dir(s))`);
75981
+ }
73618
75982
  let shuttingDown = false;
73619
75983
  let forceExitArmed = false;
73620
75984
  const shutdown = async (signal, exitCode) => {
@@ -73630,13 +75994,20 @@ async function localStartApiCommand(options) {
73630
75994
  }
73631
75995
  shuttingDown = true;
73632
75996
  logger.info(`Received ${signal}, shutting down...`);
75997
+ if (watcher) {
75998
+ try {
75999
+ await watcher.close();
76000
+ } catch (err) {
76001
+ logger.warn(`watcher.close() failed: ${err instanceof Error ? err.message : String(err)}`);
76002
+ }
76003
+ }
73633
76004
  try {
73634
76005
  await server.close();
73635
76006
  } catch (err) {
73636
76007
  logger.warn(`server.close() failed: ${err instanceof Error ? err.message : String(err)}`);
73637
76008
  }
73638
76009
  try {
73639
- await pool.dispose();
76010
+ await server.getServerState().pool.dispose();
73640
76011
  } catch (err) {
73641
76012
  logger.warn(`pool.dispose() failed: ${err instanceof Error ? err.message : String(err)}`);
73642
76013
  }
@@ -73895,7 +76266,8 @@ function resolveAssetCodePath2(stack, logicalId, resource) {
73895
76266
  return path.isAbsolute(assetPath) ? assetPath : path.resolve(cdkOutDir, assetPath);
73896
76267
  }
73897
76268
  function printRouteTable(routes) {
73898
- const sorted = [...routes].sort((a, b) => {
76269
+ const flat = routes.map((r) => r.route);
76270
+ const sorted = [...flat].sort((a, b) => {
73899
76271
  if (a.pathPattern !== b.pathPattern)
73900
76272
  return a.pathPattern.localeCompare(b.pathPattern);
73901
76273
  return a.method.localeCompare(b.method);
@@ -74049,6 +76421,16 @@ function createLocalStartApiCommand() {
74049
76421
  "--assume-role <arn-or-pair>",
74050
76422
  "Assume the Lambda's execution role and forward STS-issued temp creds. Bare <arn> = global default; <LogicalId>=<arn> = per-Lambda override (repeatable). Per-Lambda > global > unset (developer creds passed through)."
74051
76423
  ).argParser((raw, prev) => parseAssumeRoleToken(raw, prev))
76424
+ ).addOption(
76425
+ new Option7(
76426
+ "--watch",
76427
+ "Hot-reload: re-synth + re-discover routes when cdk.out/ or asset directories change. Off by default; the server keeps the previous version serving when synth fails mid-reload."
76428
+ ).default(false)
76429
+ ).addOption(
76430
+ new Option7(
76431
+ "--stage <name>",
76432
+ "Select an API Gateway Stage by its 'StageName'. Default: the first Stage attached to each API. Drives event.stageVariables for both REST v1 and HTTP API v2. NOTE: For HTTP API v2 routes, requestContext.stage is always '$default' regardless of this flag (AWS-side limitation \u2014 HTTP API only exposes one stage to the integration event); only event.stageVariables is affected for v2 routes. For REST v1 routes the selected StageName is also threaded into requestContext.stage."
76433
+ )
74052
76434
  ).action(withErrorHandling(localStartApiCommand));
74053
76435
  [...commonOptions, ...appOptions, ...contextOptions].forEach((opt) => startApi.addOption(opt));
74054
76436
  startApi.addOption(deprecatedRegionOption);
@@ -74329,7 +76711,7 @@ async function resolveLocalBuildPlan(lambda) {
74329
76711
  const manifestPath = lambda.stack.assetManifestPath;
74330
76712
  if (!manifestPath)
74331
76713
  return void 0;
74332
- const cdkOutDir = dirname3(manifestPath);
76714
+ const cdkOutDir = dirname5(manifestPath);
74333
76715
  const loader = new AssetManifestLoader();
74334
76716
  const manifest = await loader.loadManifest(cdkOutDir, lambda.stack.stackName);
74335
76717
  if (!manifest)
@@ -74633,7 +77015,7 @@ function reorderArgs(argv) {
74633
77015
  }
74634
77016
  async function main() {
74635
77017
  const program = new Command16();
74636
- program.name("cdkd").description("CDK Direct - Deploy AWS CDK apps directly via SDK/Cloud Control API").version("0.74.0");
77018
+ program.name("cdkd").description("CDK Direct - Deploy AWS CDK apps directly via SDK/Cloud Control API").version("0.75.0");
74637
77019
  program.addCommand(createBootstrapCommand());
74638
77020
  program.addCommand(createSynthCommand());
74639
77021
  program.addCommand(createListCommand());
@@ -74654,4 +77036,9 @@ main().catch((error) => {
74654
77036
  console.error("Fatal error:", error);
74655
77037
  process.exit(1);
74656
77038
  });
77039
+ /*! Bundled license information:
77040
+
77041
+ chokidar/index.js:
77042
+ (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
77043
+ */
74657
77044
  //# sourceMappingURL=cli.js.map