@awsless/awsless 0.0.112 → 0.0.114

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/bin.js CHANGED
@@ -1423,18 +1423,18 @@ var TypeObject = class {
1423
1423
  this.readonly = readonly;
1424
1424
  }
1425
1425
  types = /* @__PURE__ */ new Map();
1426
- addType(name, type) {
1426
+ add(name, type) {
1427
1427
  const value = type.toString();
1428
1428
  if (value) {
1429
- this.types.set(camelCase(name), value);
1429
+ this.types.set(name, value);
1430
1430
  }
1431
1431
  return this;
1432
1432
  }
1433
+ addType(name, type) {
1434
+ return this.add(camelCase(name), type);
1435
+ }
1433
1436
  addConst(name, type) {
1434
- if (type) {
1435
- this.types.set(constantCase3(name), type);
1436
- }
1437
- return this;
1437
+ return this.add(constantCase3(name), type);
1438
1438
  }
1439
1439
  toString() {
1440
1440
  if (!this.types.size) {
@@ -3399,6 +3399,8 @@ var graphqlPlugin = definePlugin({
3399
3399
  ).optional()
3400
3400
  }).array()
3401
3401
  }),
3402
+ onTypeGen({ config: config2 }) {
3403
+ },
3402
3404
  onApp(ctx) {
3403
3405
  const { config: config2, bootstrap: bootstrap2 } = ctx;
3404
3406
  const apis = /* @__PURE__ */ new Set();
@@ -4417,8 +4419,10 @@ var ElbEventSource = class extends Group {
4417
4419
  };
4418
4420
 
4419
4421
  // src/plugins/http.ts
4422
+ import { relative as relative4 } from "path";
4423
+ import { camelCase as camelCase4 } from "change-case";
4420
4424
  var RouteSchema = z18.custom((route) => {
4421
- return z18.string().regex(/^(POST|GET|PUT|DELETE|HEAD|OPTIONS)(\s\/[a-z0-9\+\_\-\/]*)$/ig).safeParse(route).success;
4425
+ return z18.string().regex(/^(POST|GET|PUT|DELETE|HEAD|OPTIONS)(\s\/[a-z0-9\+\_\-\/\{\}]*)$/gi).safeParse(route).success;
4422
4426
  }, "Invalid route");
4423
4427
  var parseRoute = (route) => {
4424
4428
  const [method, ...paths] = route.split(" ");
@@ -4471,12 +4475,60 @@ var httpPlugin = definePlugin({
4471
4475
  * }
4472
4476
  * }
4473
4477
  */
4474
- http: z18.record(
4475
- ResourceIdSchema,
4476
- z18.record(RouteSchema, FunctionSchema)
4477
- ).optional()
4478
+ http: z18.record(ResourceIdSchema, z18.record(RouteSchema, FunctionSchema)).optional()
4478
4479
  }).array()
4479
4480
  }),
4481
+ onTypeGen({ config: config2 }) {
4482
+ const types2 = new TypeGen("@awsless/awsless");
4483
+ const resources = new TypeObject(1);
4484
+ const api = {};
4485
+ for (const stack of config2.stacks) {
4486
+ for (const [id, routes] of Object.entries(stack.http || {})) {
4487
+ if (!(id in api))
4488
+ api[id] = {};
4489
+ for (const [route, props] of Object.entries(routes)) {
4490
+ const { path, method } = parseRoute(route);
4491
+ const file = typeof props === "string" ? props : props.file;
4492
+ if (!(method in api[id]))
4493
+ api[id][method] = {};
4494
+ api[id][method][path] = file;
4495
+ }
4496
+ }
4497
+ }
4498
+ for (const [id, routes] of Object.entries(api)) {
4499
+ const idType = new TypeObject(2);
4500
+ for (const [method, paths] of Object.entries(routes)) {
4501
+ const methodType = new TypeObject(3);
4502
+ for (const [path, file] of Object.entries(paths)) {
4503
+ const paramType = new TypeObject(4);
4504
+ for (const param of path.matchAll(/{([a-z0-9]+)}/g)) {
4505
+ paramType.addType(param[0], "string | number");
4506
+ }
4507
+ const varName = camelCase4(`${id}-${path}-${method}`);
4508
+ const relFile = relative4(directories.types, file);
4509
+ types2.addImport(varName, relFile);
4510
+ methodType.add(`'${path}'`, `Route<typeof ${varName}, ${paramType.toString() || "never"}>`);
4511
+ }
4512
+ idType.addConst(method, methodType);
4513
+ }
4514
+ resources.addType(id, idType);
4515
+ }
4516
+ const code = [
4517
+ `import { InvokeResponse } from '@awsless/lambda'`,
4518
+ `type Function = (...args: any) => any`,
4519
+ `type Event<F extends Function> = Parameters<F>[0]`,
4520
+ `type RequestWithQuery = { request: { queryStringParameters: any } }`,
4521
+ `type RequestWithBody = { request: { body: any } }`,
4522
+ `type ResponseWithBody = { statusCode: number, body: any }`,
4523
+ `type Query<F extends Function> = Event<F> extends RequestWithQuery ? Event<F>['request']['queryStringParameters'] : never`,
4524
+ `type Body<F extends Function> = Event<F> extends RequestWithBody ? Exclude<Event<F>['request']['body'], string> : never`,
4525
+ `type Response<F extends Function> = Awaited<InvokeResponse<F>> extends ResponseWithBody ? Promise<Awaited<InvokeResponse<F>>['body']> : Promise<never>`,
4526
+ `type Route<F extends Function, P> = { param: P; query: Query<F>; body: Body<F>; response: Response<F> }`
4527
+ ];
4528
+ code.map((code2) => types2.addCode(code2));
4529
+ types2.addInterface("HTTP", resources);
4530
+ return types2.toString();
4531
+ },
4480
4532
  onApp({ config: config2, bootstrap: bootstrap2 }) {
4481
4533
  if (Object.keys(config2.defaults?.http || {}).length === 0) {
4482
4534
  return;
@@ -4494,18 +4546,13 @@ var httpPlugin = definePlugin({
4494
4546
  name: `${config2.name}-${id}`,
4495
4547
  type: "application",
4496
4548
  securityGroups: [securityGroup.id],
4497
- subnets: [
4498
- bootstrap2.get("public-subnet-1"),
4499
- bootstrap2.get("public-subnet-2")
4500
- ]
4549
+ subnets: [bootstrap2.get("public-subnet-1"), bootstrap2.get("public-subnet-2")]
4501
4550
  }).dependsOn(securityGroup);
4502
4551
  const listener = new Listener(id, {
4503
4552
  loadBalancerArn: loadBalancer.arn,
4504
4553
  port: 443,
4505
4554
  protocol: "https",
4506
- certificates: [
4507
- bootstrap2.get(`certificate-${props.domain}-arn`)
4508
- ],
4555
+ certificates: [bootstrap2.get(`certificate-${props.domain}-arn`)],
4509
4556
  defaultActions: [
4510
4557
  ListenerAction.fixedResponse(404, {
4511
4558
  contentType: "application/json",
@@ -5356,7 +5403,7 @@ var LocalDirectorySchema = z24.string().refine(async (path) => {
5356
5403
  }, `Directory doesn't exist`);
5357
5404
 
5358
5405
  // src/formation/resource/cloud-front/origin-request-policy.ts
5359
- import { camelCase as camelCase4 } from "change-case";
5406
+ import { camelCase as camelCase5 } from "change-case";
5360
5407
  var OriginRequestPolicy = class extends Resource {
5361
5408
  constructor(logicalId, props = {}) {
5362
5409
  super("AWS::CloudFront::OriginRequestPolicy", logicalId);
@@ -5372,15 +5419,15 @@ var OriginRequestPolicy = class extends Resource {
5372
5419
  OriginRequestPolicyConfig: {
5373
5420
  Name: this.name,
5374
5421
  CookiesConfig: {
5375
- CookieBehavior: camelCase4(this.props.cookie?.behavior ?? "all"),
5422
+ CookieBehavior: camelCase5(this.props.cookie?.behavior ?? "all"),
5376
5423
  ...this.attr("Cookies", this.props.cookie?.values)
5377
5424
  },
5378
5425
  HeadersConfig: {
5379
- HeaderBehavior: camelCase4(this.props.header?.behavior ?? "allViewer"),
5426
+ HeaderBehavior: camelCase5(this.props.header?.behavior ?? "allViewer"),
5380
5427
  ...this.attr("Headers", this.props.header?.values)
5381
5428
  },
5382
5429
  QueryStringsConfig: {
5383
- QueryStringBehavior: camelCase4(this.props.query?.behavior ?? "all"),
5430
+ QueryStringBehavior: camelCase5(this.props.query?.behavior ?? "all"),
5384
5431
  ...this.attr("QueryStrings", this.props.query?.values)
5385
5432
  }
5386
5433
  }
@@ -8310,7 +8357,7 @@ import commonjs3 from "@rollup/plugin-commonjs";
8310
8357
  import nodeResolve3 from "@rollup/plugin-node-resolve";
8311
8358
  import { swc as swc4 } from "rollup-plugin-swc3";
8312
8359
  import { getSuites, getTests } from "@vitest/runner/utils";
8313
- import { basename as basename3, dirname as dirname6, extname as extname2, join as join11, relative as relative4 } from "path";
8360
+ import { basename as basename3, dirname as dirname6, extname as extname2, join as join11, relative as relative5 } from "path";
8314
8361
 
8315
8362
  // src/cli/ui/layout/text-box.ts
8316
8363
  import wrapAnsi3 from "wrap-ansi";
@@ -8397,7 +8444,7 @@ var singleTester = (stack, dir, filters) => {
8397
8444
  return "";
8398
8445
  }
8399
8446
  const abs = join11(process.cwd(), path);
8400
- const rel = relative4(dir, abs);
8447
+ const rel = relative5(dir, abs);
8401
8448
  const ext = extname2(rel);
8402
8449
  if (!ext) {
8403
8450
  return path;
@@ -8814,7 +8861,6 @@ var test = (program2) => {
8814
8861
  program2.command("test").argument("[stacks...]", "Optionally filter stacks to test").option("-f --filters <string...>", "Optionally filter test files").description("Test your app").action(async (stacks, options) => {
8815
8862
  await layout(async (config2, write) => {
8816
8863
  const { tests } = await toApp(config2, stacks);
8817
- debug(stacks, options);
8818
8864
  if (tests.size === 0) {
8819
8865
  write(dialog("warning", ["No tests found"]));
8820
8866
  return;
package/dist/index.d.ts CHANGED
@@ -11241,6 +11241,42 @@ interface SearchResources {
11241
11241
  }
11242
11242
  declare const Search: SearchResources;
11243
11243
 
11244
+ interface HTTP {
11245
+ }
11246
+ type Method = 'GET' | 'POST';
11247
+ type Path = string;
11248
+ type Params = Record<string, string | number>;
11249
+ type Query = Record<string, string>;
11250
+ type Body = unknown;
11251
+ type Route = {
11252
+ param?: Params;
11253
+ query?: Query;
11254
+ body?: Body;
11255
+ response: unknown;
11256
+ };
11257
+ type Routes = Record<Path, Route>;
11258
+ type Schema = Partial<Record<Method, Routes>>;
11259
+ type GetRoute<S extends Schema, M extends keyof S, P extends keyof S[M]> = S[M] extends Routes ? S[M][P] : never;
11260
+ type Props<R extends Route> = {
11261
+ headers?: Record<string, string>;
11262
+ params?: R['param'] extends Params ? R['param'] : never;
11263
+ query?: R['query'] extends Query ? R['query'] : never;
11264
+ body?: R['body'] extends Body ? R['body'] : never;
11265
+ };
11266
+ type HttpFetcher = (props: {
11267
+ method: Method;
11268
+ path: Path;
11269
+ headers: Headers;
11270
+ query?: Query;
11271
+ body?: Body;
11272
+ }) => unknown;
11273
+ declare const createHttpFetcher: (host: string) => HttpFetcher;
11274
+ declare const createHttpClient: <S extends Partial<Record<Method, Routes>>>(fetcher: HttpFetcher) => {
11275
+ fetch: <M extends keyof S, P extends keyof S[M]>(method: M, routeKey: Extract<P, string>, props?: Props<GetRoute<S, M, P>> | undefined) => Promise<GetRoute<S, M, P>["response"]>;
11276
+ get<P_1 extends keyof S["GET"]>(routeKey: Extract<P_1, string>, props?: Props<GetRoute<S, "GET", P_1>> | undefined): Promise<GetRoute<S, "GET", P_1>["response"]>;
11277
+ post<P_2 extends keyof S["POST"]>(routeKey: Extract<P_2, string>, props?: Props<GetRoute<S, "POST", P_2>> | undefined): Promise<GetRoute<S, "POST", P_2>["response"]>;
11278
+ };
11279
+
11244
11280
  type FunctionProps<H extends Handler<S>, S extends BaseSchema> = {
11245
11281
  handle: H;
11246
11282
  schema?: S;
@@ -12101,4 +12137,4 @@ declare const defineStackConfig: (config: StackConfig) => StackConfig$1 | (Stack
12101
12137
  });
12102
12138
  declare const defineAppConfig: (config: AppConfig | AppConfigFactory<AppConfig>) => CombinedDefaultPluginsConfigInput | AppConfigFactory<CombinedDefaultPluginsConfigInput>;
12103
12139
 
12104
- export { APP, AppConfig, Auth, AuthResources, Cache, CacheResources, Config, ConfigResources, CronProps, Fn, Function, FunctionMock, FunctionMockResponse, FunctionProps, FunctionResources, Plugin, Queue, QueueMock, QueueMockResponse, QueueProps, QueueResources, STACK, Search, SearchResources, StackConfig, Store, StoreResources, Table, TableResources, Topic, TopicMock, TopicMockResponse, TopicProps, TopicResources, cron, defineAppConfig, definePlugin, defineStackConfig, func, getAuthName, getAuthProps, getCacheProps, getConfigName, getFunctionName, getGlobalResourceName, getLocalResourceName, getQueueName, getSearchName, getStoreName, getTableName, getTopicName, mockFunction, mockQueue, mockTopic, queue, topic };
12140
+ export { APP, AppConfig, Auth, AuthResources, Cache, CacheResources, Config, ConfigResources, CronProps, Fn, Function, FunctionMock, FunctionMockResponse, FunctionProps, FunctionResources, HTTP, HttpFetcher, Plugin, Queue, QueueMock, QueueMockResponse, QueueProps, QueueResources, STACK, Search, SearchResources, StackConfig, Store, StoreResources, Table, TableResources, Topic, TopicMock, TopicMockResponse, TopicProps, TopicResources, createHttpClient, createHttpFetcher, cron, defineAppConfig, definePlugin, defineStackConfig, func, getAuthName, getAuthProps, getCacheProps, getConfigName, getFunctionName, getGlobalResourceName, getLocalResourceName, getQueueName, getSearchName, getStoreName, getTableName, getTopicName, mockFunction, mockQueue, mockTopic, queue, topic };
package/dist/index.js CHANGED
@@ -250,6 +250,49 @@ var Search = /* @__PURE__ */ createProxy((stack) => {
250
250
  });
251
251
  });
252
252
 
253
+ // src/node/http.ts
254
+ var createHttpFetcher = (host) => {
255
+ return async ({ method, path, headers, body, query }) => {
256
+ const url = new URL(host, path);
257
+ if (query) {
258
+ for (const [key, value] of Object.entries(query)) {
259
+ url.searchParams.set(key, value);
260
+ }
261
+ }
262
+ headers.set("content-type", "application/json");
263
+ const response = await fetch(url, {
264
+ method,
265
+ headers,
266
+ body: body ? JSON.stringify(body) : void 0
267
+ });
268
+ const result = await response.json();
269
+ return result;
270
+ };
271
+ };
272
+ var createHttpClient = (fetcher) => {
273
+ const fetch2 = (method, routeKey, props) => {
274
+ const path = routeKey.replaceAll(/{([a-z0-1-]+)}/, (key) => {
275
+ return props?.params?.[key.substring(1, key.length - 1)].toString() ?? "";
276
+ });
277
+ return fetcher({
278
+ headers: new Headers(props?.headers),
279
+ query: props?.query,
280
+ body: props?.body,
281
+ method,
282
+ path
283
+ });
284
+ };
285
+ return {
286
+ fetch: fetch2,
287
+ get(routeKey, props) {
288
+ return fetch2("GET", routeKey, props);
289
+ },
290
+ post(routeKey, props) {
291
+ return fetch2("POST", routeKey, props);
292
+ }
293
+ };
294
+ };
295
+
253
296
  // src/node/handle/function.ts
254
297
  import { lambda } from "@awsless/lambda";
255
298
  var func = (props) => {
@@ -364,6 +407,8 @@ export {
364
407
  Store,
365
408
  Table,
366
409
  Topic,
410
+ createHttpClient,
411
+ createHttpFetcher,
367
412
  cron,
368
413
  defineAppConfig,
369
414
  definePlugin,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awsless/awsless",
3
- "version": "0.0.112",
3
+ "version": "0.0.114",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -24,13 +24,13 @@
24
24
  }
25
25
  },
26
26
  "peerDependencies": {
27
- "@awsless/redis": "^0.0.8",
28
27
  "@awsless/lambda": "^0.0.14",
28
+ "@awsless/redis": "^0.0.8",
29
+ "@awsless/sns": "^0.0.7",
29
30
  "@awsless/sqs": "^0.0.7",
31
+ "@awsless/ssm": "^0.0.7",
30
32
  "@awsless/validate": "^0.0.10",
31
- "@awsless/sns": "^0.0.7",
32
- "@awsless/weak-cache": "^0.0.1",
33
- "@awsless/ssm": "^0.0.7"
33
+ "@awsless/weak-cache": "^0.0.1"
34
34
  },
35
35
  "dependencies": {
36
36
  "@aws-appsync/utils": "^1.5.0",