// cli/build-json-schema.ts
import { writeFileSync } from "node:fs";
import { join as join2 } from "node:path";
import { zodToJsonSchema } from "zod-to-json-schema";

// src/config/app.ts
import { z as z22 } from "zod";

// src/feature/alert/schema.ts
import { kebabCase } from "change-case";
import { z as z2 } from "zod";

// src/config/schema/email.ts
import { z } from "zod";
var EmailSchema = z.string().email();

// src/feature/alert/schema.ts
var AlertNameSchema = z2.string().min(3).max(256).regex(/^[a-z0-9\-]+$/i, "Invalid alert name").transform((value) => kebabCase(value)).describe("Define alert name.");
var AlertsDefaultSchema = z2.record(
  AlertNameSchema,
  z2.union([
    //
    EmailSchema.transform((v) => [v]),
    EmailSchema.array()
  ])
).optional().describe("Define the alerts in your app. Alerts are a way to send messages to one or more email addresses.");

// src/feature/auth/schema.ts
import { z as z5 } from "zod";

// src/config/schema/resource-id.ts
import { kebabCase as kebabCase2 } from "change-case";
import { z as z3 } from "zod";
var ResourceIdSchema = z3.string().min(3).max(24).regex(/^[a-z0-9\-]+$/i, "Invalid resource ID").transform((value) => kebabCase2(value));

// src/config/schema/duration.ts
import { parse } from "@awsless/duration";
import { z as z4 } from "zod";
var DurationSchema = z4.string().regex(/^[0-9]+ (seconds?|minutes?|hours?|days?|weeks?)$/, "Invalid duration").transform((v) => parse(v));
var durationMin = (min) => {
  return (duration) => {
    return duration.value >= min.value;
  };
};
var durationMax = (max) => {
  return (duration) => {
    return duration.value <= max.value;
  };
};

// src/feature/auth/schema.ts
var AuthDefaultSchema = z5.record(
  ResourceIdSchema,
  z5.object({
    allowUserRegistration: z5.boolean().default(true).describe("Specifies whether users can create an user account or if only the administrator can."),
    // messaging: z
    // 	.object({
    // 		fromEmail: EmailSchema.describe("Specifies the sender's email address."),
    // 		fromName: z.string().optional().describe("Specifies the sender's name."),
    // 		replyTo: EmailSchema.optional().describe(
    // 			'The destination to which the receiver of the email should reply.'
    // 		),
    // 	})
    // 	.optional()
    // 	.describe('The email configuration for sending messages.'),
    // secret: z.boolean().default(false).describe('Specifies whether you want to generate a client secret.'),
    username: z5.object({
      // emailAlias: z.boolean().default(true).describe('Allow the user email to be used as username.'),
      caseSensitive: z5.boolean().default(false).describe(
        "Specifies whether username case sensitivity will be enabled. When usernames and email addresses are case insensitive, users can sign in as the same user when they enter a different capitalization of their user name."
      )
    }).default({}).describe("The username policy."),
    password: z5.object({
      minLength: z5.number().int().min(6).max(99).default(12).describe("Required users to have at least the minimum password length."),
      uppercase: z5.boolean().default(true).describe("Required users to use at least one uppercase letter in their password."),
      lowercase: z5.boolean().default(true).describe("Required users to use at least one lowercase letter in their password."),
      numbers: z5.boolean().default(true).describe("Required users to use at least one number in their password."),
      symbols: z5.boolean().default(true).describe("Required users to use at least one symbol in their password."),
      temporaryPasswordValidity: DurationSchema.default("7 days").describe(
        "The duration a temporary password is valid. If the user doesn't sign in during this time, an administrator must reset their password."
      )
    }).default({}).describe("The password policy."),
    validity: z5.object({
      idToken: DurationSchema.default("1 hour").describe(
        "The ID token time limit. After this limit expires, your user can't use their ID token."
      ),
      accessToken: DurationSchema.default("1 hour").describe(
        "The access token time limit. After this limit expires, your user can't use their access token."
      ),
      refreshToken: DurationSchema.default("365 days").describe(
        "The refresh token time limit. After this limit expires, your user can't use their refresh token."
      )
    }).default({}).describe("Specifies the validity duration for every JWT token.")
    // triggers: TriggersSchema.optional(),
  })
).default({}).describe("Define the authenticatable users in your app.");

// src/feature/domain/schema.ts
import { z as z6 } from "zod";
var DomainNameSchema = z6.string().regex(/[a-z\-\_\.]/g, "Invalid domain name").describe(
  "Enter a fully qualified domain name, for example, www.example.com. You can optionally include a trailing dot. If you omit the trailing dot, Amazon Route 53 assumes that the domain name that you specify is fully qualified. This means that Route 53 treats www.example.com (without a trailing dot) and www.example.com. (with a trailing dot) as identical."
);
var DNSTypeSchema = z6.enum(["A", "AAAA", "CAA", "CNAME", "DS", "MX", "NAPTR", "NS", "PTR", "SOA", "SPF", "SRV", "TXT"]).describe("The DNS record type.");
var TTLSchema = DurationSchema.describe("The resource record cache time to live (TTL).");
var RecordsSchema = z6.string().array().describe("One or more values that correspond with the value that you specified for the Type property.");
var DomainsDefaultSchema = z6.record(
  ResourceIdSchema,
  z6.object({
    domain: DomainNameSchema.describe("Define the domain name"),
    dns: z6.object({
      name: DomainNameSchema.optional(),
      type: DNSTypeSchema,
      ttl: TTLSchema,
      records: RecordsSchema
    }).array().optional().describe("Define the domain dns records")
  })
).optional().describe("Define the domains for your application.");

// src/feature/function/schema.ts
import { days, minutes, seconds, toDays } from "@awsless/duration";
import { gibibytes, mebibytes } from "@awsless/size";
import { z as z11 } from "zod";

// src/config/schema/local-directory.ts
import { stat } from "fs/promises";
import { z as z8 } from "zod";

// src/config/schema/relative-path.ts
import { join } from "path";
import { z as z7 } from "zod";
var basePath;
var resolvePath = (path) => {
  if (path.startsWith(".") && basePath) {
    return join(basePath, path);
  }
  return path;
};
var RelativePathSchema = z7.string().transform((path) => resolvePath(path));

// src/config/schema/local-directory.ts
var LocalDirectorySchema = z8.union([
  RelativePathSchema.refine(async (path) => {
    try {
      const s = await stat(path);
      return s.isDirectory();
    } catch (error) {
      return false;
    }
  }, `Directory doesn't exist`),
  z8.object({
    nocheck: RelativePathSchema.describe(
      "Specifies a local directory without checking if the directory exists."
    )
  }).transform((v) => v.nocheck)
]);

// src/config/schema/local-file.ts
import { stat as stat2 } from "fs/promises";
import { z as z9 } from "zod";
var LocalFileSchema = z9.union([
  RelativePathSchema.refine(async (path) => {
    try {
      const s = await stat2(path);
      return s.isFile();
    } catch (error) {
      return false;
    }
  }, `File doesn't exist`),
  z9.object({
    nocheck: RelativePathSchema.describe("Specifies a local file without checking if the file exists.")
  }).transform((v) => v.nocheck)
]);

// src/config/schema/size.ts
import { parse as parse2 } from "@awsless/size";
import { z as z10 } from "zod";
var SizeSchema = z10.string().regex(/^[0-9]+ (B|KB|MB|GB|TB|PB)$/, "Invalid size").transform((v) => parse2(v));
var sizeMin = (min) => {
  return (size) => {
    return size.value >= min.value;
  };
};
var sizeMax = (max) => {
  return (size) => {
    return size.value <= max.value;
  };
};

// src/feature/function/schema.ts
var MemorySizeSchema = SizeSchema.refine(sizeMin(mebibytes(128)), "Minimum memory size is 128 MB").refine(sizeMax(gibibytes(10)), "Maximum memory size is 10 GB").describe(
  "The amount of memory available to the function at runtime. Increasing the function memory also increases its CPU allocation. The value can be any multiple of 1 MB. You can specify a size value from 128 MB to 10 GB."
);
var TimeoutSchema = DurationSchema.refine(durationMin(seconds(10)), "Minimum timeout duration is 10 seconds").refine(durationMax(minutes(15)), "Maximum timeout duration is 15 minutes").describe(
  "The amount of time that Lambda allows a function to run before stopping it. You can specify a size value from 1 second to 15 minutes."
);
var EphemeralStorageSizeSchema = SizeSchema.refine(
  sizeMin(mebibytes(512)),
  "Minimum ephemeral storage size is 512 MB"
).refine(sizeMax(gibibytes(10)), "Minimum ephemeral storage size is 10 GB").describe("The size of the function's /tmp directory. You can specify a size value from 512 MB to 10 GB.");
var ReservedConcurrentExecutionsSchema = z11.number().int().min(0).describe("The number of simultaneous executions to reserve for the function. You can specify a number from 0.");
var EnvironmentSchema = z11.record(z11.string(), z11.string()).optional().describe("Environment variable key-value pairs.");
var ArchitectureSchema = z11.enum(["x86_64", "arm64"]).describe("The instruction set architecture that the function supports.");
var RetryAttemptsSchema = z11.number().int().min(0).max(2).describe(
  "The maximum number of times to retry when the function returns an error. You can specify a number from 0 to 2."
);
var NodeRuntimeSchema = z11.enum(["nodejs18.x", "nodejs20.x", "nodejs22.x"]);
var ContainerRuntimeSchema = z11.literal("container");
var RuntimeSchema = NodeRuntimeSchema.or(ContainerRuntimeSchema).or(z11.string()).describe("The identifier of the function's runtime.");
var ActionSchema = z11.string();
var ActionsSchema = z11.union([ActionSchema.transform((v) => [v]), ActionSchema.array()]);
var ArnSchema = z11.string().startsWith("arn:");
var WildcardSchema = z11.literal("*");
var ResourceSchema = z11.union([ArnSchema, WildcardSchema]);
var ResourcesSchema = z11.union([ResourceSchema.transform((v) => [v]), ResourceSchema.array()]);
var PermissionSchema = z11.object({
  effect: z11.enum(["allow", "deny"]).default("allow"),
  actions: ActionsSchema,
  resources: ResourcesSchema
});
var PermissionsSchema = z11.union([PermissionSchema.transform((v) => [v]), PermissionSchema.array()]).describe("Add IAM permissions to your function.");
var WarmSchema = z11.number().int().min(0).max(10).describe("Specify how many functions you want to warm up each 5 minutes. You can specify a number from 0 to 10.");
var VPCSchema = z11.boolean().describe("Put the function inside your global VPC.");
var MinifySchema = z11.boolean().describe("Minify the function code.");
var HandlerSchema = z11.string().describe("The name of the exported method within your code that Lambda calls to run your function.");
var DescriptionSchema = z11.string().describe("A description of the function.");
var validLogRetentionDays = [
  ...[1, 3, 5, 7, 14, 30, 60, 90, 120, 150],
  ...[180, 365, 400, 545, 731, 1096, 1827, 2192],
  ...[2557, 2922, 3288, 3653]
];
var LogRetentionSchema = DurationSchema.refine(
  durationMin(days(0)),
  "Minimum log retention is 0 day, which will disable logging."
).refine(
  (duration) => {
    return validLogRetentionDays.includes(toDays(duration));
  },
  `Invalid log retention. Valid days are: ${validLogRetentionDays.map((days4) => `${days4}`).join(", ")}`
).describe("The log retention duration.");
var LogSchema = z11.union([
  z11.boolean().transform((enabled) => ({ retention: enabled ? days(7) : days(0) })),
  LogRetentionSchema.transform((retention) => ({ retention })),
  z11.object({
    // subscription: LogSubscriptionSchema.optional(),
    retention: LogRetentionSchema.optional(),
    format: z11.enum(["text", "json"]).describe(
      `The format in which Lambda sends your function's application and system logs to CloudWatch. Select between plain text and structured JSON.`
    ).optional(),
    system: z11.enum(["debug", "info", "warn"]).describe(
      "Set this property to filter the system logs for your function that Lambda sends to CloudWatch. Lambda only sends system logs at the selected level of detail and lower, where DEBUG is the highest level and WARN is the lowest."
    ).optional(),
    level: z11.enum(["trace", "debug", "info", "warn", "error", "fatal"]).describe(
      "Set this property to filter the application logs for your function that Lambda sends to CloudWatch. Lambda only sends application logs at the selected level of detail and lower, where TRACE is the highest level and FATAL is the lowest."
    ).optional()
  })
]).describe("Enable logging to a CloudWatch log group. Providing a duration value will set the log retention time.");
var LayersSchema = z11.string().array().describe(
  // `A list of function layers to add to the function's execution environment..`
  `A list of function layers to add to the function's execution environment. Specify each layer by its ARN, including the version.`
);
var FileCodeSchema = z11.object({
  file: LocalFileSchema.describe("The file path of the function code."),
  minify: MinifySchema.optional().default(true),
  external: z11.string().array().optional().describe(`A list of external packages that won't be included in the bundle.`)
});
var BundleCodeSchema = z11.object({
  bundle: LocalDirectorySchema.describe("The directory that needs to be bundled.")
});
var CodeSchema = z11.union([
  LocalFileSchema.transform((file) => ({
    file
  })).pipe(FileCodeSchema),
  FileCodeSchema,
  BundleCodeSchema
]).describe("Specify the code of your function.");
var FnSchema = z11.object({
  code: CodeSchema,
  // node
  handler: HandlerSchema.optional(),
  // build: BuildSchema.optional(),
  // bundle: BundleSchema.optional(),
  // container
  // ...
  runtime: RuntimeSchema.optional(),
  description: DescriptionSchema.optional(),
  warm: WarmSchema.optional(),
  vpc: VPCSchema.optional(),
  log: LogSchema.optional(),
  timeout: TimeoutSchema.optional(),
  memorySize: MemorySizeSchema.optional(),
  architecture: ArchitectureSchema.optional(),
  ephemeralStorageSize: EphemeralStorageSizeSchema.optional(),
  retryAttempts: RetryAttemptsSchema.optional(),
  reserved: ReservedConcurrentExecutionsSchema.optional(),
  layers: LayersSchema.optional(),
  environment: EnvironmentSchema.optional(),
  permissions: PermissionsSchema.optional()
});
var FunctionSchema = z11.union([
  LocalFileSchema.transform((code) => ({
    code
  })).pipe(FnSchema),
  FnSchema
]);
var FunctionsSchema = z11.record(ResourceIdSchema, FunctionSchema).optional().describe("Define the functions in your stack.");
var FunctionDefaultSchema = z11.object({
  runtime: RuntimeSchema.default("nodejs20.x"),
  // node
  handler: HandlerSchema.default("index.default"),
  // build: BuildSchema.default({
  // 	type: 'simple',
  // 	minify: true,
  // }),
  // container
  warm: WarmSchema.default(0),
  vpc: VPCSchema.default(false),
  log: LogSchema.default(true).transform((log) => ({
    retention: log.retention ?? days(7),
    level: "level" in log ? log.level : "error",
    system: "system" in log ? log.system : "warn",
    format: "format" in log ? log.format : "json"
  })),
  timeout: TimeoutSchema.default("10 seconds"),
  memorySize: MemorySizeSchema.default("128 MB"),
  architecture: ArchitectureSchema.default("arm64"),
  ephemeralStorageSize: EphemeralStorageSizeSchema.default("512 MB"),
  retryAttempts: RetryAttemptsSchema.default(2),
  reserved: ReservedConcurrentExecutionsSchema.optional(),
  layers: LayersSchema.optional(),
  environment: EnvironmentSchema.optional(),
  permissions: PermissionsSchema.optional()
}).default({});

// src/feature/layer/schema.ts
import { z as z13 } from "zod";

// src/config/schema/lambda.ts
import { z as z12 } from "zod";
var ArchitectureSchema2 = z12.enum(["x86_64", "arm64"]).describe("The instruction set architecture that the function supports.");
var NodeRuntimeSchema2 = z12.enum(["nodejs18.x", "nodejs20.x", "nodejs22.x"]).describe("The identifier of the function's runtime.");

// src/feature/layer/schema.ts
var Schema = z13.object({
  file: LocalFileSchema,
  runtimes: NodeRuntimeSchema2.array().optional(),
  architecture: ArchitectureSchema2.optional(),
  packages: z13.string().array().optional().describe(
    "Define the package names that are available bundled in the layer. Those packages are not bundled while bundling the lambda."
  )
});
var LayerSchema = z13.record(
  z13.string(),
  z13.union([
    LocalFileSchema.transform((file) => ({
      file,
      description: void 0
    })),
    Schema
  ])
).optional().describe("Define the lambda layers in your stack.");

// src/feature/on-failure/schema.ts
var OnFailureDefaultSchema = FunctionSchema.optional().describe(
  "Defining a onFailure handler will add a global onFailure handler for the following resources:\n- Async lambda functions\n- SQS queues\n- DynamoDB streams"
);

// src/feature/on-log/schema.ts
import { z as z14 } from "zod";
var FilterSchema = z14.enum(["trace", "debug", "info", "warn", "error", "fatal"]).array().describe("The log level that will gets delivered to the consumer.");
var OnLogDefaultSchema = z14.union([
  FunctionSchema.transform((consumer) => ({
    consumer,
    filter: ["error", "fatal"]
  })),
  z14.object({
    consumer: FunctionSchema,
    filter: FilterSchema
  })
]).optional().describe("Define a subscription on all Lambda functions logs.");

// src/feature/pubsub/schema.ts
import { z as z15 } from "zod";
var DomainSchema = ResourceIdSchema.describe("The domain id to link your Pubsub API with.");
var PubSubDefaultSchema = z15.record(
  ResourceIdSchema,
  z15.object({
    auth: FunctionSchema,
    domain: DomainSchema.optional(),
    subDomain: z15.string().optional()
    // auth: z.union([
    // 	ResourceIdSchema,
    // 	z.object({
    // 		authorizer: FunctionSchema,
    // 		// ttl: AuthorizerTtl.default('1 hour'),
    // 	}),
    // ]),
    // policy: z
    // 	.object({
    // 		publish: z.array(z.string()).optional(),
    // 		subscribe: z.array(z.string()).optional(),
    // 	})
    // 	.optional(),
  })
).optional().describe("Define the pubsub subscriber in your stack.");
var PubSubSchema = z15.record(
  ResourceIdSchema,
  z15.object({
    sql: z15.string().describe("The SQL statement used to query the IOT topic."),
    sqlVersion: z15.enum(["2015-10-08", "2016-03-23", "beta"]).default("2016-03-23").describe("The version of the SQL rules engine to use when evaluating the rule."),
    consumer: FunctionSchema.describe("The consuming lambda function properties.")
  })
).optional().describe("Define the pubsub subscriber in your stack.");

// src/feature/queue/schema.ts
import { days as days2, hours, minutes as minutes2, seconds as seconds2 } from "@awsless/duration";
import { kibibytes } from "@awsless/size";
import { z as z16 } from "zod";
var RetentionPeriodSchema = DurationSchema.refine(
  durationMin(minutes2(1)),
  "Minimum retention period is 1 minute"
).refine(durationMax(days2(14)), "Maximum retention period is 14 days").describe(
  "The number of seconds that Amazon SQS retains a message. You can specify a duration from 1 minute to 14 days."
);
var VisibilityTimeoutSchema = DurationSchema.refine(
  durationMax(hours(12)),
  "Maximum visibility timeout is 12 hours"
).describe(
  "The length of time during which a message will be unavailable after a message is delivered from the queue. This blocks other components from receiving the same message and gives the initial component time to process and delete the message from the queue. You can specify a duration from 0 to 12 hours."
);
var DeliveryDelaySchema = DurationSchema.refine(
  durationMax(minutes2(15)),
  "Maximum delivery delay is 15 minutes"
).describe(
  "The time in seconds for which the delivery of all messages in the queue is delayed. You can specify a duration from 0 to 15 minutes."
);
var ReceiveMessageWaitTimeSchema = DurationSchema.refine(
  durationMin(seconds2(1)),
  "Minimum receive message wait time is 1 second"
).refine(durationMax(seconds2(20)), "Maximum receive message wait time is 20 seconds").describe(
  "Specifies the duration, that the ReceiveMessage action call waits until a message is in the queue in order to include it in the response, rather than returning an empty response if a message isn't yet available. You can specify a duration from 1 to 20 seconds. Short polling is used as the default."
);
var MaxMessageSizeSchema = SizeSchema.refine(sizeMin(kibibytes(1)), "Minimum max message size is 1 KB").refine(sizeMax(kibibytes(256)), "Maximum max message size is 256 KB").describe(
  "The limit of how many bytes that a message can contain before Amazon SQS rejects it. You can specify an size from 1 KB to 256 KB."
);
var BatchSizeSchema = z16.number().int().min(1, "Minimum batch size is 1").max(1e4, "Maximum batch size is 10000").describe(
  "The maximum number of records in each batch that Lambda pulls from your queue and sends to your function. Lambda passes all of the records in the batch to the function in a single call, up to the payload limit for synchronous invocation (6 MB). You can specify an integer from 1 to 10000."
);
var MaxConcurrencySchema = z16.number().int().min(2, "Minimum max concurrency is 2").max(1e3, "Maximum max concurrency is 1000").describe(
  "Limits the number of concurrent instances that the queue worker can invoke. You can specify an integer from 2 to 1000."
);
var MaxBatchingWindow = DurationSchema.refine(
  durationMax(minutes2(5)),
  "Maximum max batching window is 5 minutes"
).describe(
  "The maximum amount of time, that Lambda spends gathering records before invoking the function. You can specify an duration from 0 seconds to 5 minutes."
);
var QueueDefaultSchema = z16.object({
  retentionPeriod: RetentionPeriodSchema.default("7 days"),
  visibilityTimeout: VisibilityTimeoutSchema.default("30 seconds"),
  deliveryDelay: DeliveryDelaySchema.default("0 seconds"),
  receiveMessageWaitTime: ReceiveMessageWaitTimeSchema.optional(),
  maxMessageSize: MaxMessageSizeSchema.default("256 KB"),
  batchSize: BatchSizeSchema.default(10),
  maxConcurrency: MaxConcurrencySchema.optional(),
  maxBatchingWindow: MaxBatchingWindow.optional()
}).default({});
var QueueSchema = z16.object({
  consumer: FunctionSchema.describe("The consuming lambda function properties."),
  retentionPeriod: RetentionPeriodSchema.optional(),
  visibilityTimeout: VisibilityTimeoutSchema.optional(),
  deliveryDelay: DeliveryDelaySchema.optional(),
  receiveMessageWaitTime: ReceiveMessageWaitTimeSchema.optional(),
  maxMessageSize: MaxMessageSizeSchema.optional(),
  batchSize: BatchSizeSchema.optional(),
  maxConcurrency: MaxConcurrencySchema.optional(),
  maxBatchingWindow: MaxBatchingWindow.optional()
});
var QueuesSchema = z16.record(
  ResourceIdSchema,
  z16.union([
    LocalFileSchema.transform((consumer) => ({
      consumer
    })).pipe(QueueSchema),
    QueueSchema
  ])
).optional().describe("Define the queues in your stack.");

// src/feature/rest/schema.ts
import { z as z18 } from "zod";

// src/config/schema/route.ts
import { z as z17 } from "zod";
var RouteSchema = z17.union([
  z17.string().regex(/^(POST|GET|PUT|DELETE|HEAD|OPTIONS|ANY)(\s\/[a-z0-9\+\_\-\/\{\}]*)$/gi, "Invalid route"),
  z17.literal("$default")
]);

// src/feature/rest/schema.ts
var RestDefaultSchema = z18.record(
  ResourceIdSchema,
  z18.object({
    domain: ResourceIdSchema.describe("The domain id to link your API with.").optional(),
    subDomain: z18.string().optional()
  })
).optional().describe("Define your global REST API's.");
var RestSchema = z18.record(
  ResourceIdSchema,
  z18.record(
    RouteSchema.describe(
      [
        "The REST API route that is comprised by the http method and http path.",
        "The possible http methods are POST, GET,PUT, DELETE, HEAD, OPTIONS, ANY.",
        "Example: GET /posts/{id}"
      ].join("\n")
    ),
    FunctionSchema
  )
).optional().describe("Define routes in your stack for your global REST API.");

// src/feature/rpc/schema.ts
import { z as z19 } from "zod";
import { minutes as minutes3, seconds as seconds3 } from "@awsless/duration";
var TimeoutSchema2 = DurationSchema.refine(durationMin(seconds3(10)), "Minimum timeout duration is 10 seconds").refine(durationMax(minutes3(5)), "Maximum timeout duration is 5 minutes").describe(
  [
    "The amount of time that the RPC lambda is allowed run before stopping it.",
    "You can specify a size value from 1 second to 5 minutes.",
    "The timeouts of all inner RPC functions will be capped at 80% of this timeout."
  ].join(" ")
);
var RpcDefaultSchema = z19.record(
  ResourceIdSchema,
  z19.object({
    domain: ResourceIdSchema.describe("The domain id to link your RPC API with.").optional(),
    subDomain: z19.string().optional(),
    auth: FunctionSchema.optional(),
    log: LogSchema.optional(),
    timeout: TimeoutSchema2.default("1 minutes"),
    geoRestrictions: z19.array(z19.string().length(2).toUpperCase()).default([]).describe("Specifies a blacklist of countries that should be blocked.")
  })
).describe(`Define the global RPC API's.`).optional();
var RpcSchema = z19.record(ResourceIdSchema, z19.record(z19.string(), FunctionSchema).describe("The queries for your global RPC API.")).describe("Define the schema in your stack for your global RPC API.").optional();

// src/feature/instance/schema.ts
import { days as days3, toDays as toDays2 } from "@awsless/duration";
import { toMebibytes } from "@awsless/size";
import { z as z20 } from "zod";
var CpuSchema = z20.union([z20.literal(0.25), z20.literal(0.5), z20.literal(1), z20.literal(2), z20.literal(4), z20.literal(8), z20.literal(16)]).transform((v) => `${v} vCPU`).describe(
  "The number of virtual CPU units (vCPU) used by the instance. Valid values: 0.25, 0.5, 1, 2, 4, 8, 16 vCPU."
);
var validMemorySize = [
  // 0.25 vCPU
  512,
  1024,
  2048,
  // 0.5 vCPU
  1024,
  2048,
  3072,
  4096,
  // 1 vCPU
  2048,
  3072,
  4096,
  5120,
  6144,
  7168,
  8192,
  // 2 vCPU
  4096,
  5120,
  6144,
  7168,
  8192,
  9216,
  10240,
  11264,
  12288,
  13312,
  14336,
  15360,
  16384
];
var MemorySizeSchema2 = SizeSchema.refine(
  (s) => validMemorySize.includes(toMebibytes(s)),
  `Invalid memory size. Allowed sizes: ${validMemorySize.join(", ")} MiB`
).describe("The amount of memory (in MiB) used by the instance. Valid memory values depend on the CPU configuration.");
var HealthCheckSchema = z20.object({
  path: z20.string().describe("The path that the container runs to determine if it is healthy."),
  interval: DurationSchema.describe("The time period in seconds between each health check execution."),
  retries: z20.number().int().min(1).max(10).describe(
    "The number of times to retry a failed health check before the container is considered unhealthy."
  ),
  startPeriod: DurationSchema.describe(
    "The optional grace period to provide containers time to bootstrap before failed health checks count towards the maximum number of retries."
  ),
  timeout: DurationSchema.describe(
    "The time period in seconds to wait for a health check to succeed before it is considered a failure."
  )
}).describe("The health check command and associated configuration parameters for the container.");
var EnvironmentSchema2 = z20.record(z20.string(), z20.string()).optional().describe("Environment variable key-value pairs.");
var ArchitectureSchema3 = z20.enum(["x86_64", "arm64"]).describe("The instruction set architecture that the instance supports.");
var ActionSchema2 = z20.string();
var ActionsSchema2 = z20.union([ActionSchema2.transform((v) => [v]), ActionSchema2.array()]);
var ArnSchema2 = z20.string().startsWith("arn:");
var WildcardSchema2 = z20.literal("*");
var ResourceSchema2 = z20.union([ArnSchema2, WildcardSchema2]);
var ResourcesSchema2 = z20.union([ResourceSchema2.transform((v) => [v]), ResourceSchema2.array()]);
var PermissionSchema2 = z20.object({
  effect: z20.enum(["allow", "deny"]).default("allow"),
  actions: ActionsSchema2,
  resources: ResourcesSchema2
});
var PermissionsSchema2 = z20.union([PermissionSchema2.transform((v) => [v]), PermissionSchema2.array()]).describe("Add IAM permissions to your instance.");
var DescriptionSchema2 = z20.string().describe("A description of the instance.");
var ImageSchema = z20.string().optional().describe("The URL of the container image to use.");
var validLogRetentionDays2 = [
  ...[1, 3, 5, 7, 14, 30, 60, 90, 120, 150],
  ...[180, 365, 400, 545, 731, 1096, 1827, 2192],
  ...[2557, 2922, 3288, 3653]
];
var LogRetentionSchema2 = DurationSchema.refine(
  durationMin(days3(0)),
  "Minimum log retention is 0 day, which will disable logging."
).refine(
  (duration) => {
    return validLogRetentionDays2.includes(toDays2(duration));
  },
  `Invalid log retention. Valid days are: ${validLogRetentionDays2.map((days4) => `${days4}`).join(", ")}`
).describe("The log retention duration.");
var LogSchema2 = z20.union([
  z20.boolean().transform((enabled) => ({ retention: enabled ? days3(7) : days3(0) })),
  LogRetentionSchema2.transform((retention) => ({ retention })),
  z20.object({
    retention: LogRetentionSchema2.optional()
  })
]).describe("Enable logging to a CloudWatch log group. Providing a duration value will set the log retention time.");
var FileCodeSchema2 = z20.object({
  file: LocalFileSchema.describe("The file path of the instance code.")
});
var CodeSchema2 = z20.union([
  LocalFileSchema.transform((file) => ({
    file
  })).pipe(FileCodeSchema2),
  FileCodeSchema2
]).describe("Specify the code of your instance.");
var ISchema = z20.object({
  code: CodeSchema2,
  description: DescriptionSchema2.optional(),
  image: ImageSchema.optional(),
  log: LogSchema2.optional(),
  cpu: CpuSchema.optional(),
  memorySize: MemorySizeSchema2.optional(),
  architecture: ArchitectureSchema3.optional(),
  environment: EnvironmentSchema2.optional(),
  permissions: PermissionsSchema2.optional(),
  healthCheck: HealthCheckSchema.optional()
  // restartPolicy: RestartPolicySchema.optional(),
});
var InstanceSchema = z20.union([
  LocalFileSchema.transform((code) => ({
    code
  })).pipe(ISchema),
  ISchema
]);
var InstancesSchema = z20.record(ResourceIdSchema, InstanceSchema).optional().describe("Define the instances in your stack.");
var InstanceDefaultSchema = z20.object({
  image: ImageSchema.default("public.ecr.aws/aws-cli/aws-cli:amd64"),
  cpu: CpuSchema.default(0.25),
  memorySize: MemorySizeSchema2.default("512 MB"),
  architecture: ArchitectureSchema3.default("arm64"),
  environment: EnvironmentSchema2.optional(),
  permissions: PermissionsSchema2.optional(),
  healthCheck: HealthCheckSchema.optional(),
  // restartPolicy: RestartPolicySchema.default({ enabled: true }),
  log: LogSchema2.default(true).transform((log) => ({
    retention: log.retention ?? days3(7)
  }))
}).default({});

// src/config/schema/region.ts
import { z as z21 } from "zod";
var US = ["us-east-2", "us-east-1", "us-west-1", "us-west-2"];
var AF = ["af-south-1"];
var AP = [
  "ap-east-1",
  "ap-south-2",
  "ap-southeast-3",
  "ap-southeast-4",
  "ap-south-1",
  "ap-northeast-3",
  "ap-northeast-2",
  "ap-southeast-1",
  "ap-southeast-2",
  "ap-northeast-1"
];
var CA = ["ca-central-1"];
var EU = [
  "eu-central-1",
  "eu-west-1",
  "eu-west-2",
  "eu-south-1",
  "eu-west-3",
  "eu-south-2",
  "eu-north-1",
  "eu-central-2"
];
var ME = ["me-south-1", "me-central-1"];
var SA = ["sa-east-1"];
var regions = [...US, ...AF, ...AP, ...CA, ...EU, ...ME, ...SA];
var RegionSchema = z21.enum(regions);

// src/config/app.ts
var AppSchema = z22.object({
  $schema: z22.string().optional(),
  name: ResourceIdSchema.describe("App name."),
  region: RegionSchema.describe("The AWS region to deploy to."),
  profile: z22.string().describe("The AWS profile to deploy to."),
  protect: z22.boolean().default(false).describe("Protect your app & stacks from being deleted."),
  removal: z22.enum(["remove", "retain"]).default("remove").describe(
    [
      "Configure how your resources are handled when they have to be removed.",
      "",
      "remove: Removes the underlying resource.",
      "retain: Retains resources like S3 stores and DynamoDB tables. Removes everything else."
    ].join("\n")
  ),
  // stage: z
  // 	.string()
  // 	.regex(/^[a-z]+$/)
  // 	.default('prod')
  // 	.describe('The deployment stage.'),
  // onFailure: OnFailureSchema,
  defaults: z22.object({
    onFailure: OnFailureDefaultSchema,
    onLog: OnLogDefaultSchema,
    auth: AuthDefaultSchema,
    domains: DomainsDefaultSchema,
    function: FunctionDefaultSchema,
    instance: InstanceDefaultSchema,
    queue: QueueDefaultSchema,
    // graphql: GraphQLDefaultSchema,
    // http: HttpDefaultSchema,
    rest: RestDefaultSchema,
    rpc: RpcDefaultSchema,
    pubsub: PubSubDefaultSchema,
    // table: TableDefaultSchema,
    // store: StoreDefaultSchema,
    alerts: AlertsDefaultSchema,
    layers: LayerSchema
    // dataRetention: z.boolean().describe('Configure how your resources are handled on delete.').default(false),
  }).default({}).describe("Default properties")
});

// src/config/stack.ts
import { z as z38 } from "zod";

// src/feature/cache/schema.ts
import { gibibytes as gibibytes2 } from "@awsless/size";
import { z as z23 } from "zod";
var StorageSchema = SizeSchema.refine(sizeMin(gibibytes2(1)), "Minimum storage size is 1 GB").refine(
  sizeMax(gibibytes2(5e3)),
  "Maximum storage size is 5000 GB"
);
var MinimumStorageSchema = StorageSchema.describe(
  "The lower limit for data storage the cache is set to use. You can specify a size value from 1 GB to 5000 GB."
);
var MaximumStorageSchema = StorageSchema.describe(
  "The upper limit for data storage the cache is set to use. You can specify a size value from 1 GB to 5000 GB."
);
var EcpuSchema = z23.number().int().min(1e3).max(15e6);
var MinimumEcpuSchema = EcpuSchema.describe(
  "The minimum number of ECPUs the cache can consume per second. You can specify a integer from 1,000 to 15,000,000."
);
var MaximumEcpuSchema = EcpuSchema.describe(
  "The maximum number of ECPUs the cache can consume per second. You can specify a integer from 1,000 to 15,000,000."
);
var CachesSchema = z23.record(
  ResourceIdSchema,
  z23.object({
    minStorage: MinimumStorageSchema.optional(),
    maxStorage: MaximumStorageSchema.optional(),
    minECPU: MinimumEcpuSchema.optional(),
    maxECPU: MaximumEcpuSchema.optional(),
    snapshotRetentionLimit: z23.number().int().positive().default(1)
  })
).optional().describe("Define the caches in your stack. For access to the cache put your functions inside the global VPC.");

// src/feature/command/schema.ts
import { z as z24 } from "zod";
var CommandSchema = z24.union([
  z24.object({
    file: LocalFileSchema,
    handler: z24.string().default("default").describe("The name of the handler that needs to run"),
    description: z24.string().optional().describe("A description of the command")
    // options: z.record(ResourceIdSchema, OptionSchema).optional(),
    // arguments: z.record(ResourceIdSchema, ArgumentSchema).optional(),
  }),
  LocalFileSchema.transform((file) => ({
    file,
    handler: "default",
    description: void 0
  }))
]);
var CommandsSchema = z24.record(ResourceIdSchema, CommandSchema).optional().describe("Define the custom commands for your stack.");

// src/feature/config/schema.ts
import { z as z25 } from "zod";
var ConfigNameSchema = z25.string().regex(/[a-z0-9\-]/g, "Invalid config name");
var ConfigsSchema = z25.array(ConfigNameSchema).optional().describe("Define the config values for your stack.");

// src/feature/cron/schema/index.ts
import { z as z27 } from "zod";

// src/feature/cron/schema/schedule.ts
import { z as z26 } from "zod";
import { awsCronExpressionValidator } from "aws-cron-expression-validator";
var RateExpressionSchema = z26.custom(
  (value) => {
    return z26.string().regex(/^[0-9]+ (seconds?|minutes?|hours?|days?)$/).refine((rate) => {
      const [str] = rate.split(" ");
      const number = parseInt(str);
      return number > 0;
    }).safeParse(value).success;
  },
  { message: "Invalid rate expression" }
).transform((rate) => {
  const [str] = rate.split(" ");
  const number = parseInt(str);
  const more = rate.endsWith("s");
  if (more && number === 1) {
    return `rate(${rate.substring(0, rate.length - 1)})`;
  }
  return `rate(${rate})`;
});
var CronExpressionSchema = z26.custom(
  (value) => {
    return z26.string().safeParse(value).success;
  },
  { message: "Invalid cron expression" }
).superRefine((value, ctx) => {
  try {
    awsCronExpressionValidator(value);
  } catch (error) {
    if (error instanceof Error) {
      ctx.addIssue({
        code: z26.ZodIssueCode.custom,
        message: `Invalid cron expression: ${error.message}`
      });
    } else {
      ctx.addIssue({
        code: z26.ZodIssueCode.custom,
        message: "Invalid cron expression"
      });
    }
  }
}).transform((value) => {
  return `cron(${value.trim()})`;
});
var ScheduleExpressionSchema = RateExpressionSchema.or(CronExpressionSchema);

// src/feature/cron/schema/index.ts
var CronsSchema = z27.record(
  ResourceIdSchema,
  z27.object({
    enabled: z27.boolean().default(true).describe("If the cron is enabled."),
    consumer: FunctionSchema.describe("The consuming lambda function properties."),
    schedule: ScheduleExpressionSchema.describe(
      'The scheduling expression.\n\nexample: "0 20 * * ? *"\nexample: "5 minutes"'
    ),
    payload: z27.unknown().optional().describe("The JSON payload that will be passed to the consumer.")
  })
).optional().describe(`Define the cron jobs in your stack.`);

// src/feature/search/schema.ts
import { gibibytes as gibibytes3 } from "@awsless/size";
import { z as z28 } from "zod";
var VersionSchema = z28.union([
  //
  z28.enum(["2.13", "2.11", "2.9", "2.7", "2.5", "2.3", "1.3"]),
  z28.string()
]).describe("Specify the OpenSearch engine version.");
var TypeSchema = z28.union([
  z28.enum([
    "t3.small",
    "t3.medium",
    "m3.medium",
    "m3.large",
    "m3.xlarge",
    "m3.2xlarge",
    "m4.large",
    "m4.xlarge",
    "m4.2xlarge",
    "m4.4xlarge",
    "m4.10xlarge",
    "m5.large",
    "m5.xlarge",
    "m5.2xlarge",
    "m5.4xlarge",
    "m5.12xlarge",
    "m5.24xlarge",
    "r5.large",
    "r5.xlarge",
    "r5.2xlarge",
    "r5.4xlarge",
    "r5.12xlarge",
    "r5.24xlarge",
    "c5.large",
    "c5.xlarge",
    "c5.2xlarge",
    "c5.4xlarge",
    "c5.9xlarge",
    "c5.18xlarge",
    "or1.medium",
    "or1.large",
    "or1.xlarge",
    "or1.2xlarge",
    "or1.4xlarge",
    "or1.8xlarge",
    "or1.12xlarge",
    "or1.16xlarge",
    "ultrawarm1.medium",
    "ultrawarm1.large",
    "ultrawarm1.xlarge",
    "r3.large",
    "r3.xlarge",
    "r3.2xlarge",
    "r3.4xlarge",
    "r3.8xlarge",
    "i2.xlarge",
    "i2.2xlarge",
    "i3.large",
    "i3.xlarge",
    "i3.2xlarge",
    "i3.4xlarge",
    "i3.8xlarge",
    "i3.16xlarge",
    "r6g.large",
    "r6g.xlarge",
    "r6g.2xlarge",
    "r6g.4xlarge",
    "r6g.8xlarge",
    "r6g.12xlarge",
    "m6g.large",
    "m6g.xlarge",
    "m6g.2xlarge",
    "m6g.4xlarge",
    "m6g.8xlarge",
    "m6g.12xlarge",
    "r6gd.large",
    "r6gd.xlarge",
    "r6gd.2xlarge",
    "r6gd.4xlarge",
    "r6gd.8xlarge",
    "r6gd.12xlarge",
    "r6gd.16xlarge"
  ]),
  z28.string()
]).describe("Instance type of data nodes in the cluster.");
var CountSchema = z28.number().int().min(1).describe("Number of instances in the cluster.");
var StorageSizeSchema = SizeSchema.refine(sizeMin(gibibytes3(10)), "Minimum storage size is 10 GB").refine(sizeMax(gibibytes3(100)), "Maximum storage size is 100 GB").describe("The size of the function's /tmp directory. You can specify a size value from 512 MB to 10 GiB.");
var SearchsSchema = z28.record(
  ResourceIdSchema,
  z28.object({
    type: TypeSchema.default("t3.small"),
    count: CountSchema.default(1),
    version: VersionSchema.default("2.13"),
    storage: StorageSizeSchema.default("10 GB")
    // vpc: z.boolean().default(false),
    // migration: FunctionSchema.optional(),
  })
).optional().describe("Define the search instances in your stack. Backed by OpenSearch.");

// src/feature/site/schema.ts
import { z as z30 } from "zod";

// src/config/schema/local-entry.ts
import { stat as stat3 } from "fs/promises";
import { z as z29 } from "zod";
var LocalEntrySchema = z29.union([
  RelativePathSchema.refine(async (path) => {
    try {
      const s = await stat3(path);
      return s.isFile() || s.isDirectory();
    } catch (error) {
      return false;
    }
  }, `File or directory doesn't exist`),
  z29.object({
    nocheck: RelativePathSchema.describe(
      "Specifies a local file or directory without checking if the file or directory exists."
    )
  }).transform((v) => v.nocheck)
]);

// src/feature/site/schema.ts
var ErrorResponsePathSchema = z30.string().describe(
  [
    "The path to the custom error page that you want to return to the viewer when your origin returns the HTTP status code specified.",
    "- We recommend that you store custom error pages in an Amazon S3 bucket.",
    "If you store custom error pages on an HTTP server and the server starts to return 5xx errors, CloudFront can't get the files that you want to return to viewers because the origin server is unavailable."
  ].join("\n")
);
var StatusCodeSchema = z30.number().int().positive().optional().describe(
  [
    "The HTTP status code that you want CloudFront to return to the viewer along with the custom error page.",
    "There are a variety of reasons that you might want CloudFront to return a status code different from the status code that your origin returned to CloudFront, for example:",
    "- Some Internet devices (some firewalls and corporate proxies, for example) intercept HTTP 4xx and 5xx and prevent the response from being returned to the viewer.",
    "If you substitute 200, the response typically won't be intercepted.",
    `- If you don't care about distinguishing among different client errors or server errors, you can specify 400 or 500 as the ResponseCode for all 4xx or 5xx errors.`,
    `- You might want to return a 200 status code (OK) and static website so your customers don't know that your website is down.`
  ].join("\n")
);
var MinTTLSchema = DurationSchema.describe(
  "The minimum amount of time, that you want to cache the error response. When this time period has elapsed, CloudFront queries your origin to see whether the problem that caused the error has been resolved and the requested object is now available."
);
var ErrorResponseSchema = z30.union([
  ErrorResponsePathSchema,
  z30.object({
    path: ErrorResponsePathSchema,
    statusCode: StatusCodeSchema.optional(),
    minTTL: MinTTLSchema.optional()
  })
]).optional();
var SitesSchema = z30.record(
  ResourceIdSchema,
  z30.object({
    domain: ResourceIdSchema.describe("The domain id to link your site with.").optional(),
    subDomain: z30.string().optional(),
    // bind: z
    // 	.object({
    // 		auth: z.array(ResourceIdSchema),
    // 		graphql: z.array(ResourceIdSchema),
    // 		// http: z.array(ResourceIdSchema),
    // 		// rest: z.array(ResourceIdSchema),
    // 	})
    // 	.optional(),
    build: z30.object({
      command: z30.string().describe(
        `Specifies the files and directories to generate the cache key for your custom build command.`
      ),
      cacheKey: z30.union([LocalEntrySchema.transform((v) => [v]), LocalEntrySchema.array()]).describe(
        `Specifies the files and directories to generate the cache key for your custom build command.`
      ),
      configs: z30.string().array().describe("Define the config values for your build command.")
    }).optional().describe(`Specifies the build process for sites that need a build step.`),
    static: z30.union([LocalDirectorySchema, z30.boolean()]).optional().describe(
      "Specifies the path to the static files directory. Additionally you can also pass `true` when you don't have local static files, but still want to make an S3 bucket."
    ),
    ssr: FunctionSchema.optional().describe("Specifies the file that will render the site on the server."),
    // envPrefix: z.string().optional().describe('Specifies a prefix for all '),
    // origin: z
    // 	.enum(['ssr-first', 'static-first'])
    // 	.default('static-first')
    // 	.describe('Specifies the origin fallback ordering.'),
    // bind: z.object({
    // 	auth:
    // 	h
    // }).optional(),
    // ssr: z.union([
    // 	FunctionSchema.optional(),
    // 	z.object({
    // 		consumer: FunctionSchema.optional(),
    // 		responseStreaming: z.boolean().default(false),
    // 		build: z.string().optional(),
    // 	}),
    // ]),
    geoRestrictions: z30.array(z30.string().length(2).toUpperCase()).default([]).describe("Specifies a blacklist of countries that should be blocked."),
    // forwardHost: z
    // 	.boolean()
    // 	.default(false)
    // 	.describe(
    // 		[
    // 			'Specify if the original `host` header should be forwarded to the SSR function.',
    // 			'The original `host` header will be forwarded as `x-forwarded-host`.',
    // 			'Keep in mind that this requires an extra CloudFront Function.',
    // 		].join('\n')
    // 	),
    errors: z30.object({
      400: ErrorResponseSchema.describe("Customize a `400 Bad Request` response."),
      403: ErrorResponseSchema.describe("Customize a `403 Forbidden` response."),
      404: ErrorResponseSchema.describe("Customize a `404 Not Found` response."),
      405: ErrorResponseSchema.describe("Customize a `405 Method Not Allowed` response."),
      414: ErrorResponseSchema.describe("Customize a `414 Request-URI` response."),
      416: ErrorResponseSchema.describe("Customize a `416 Range Not` response."),
      500: ErrorResponseSchema.describe("Customize a `500 Internal Server` response."),
      501: ErrorResponseSchema.describe("Customize a `501 Not Implemented` response."),
      502: ErrorResponseSchema.describe("Customize a `502 Bad Gateway` response."),
      503: ErrorResponseSchema.describe("Customize a `503 Service Unavailable` response."),
      504: ErrorResponseSchema.describe("Customize a `504 Gateway Timeout` response.")
    }).optional().describe("Customize the error responses for specific HTTP status codes."),
    cors: z30.object({
      override: z30.boolean().default(false),
      maxAge: DurationSchema.default("365 days"),
      exposeHeaders: z30.string().array().optional(),
      credentials: z30.boolean().default(false),
      headers: z30.string().array().default(["*"]),
      origins: z30.string().array().default(["*"]),
      methods: z30.enum(["GET", "DELETE", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "ALL"]).array().default(["ALL"])
    }).optional().describe("Specify the cors headers."),
    auth: z30.object({
      username: z30.string().describe("Basic auth username"),
      password: z30.string().describe("Basic auth password")
    }).optional().describe("Enable basic authentication for the site"),
    security: z30.object({
      // contentSecurityPolicy: z.object({
      // 	override: z.boolean().default(false),
      // 	policy: z.string(),
      // })
      // contentSecurityPolicy?: {
      // 	override?: boolean
      // 	contentSecurityPolicy: string
      // }
      // contentTypeOptions?: {
      // 	override?: boolean
      // }
      // frameOptions?: {
      // 	override?: boolean
      // 	frameOption?: 'deny' | 'same-origin'
      // }
      // referrerPolicy?: {
      // 	override?: boolean
      // 	referrerPolicy?: (
      // 		'no-referrer' |
      // 		'no-referrer-when-downgrade' |
      // 		'origin' |
      // 		'origin-when-cross-origin' |
      // 		'same-origin' |
      // 		'strict-origin' |
      // 		'strict-origin-when-cross-origin' |
      // 		'unsafe-url'
      // 	)
      // }
      // strictTransportSecurity?: {
      // 	maxAge?: Duration
      // 	includeSubdomains?: boolean
      // 	override?: boolean
      // 	preload?: boolean
      // }
      // xssProtection?: {
      // 	override?: boolean
      // 	enable?: boolean
      // 	modeBlock?: boolean
      // 	reportUri?: string
      // }
    }).optional().describe("Specify the security policy."),
    cache: z30.object({
      cookies: z30.string().array().optional().describe("Specifies the cookies that CloudFront includes in the cache key."),
      headers: z30.string().array().optional().describe("Specifies the headers that CloudFront includes in the cache key."),
      queries: z30.string().array().optional().describe("Specifies the query values that CloudFront includes in the cache key.")
    }).optional().describe(
      "Specifies the cookies, headers, and query values that CloudFront includes in the cache key."
    )
  })
).optional().describe("Define the sites in your stack.");

// src/feature/store/schema.ts
import { z as z31 } from "zod";
var StoresSchema = z31.union([
  z31.array(ResourceIdSchema).transform((list) => {
    const stores = {};
    for (const key of list) {
      stores[key] = {};
    }
    return stores;
  }),
  z31.record(
    ResourceIdSchema,
    z31.object({
      // cors: CorsSchema,
      // deletionProtection: DeletionProtectionSchema.optional(),
      versioning: z31.boolean().default(false).describe("Enable versioning of your store."),
      events: z31.object({
        // create
        "created:*": FunctionSchema.optional().describe(
          "Subscribe to notifications regardless of the API that was used to create an object."
        ),
        "created:put": FunctionSchema.optional().describe(
          "Subscribe to notifications when an object is created using the PUT API operation."
        ),
        "created:post": FunctionSchema.optional().describe(
          "Subscribe to notifications when an object is created using the POST API operation."
        ),
        "created:copy": FunctionSchema.optional().describe(
          "Subscribe to notifications when an object is created using the COPY API operation."
        ),
        "created:upload": FunctionSchema.optional().describe(
          "Subscribe to notifications when an object multipart upload has been completed."
        ),
        // remove
        "removed:*": FunctionSchema.optional().describe(
          "Subscribe to notifications when an object is deleted or a delete marker for a versioned object is created."
        ),
        "removed:delete": FunctionSchema.optional().describe(
          "Subscribe to notifications when an object is deleted"
        ),
        "removed:marker": FunctionSchema.optional().describe(
          "Subscribe to notifications when a delete marker for a versioned object is created."
        )
      }).optional().describe("Describes the store events you want to subscribe too.")
    })
  )
]).optional().describe("Define the stores in your stack.");

// src/feature/icon/schema.ts
import { z as z32 } from "zod";
var staticOriginSchema = LocalDirectorySchema.describe(
  "Specifies the path to a local image directory that will be uploaded in S3."
);
var functionOriginSchema = FunctionSchema.describe(
  "Specifies the file that will be called when an image isn't found in the (cache) bucket."
);
var IconsSchema = z32.record(
  ResourceIdSchema,
  z32.object({
    domain: ResourceIdSchema.describe("The domain id to link your site with.").optional(),
    subDomain: z32.string().optional(),
    log: LogSchema.optional(),
    cacheDuration: DurationSchema.optional().describe("The cache duration of the cached icons."),
    preserveId: z32.boolean().optional().default(false).describe("Preserve the IDs of the icons."),
    symbols: z32.boolean().optional().default(false).describe("Use SVG symbols for icons."),
    origin: z32.union([
      z32.object({
        static: staticOriginSchema,
        function: functionOriginSchema.optional()
      }),
      z32.object({
        static: staticOriginSchema.optional(),
        function: functionOriginSchema
      }),
      z32.object({
        static: staticOriginSchema,
        function: functionOriginSchema
      })
    ]).describe(
      "Image transformation will be applied from a base image. Base images orginates from a local directory that will be uploaded to S3 or from a lambda function."
    ),
    cors: z32.object({
      override: z32.boolean().default(true),
      maxAge: DurationSchema.default("365 days"),
      exposeHeaders: z32.string().array().optional(),
      credentials: z32.boolean().default(false),
      headers: z32.string().array().default(["*"]),
      origins: z32.string().array().default(["*"])
    }).optional().describe("Specify the cors headers.")
    // version: z.number().int().min(1).optional().describe('Version of the icon configuration.'),
  })
).optional().describe("Define an icon proxy in your stack. Store, optimize, and deliver icons at scale.");

// src/feature/image/schema.ts
import { z as z33 } from "zod";
var transformationOptionsSchema = z33.object({
  width: z33.number().int().positive().optional(),
  height: z33.number().int().positive().optional(),
  fit: z33.enum(["cover", "contain", "fill", "inside", "outside"]).optional(),
  position: z33.enum(["top", "right top", "right", "right bottom", "bottom", "left bottom", "left", "left top", "center"]).optional(),
  quality: z33.number().int().min(1).max(100).optional()
});
var staticOriginSchema2 = LocalDirectorySchema.describe(
  "Specifies the path to a local image directory that will be uploaded in S3."
);
var functionOriginSchema2 = FunctionSchema.describe(
  "Specifies the file that will be called when an image isn't found in the (cache) bucket."
);
var ImagesSchema = z33.record(
  ResourceIdSchema,
  z33.object({
    domain: ResourceIdSchema.describe("The domain id to link your site with.").optional(),
    subDomain: z33.string().optional(),
    log: LogSchema.optional(),
    cacheDuration: DurationSchema.optional().describe("Cache duration of the cached images."),
    presets: z33.record(z33.string(), transformationOptionsSchema).describe("Named presets for image transformations"),
    extensions: z33.object({
      jpeg: z33.object({
        mozjpeg: z33.boolean().optional(),
        progressive: z33.boolean().optional()
      }).optional(),
      webp: z33.object({
        effort: z33.number().int().min(1).max(10).default(7).optional(),
        lossless: z33.boolean().optional(),
        nearLossless: z33.boolean().optional()
      }).optional(),
      png: z33.object({
        compressionLevel: z33.number().int().min(0).max(9).default(6).optional()
      }).optional()
    }).refine((data) => {
      return Object.keys(data).length > 0;
    }, "At least one extension must be defined.").describe("Specify the allowed extensions."),
    origin: z33.union([
      z33.object({
        static: staticOriginSchema2,
        function: functionOriginSchema2.optional()
      }),
      z33.object({
        static: staticOriginSchema2.optional(),
        function: functionOriginSchema2
      }),
      z33.object({
        static: staticOriginSchema2,
        function: functionOriginSchema2
      })
    ]).describe(
      "Specify the origin of your images. Image transformation will be applied from a base image. Base images can be loaded from a S3 bucket (that is synced from a local directory) or dynamicly from a lambda function."
    ),
    version: z33.number().int().min(1).optional().describe("Version of the image configuration.")
  })
).optional().describe("Define an image proxy in your stack. Store, transform, optimize, and deliver images at scale.");

// src/feature/table/schema.ts
import { minutes as minutes4, seconds as seconds4 } from "@awsless/duration";
import { z as z34 } from "zod";
var KeySchema = z34.string().min(1).max(255);
var TablesSchema = z34.record(
  ResourceIdSchema,
  z34.object({
    hash: KeySchema.describe(
      "Specifies the name of the partition / hash key that makes up the primary key for the table."
    ),
    sort: KeySchema.optional().describe(
      "Specifies the name of the range / sort key that makes up the primary key for the table."
    ),
    fields: z34.record(z34.string(), z34.enum(["string", "number", "binary"])).optional().describe(
      'A list of attributes that describe the key schema for the table and indexes. If no attribute field is defined we default to "string".'
    ),
    class: z34.enum(["standard", "standard-infrequent-access"]).default("standard").describe("The table class of the table."),
    pointInTimeRecovery: z34.boolean().default(false).describe("Indicates whether point in time recovery is enabled on the table."),
    ttl: KeySchema.optional().describe(
      [
        "The name of the TTL attribute used to store the expiration time for items in the table.",
        "To update this property, you must first disable TTL and then enable TTL with the new attribute name."
      ].join("\n")
    ),
    // deletionProtection: DeletionProtectionSchema.optional(),
    stream: z34.object({
      type: z34.enum(["keys-only", "new-image", "old-image", "new-and-old-images"]).describe(
        [
          "When an item in the table is modified, you can determines what information is written to the stream for this table.",
          "Valid values are:",
          "- keys-only - Only the key attributes of the modified item are written to the stream.",
          "- new-image - The entire item, as it appears after it was modified, is written to the stream.",
          "- old-image - The entire item, as it appeared before it was modified, is written to the stream.",
          "- new-and-old-images - Both the new and the old item images of the item are written to the stream."
        ].join("\n")
      ),
      batchSize: z34.number().min(1).max(1e4).default(1).describe(
        [
          "The maximum number of records in each batch that Lambda pulls from your stream and sends to your function.",
          "Lambda passes all of the records in the batch to the function in a single call, up to the payload limit for synchronous invocation (6 MB).",
          "You can specify a number from 1 to 10000."
        ].join("\n")
      ),
      batchWindow: DurationSchema.refine(
        durationMin(seconds4(1)),
        "Minimum batch window duration is 1 second"
      ).refine(durationMax(minutes4(5)), "Maximum batch window duration is 5 minutes").optional().describe(
        [
          "The maximum amount of time that is spend gathering records before invoking the function.",
          "You can specify a duration from 1 seconds to 5 minutes."
        ].join("\n")
      ),
      // maxRecordAge: DurationSchema.refine(
      // 	durationMin(seconds(1)),
      // 	'Minimum record age duration is 1 second'
      // )
      // 	.refine(durationMax(minutes(5)), 'Maximum batch window duration is 5 minutes')
      // 	.optional()
      // 	.describe(
      // 		[
      // 			'Discard records after the specified number of retries.',
      // 			'The default value is -1, which sets the maximum number of retries to infinite.',
      // 			'When maxRetryAttempts is infinite, Lambda retries failed records until the record expires in the event source.',
      // 			'You can specify a number from -1 to 10000.',
      // 		].join('\n')
      // 	),
      retryAttempts: z34.number().min(-1).max(1e4).default(-1).describe(
        [
          "Discard records after the specified number of retries.",
          "The default value is -1, which sets the maximum number of retries to infinite.",
          "When maxRetryAttempts is infinite, Lambda retries failed records until the record expires in the event source.",
          "You can specify a number from -1 to 10000."
        ].join("\n")
      ),
      concurrencyPerShard: z34.number().min(1).max(10).default(1).describe(
        [
          "The number of batches to process concurrently from each shard.",
          "You can specify a number from 1 to 10."
        ].join("\n")
      ),
      consumer: FunctionSchema.describe("The consuming lambda function for the stream")
    }).optional().describe(
      "The settings for the DynamoDB table stream, which capture changes to items stored in the table."
    ),
    indexes: z34.record(
      z34.string(),
      z34.object({
        hash: KeySchema.describe(
          "Specifies the name of the partition / hash key that makes up the primary key for the global secondary index."
        ),
        sort: KeySchema.optional().describe(
          "Specifies the name of the range / sort key that makes up the primary key for the global secondary index."
        ),
        projection: z34.enum(["all", "keys-only"]).default("all").describe(
          [
            "The set of attributes that are projected into the index:",
            "- all - All of the table attributes are projected into the index.",
            "- keys-only - Only the index and primary keys are projected into the index.",
            '@default "all"'
          ].join("\n")
        )
      })
    ).optional().describe("Specifies the global secondary indexes to be created on the table.")
  })
).optional().describe("Define the tables in your stack.");

// src/feature/task/schema.ts
import { z as z35 } from "zod";
var RetryAttemptsSchema2 = z35.number().int().min(0).max(2).describe(
  "The maximum number of times to retry when the function returns an error. You can specify a number from 0 to 2."
);
var TaskSchema = z35.union([
  LocalFileSchema.transform((file) => ({
    consumer: {
      code: {
        file,
        minify: true,
        external: []
      }
    },
    retryAttempts: void 0
  })),
  z35.object({
    consumer: FunctionSchema,
    retryAttempts: RetryAttemptsSchema2.optional()
  })
]);
var TasksSchema = z35.record(ResourceIdSchema, TaskSchema).optional().describe("Define the tasks in your stack.");

// src/feature/test/schema.ts
import { z as z36 } from "zod";
var TestsSchema = z36.union([LocalDirectorySchema.transform((v) => [v]), LocalDirectorySchema.array()]).describe("Define the location of your tests for your stack.").optional();

// src/feature/topic/schema.ts
import { kebabCase as kebabCase3 } from "change-case";
import { z as z37 } from "zod";
var TopicNameSchema = z37.string().min(3).max(256).regex(/^[a-z0-9\-]+$/i, "Invalid topic name").transform((value) => kebabCase3(value)).describe("Define event topic name.");
var TopicsSchema = z37.array(TopicNameSchema).refine((topics) => {
  return topics.length === new Set(topics).size;
}, "Must be a list of unique topic names").optional().describe("Define the event topics to publish too in your stack.");
var SubscribersSchema = z37.record(TopicNameSchema, FunctionSchema).optional().describe("Define the event topics to subscribe too in your stack.");

// src/config/stack.ts
var DependsSchema = ResourceIdSchema.array().optional().describe("Define the stacks that this stack is depended on.");
var NameSchema = ResourceIdSchema.refine((name) => !["base", "hostedzones"].includes(name), {
  message: `Stack name can't be a reserved name.`
}).describe("Stack name.");
var StackSchema = z38.object({
  $schema: z38.string().optional(),
  name: NameSchema,
  depends: DependsSchema,
  commands: CommandsSchema,
  // onFailure: OnFailureSchema,
  // auth: AuthSchema,
  // graphql: GraphQLSchema,
  // http: HttpSchema,
  rest: RestSchema,
  rpc: RpcSchema,
  configs: ConfigsSchema,
  crons: CronsSchema,
  caches: CachesSchema,
  topics: TopicsSchema,
  subscribers: SubscribersSchema,
  functions: FunctionsSchema,
  instances: InstancesSchema,
  tasks: TasksSchema,
  tables: TablesSchema,
  stores: StoresSchema,
  // streams: StreamsSchema,
  queues: QueuesSchema,
  pubsub: PubSubSchema,
  searchs: SearchsSchema,
  sites: SitesSchema,
  tests: TestsSchema,
  images: ImagesSchema,
  icons: IconsSchema
});

// cli/build-json-schema.ts
var generateJsonSchema = (props) => {
  const file = join2(process.cwd(), `dist/${props.name}.json`);
  const schema = zodToJsonSchema(props.schema, {
    name: props.name,
    // errorMessages: true,
    markdownDescription: true,
    pipeStrategy: "input",
    $refStrategy: "none"
  });
  appendDefaults(schema);
  schema.title = props.title;
  writeFileSync(file, JSON.stringify(schema));
};
var appendDefaults = (object) => {
  if (Array.isArray(object)) {
    object.forEach(appendDefaults);
  }
  if (typeof object === "object" && object !== null) {
    if ("default" in object && "type" in object) {
      if ("description" in object) {
        object.description += `

@default ${JSON.stringify(object.default)}`;
      }
      if ("markdownDescription" in object) {
        object.markdownDescription += `

@default \`\`\`${JSON.stringify(object.default)}\`\`\``;
      }
    } else {
      Object.values(object).forEach(appendDefaults);
    }
  }
};
generateJsonSchema({
  schema: AppSchema,
  name: "app",
  title: "Awsless App Config"
});
generateJsonSchema({
  schema: StackSchema,
  name: "stack",
  title: "Awsless Stack Config"
});
