├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md ├── pr_owners.txt ├── stale.yml └── workflows │ └── test.yml ├── .gitignore ├── .prettierrc ├── .vscode └── settings.json ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── docs └── guide.md ├── examples ├── graphql-api │ ├── codegen.yml │ ├── index.ts │ ├── lambda │ │ ├── common.ts │ │ ├── create-note.ts │ │ ├── delete-note.ts │ │ ├── index.ts │ │ ├── note.ts │ │ └── notes.ts │ └── schema.gql ├── index.ts └── rest-api │ ├── index.ts │ └── lambda │ ├── hello-concise-constructs.ts │ └── index.ts ├── package-lock.json ├── package.json ├── src ├── ctor.test.ts ├── ctor.ts ├── define.test.ts ├── define.ts ├── index.ts ├── tests │ ├── basic.ts │ ├── overwrites.ts │ └── types.ts └── util │ ├── in-rest.test.ts │ ├── in-rest.ts │ ├── index.ts │ ├── molecules.ts │ ├── recombine-tagged-template-args.test.ts │ └── recombine-tagged-template-args.ts ├── tsconfig.base.json ├── tsconfig.build.json └── tsconfig.json /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: "Is something going wrong?" 4 | title: "Bug: " 5 | labels: "" 6 | --- 7 | 8 | 12 | 13 | **`concise-constructs` version:** \[version\] 14 | 15 | 16 | 17 | **Search Terms:** 18 | 19 | **Code:** 20 | 21 | 22 | 23 | ```ts 24 | const a = "B"; 25 | ``` 26 | 27 | **Expected Behavior:** 28 | 29 | **Actual Behavior:** 30 | 31 | **Sandbox / Repo Link:** 32 | 33 | **Related Issues:** 34 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: "Do you have an idea for new functionality?" 4 | title: "Feature Request: " 5 | labels: "" 6 | --- 7 | 8 | ## Search Terms 9 | 10 | 11 | 12 | ## Suggestion 13 | 14 | 15 | 16 | ## Use Cases 17 | 18 | 22 | 23 | ## Examples 24 | 25 | 26 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | **Summary**: 8 | 9 | Please verify the following: 10 | 11 | - [ ] Your PR is up-to-date with the `main` branch 12 | - [ ] There are new or updated tests validating the change 13 | - [ ] You have successfully run `npm run test` locally 14 | - [ ] If the API is changed, there is documentation reflecting the change. 15 | -------------------------------------------------------------------------------- /.github/pr_owners.txt: -------------------------------------------------------------------------------- 1 | harrysolovay -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | only: issues 2 | daysUntilStale: 30 3 | daysUntilClose: 7 4 | exemptLabels: 5 | - feature-request 6 | - to-be-reproduced 7 | - bug 8 | - tracked 9 | - needs-discussion 10 | staleLabel: pending-close-response-required 11 | markComment: > 12 | Please follow-up on this issue if you wish to keep it open. Thank you! 13 | 14 | 15 | closeComment: > 16 | This issue has been closed because of inactivity. Please open a new issue if you are still encountering problems. 17 | 18 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: 3 | push: 4 | branches: 5 | - "**" 6 | - "!main" 7 | jobs: 8 | test: 9 | name: Test 10 | runs-on: ubuntu-20.04 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: actions/setup-node@v1 14 | with: 15 | node-version: "12.x" 16 | - run: npm ci 17 | - run: yarn test 18 | - run: yarn build 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /* 2 | !.github 3 | !.gitignore 4 | !.prettierrc 5 | !.vscode 6 | !CHANGELOG.md 7 | !CODE_OF_CONDUCT.md 8 | !CONTRIBUTING.md 9 | !docs 10 | examples/*/cdk.out 11 | examples/*/outputs.json 12 | examples/*/lambda/dist 13 | examples/*/lambda/generated-types.ts 14 | !examples 15 | !LICENSE 16 | !NOTICE 17 | !package.json 18 | !package-lock.json 19 | !README.md 20 | !src 21 | !tsconfig*.json 22 | **/.DS_Store 23 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "always", 3 | "bracketSpacing": false, 4 | "embeddedLanguageFormatting": "auto", 5 | "jsxBracketSameLine": false, 6 | "jsxSingleQuote": false, 7 | "printWidth": 140, 8 | "proseWrap": "never", 9 | "semi": true, 10 | "singleQuote": false, 11 | "tabWidth": 2, 12 | "trailingComma": "all", 13 | "useTabs": false 14 | } 15 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "[graphql]": { 3 | "editor.defaultFormatter": "esbenp.prettier-vscode", 4 | "editor.formatOnSave": true 5 | }, 6 | "[javascript]": { 7 | "editor.defaultFormatter": "esbenp.prettier-vscode", 8 | "editor.formatOnSave": true 9 | }, 10 | "[json]": { 11 | "editor.defaultFormatter": "esbenp.prettier-vscode", 12 | "editor.formatOnSave": true 13 | }, 14 | "[jsonc]": { 15 | "editor.defaultFormatter": "esbenp.prettier-vscode", 16 | "editor.formatOnSave": true 17 | }, 18 | "[typescript]": { 19 | "editor.defaultFormatter": "esbenp.prettier-vscode", 20 | "editor.formatOnSave": true 21 | }, 22 | "[markdown]": { 23 | "editor.defaultFormatter": "esbenp.prettier-vscode", 24 | "editor.formatOnSave": true, 25 | "editor.quickSuggestions": true, 26 | "editor.suggest.showReferences": true, 27 | "editor.wordWrap": "on" 28 | }, 29 | "[yaml]": { 30 | "editor.insertSpaces": true, 31 | "editor.tabSize": 2, 32 | "editor.quickSuggestions": { 33 | "other": true, 34 | "comments": false, 35 | "strings": true 36 | }, 37 | "editor.defaultFormatter": "esbenp.prettier-vscode", 38 | "editor.formatOnSave": true 39 | }, 40 | "deno.enable": false, 41 | "editor.tabSize": 2, 42 | "editor.formatOnSave": true, 43 | "git.ignoreLimitWarning": true 44 | } 45 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | ### [0.0.2](https://github.com/awslabs/concise-constructs/compare/v0.0.2-next.2...v0.0.2) (2021-01-26) 6 | 7 | ### [0.0.2-next.2](https://github.com/awslabs/concise-constructs/compare/v0.0.2-next.1...v0.0.2-next.2) (2021-01-26) 8 | 9 | ### [0.0.2-next.1](https://github.com/awslabs/concise-constructs/compare/v0.0.2-next.0...v0.0.2-next.1) (2021-01-26) 10 | 11 | ### Bug Fixes 12 | 13 | - make IsRoot work with CDK constructs ([8e6122c](https://github.com/awslabs/concise-constructs/commit/8e6122cd5746a9d4291697b5709601f14742406b)) 14 | 15 | ### [0.0.2-next.0](https://github.com/awslabs/concise-constructs/compare/v0.0.1...v0.0.2-next.0) (2021-01-26) 16 | 17 | ### 0.0.1 (2021-01-26) 18 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | 3 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact opensource-codeofconduct@amazon.com with any additional questions or comments. 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional documentation, we greatly value feedback and contributions from our community. 4 | 5 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary information to effectively respond to your bug report or contribution. 6 | 7 | ## Reporting Bugs/Feature Requests 8 | 9 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 10 | 11 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 12 | 13 | - A reproducible test case or series of steps 14 | - The version of our code being used 15 | - Any modifications you've made relevant to the bug 16 | - Anything unusual about your environment or deployment 17 | 18 | ## Contributing via Pull Requests 19 | 20 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 21 | 22 | 1. You are working against the latest source on the _main_ branch. 23 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 24 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 25 | 26 | To send us a pull request, please: 27 | 28 | 1. Fork the repository. 29 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 30 | 3. Ensure local tests pass. 31 | 4. Commit to your fork using clear commit messages. 32 | 5. Send us a pull request, answering any default questions in the pull request interface. 33 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 34 | 35 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 36 | 37 | ## Finding contributions to work on 38 | 39 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 40 | 41 | ## Code of Conduct 42 | 43 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact opensource-codeofconduct@amazon.com with any additional questions or comments. 44 | 45 | ## Security issue notifications 46 | 47 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 48 | 49 | ## Licensing 50 | 51 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 52 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Concise Constructs 2 | 3 | [![npm version](https://img.shields.io/npm/v/concise-constructs.svg?style=flat-square)](https://badge.fury.io/js/concise-constructs) ![license](https://img.shields.io/npm/l/concise-constructs.svg?style=flat-square) [![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://github.com/awslabs/concise-constructs/blob/master/CONTRIBUTING.md#submitting-pull-requests) 4 | 5 | **A utility for defining constructs without ever needing to think about scope.** "Concise" constructs are interoperable with classical constructs. The difference is cosmetic; if concise constructs better-jive with your API-design sensibilities, great! Otherwise, [classical constructs](https://github.com/aws/constructs) are still state of the art. 6 | 7 | > NOTE: this repo follows SemVer and there is yet to be a major release; the public API can still change. 8 | 9 | > NOTE: [JSII](https://github.com/aws/jsii) cannot yet package concise constructs for consumption in non-TypeScript CDK projects. 10 | 11 | --- 12 | 13 | ## Resources 14 | 15 | 16 | 17 | - [Guide →](docs/guide.md)
An explanation of the mechanics 18 | - [Rest API Example →](examples/rest-api)
Using Lambda & API Gateway 19 | - [GraphQL API →](examples/graphql-api)
Using AppSync, Lambda Resolvers & DynamoDB 20 | 21 | > To execute an example, run `npm run example [example-dir] [command]` (for example, `npm run example graphql-api deploy`) 22 | 23 | ## Installation 24 | 25 | **Node** users can install with [npm](https://www.npmjs.com/package/concise-constructs). 26 | 27 | ```sh 28 | npm install concise-constructs 29 | ``` 30 | 31 | > Packaged as [CommonJS](http://wiki.commonjs.org/wiki/Modules/1.1), alongside corresponding type definitions. 32 | 33 | ## Snippets 34 | 35 | ### Lambda Rest API 36 | 37 | ```ts 38 | import {C} from "concise-constructs"; 39 | import * as cdk from "@aws-cdk/core"; 40 | import * as lambda from "@aws-cdk/aws-lambda"; 41 | import path from "path"; 42 | 43 | const code = new lambda.AssetCode(path.resolve(__dirname, "lambda")); 44 | 45 | const Stack = C(cdk.Stack, (define) => ({ 46 | fn: define`my-fn`(lambda.Function, { 47 | code, 48 | handler: "index.handler", 49 | runtime: lambda.Runtime.NODEJS_12_X, 50 | }), 51 | })); 52 | 53 | const App = C(cdk.App, (define) => { 54 | define`my-stack`(Stack); 55 | }); 56 | 57 | new App().synth(); 58 | ``` 59 | 60 |
61 | ... is equivalent to the following. 62 | 63 | ```ts 64 | import * as cdk from "@aws-cdk/core"; 65 | import * as lambda from "@aws-cdk/aws-lambda"; 66 | import path from "path"; 67 | 68 | const code = new lambda.AssetCode(path.resolve(__dirname, "lambda")); 69 | 70 | class Stack extends cdk.Stack { 71 | fn; 72 | 73 | constructor(scope: cdk.App, id: string) { 74 | super(scope, id); 75 | 76 | this.fn = new lambda.Function(this, "my-fn", { 77 | code, 78 | handler: "index.handler", 79 | runtime: lambda.Runtime.NODEJS_12_X, 80 | }); 81 | } 82 | } 83 | 84 | class App extends cdk.App { 85 | constructor() { 86 | super(); 87 | 88 | new Stack(this, "my-stack"); 89 | } 90 | } 91 | 92 | new App().synth(); 93 | ``` 94 | 95 |
96 | 97 | ### SQS + SNS 98 | 99 | ```ts 100 | import {C} from "concise-constructs"; 101 | import * as cdk from "@aws-cdk/core"; 102 | import * as sqs from "@aws-cdk/aws-sqs"; 103 | import * as sns from "@aws-cdk/aws-sns"; 104 | 105 | const Stack = C(cdk.Stack, (define) => { 106 | const queue = define`HelloCdkQueue`(sqs.Queue, { 107 | visibilityTimeout: cdk.Duration.seconds(300), 108 | }); 109 | 110 | const topic = define`HelloCdkTopic`(sns.Topic); 111 | 112 | topic.addSubscription(new subs.SqsSubscription(queue)); 113 | 114 | return {queue, topic}; 115 | }); 116 | 117 | const App = C(cdk.App, (define) => { 118 | const stack = define`my-stack`(Stack); 119 | stack.queue; // sqs.Queue 120 | stack.topic; // sns.Topic 121 | }); 122 | ``` 123 | 124 |
125 | ... is equivalent to the following. 126 | 127 | ```ts 128 | import * as cdk from "@aws-cdk/core"; 129 | import * as sqs from "@aws-cdk/aws-sqs"; 130 | import * as sns from "@aws-cdk/aws-sns"; 131 | 132 | class HelloCdkStack extends cdk.Stack { 133 | queue; 134 | topic; 135 | 136 | constructor(scope: cdk.App, id: string) { 137 | super(scope, id, props); 138 | 139 | this.queue = new sqs.Queue(this, "HelloCdkQueue", { 140 | visibilityTimeout: cdk.Duration.seconds(300), 141 | }); 142 | 143 | this.topic = new sns.Topic(this, "HelloCdkTopic"); 144 | 145 | topic.addSubscription(new subs.SqsSubscription(this.queue)); 146 | } 147 | } 148 | 149 | class App extends cdk.App { 150 | constructor() { 151 | super(); 152 | 153 | const stack = new Stack(this, "my-stack"); 154 | stack.queue; // sqs.Queue 155 | stack.topic; // sns.Topic 156 | } 157 | } 158 | 159 | new App().synth(); 160 | ``` 161 | 162 |
163 | 164 | ### Lambda CRON 165 | 166 | ```ts 167 | import {C} from "concise-constructs"; 168 | import * as cdk from "@aws-cdk/core"; 169 | import * as events from "@aws-cdk/aws-events"; 170 | import * as lambda from "@aws-cdk/aws-lambda"; 171 | import * as targets from "@aws-cdk/aws-event-targets"; 172 | 173 | const code = new lambda.AssetCode(path.resolve(__dirname, "lambda")); 174 | 175 | const Stack = C(cdk.Stack, (define) => { 176 | const lambdaFn = define`singleton`(lambda.Function, { 177 | code, 178 | handler: "index.handler", 179 | timeout: cdk.Duration.seconds(300), 180 | runtime: lambda.Runtime.PYTHON_3_6, 181 | }); 182 | 183 | const rule = define`rule`(events.Rule, { 184 | schedule: events.Schedule.expression("cron(0 18 ? * MON-FRI *)"), 185 | }); 186 | 187 | rule.addTarget(new targets.LambdaFunction(lambdaFn)); 188 | }); 189 | 190 | const App = C(cdk.App, (define) => { 191 | const stack = define`my-stack`(Stack); 192 | }); 193 | 194 | new App().synth(); 195 | ``` 196 | 197 |
198 | ... is equivalent to the following. 199 | 200 | ```ts 201 | import * as cdk from "@aws-cdk/core"; 202 | import * as events from "@aws-cdk/aws-events"; 203 | import * as lambda from "@aws-cdk/aws-lambda"; 204 | import * as targets from "@aws-cdk/aws-event-targets"; 205 | 206 | const code = new lambda.AssetCode(path.resolve(__dirname, "lambda")); 207 | 208 | class Stack extends cdk.Stack { 209 | constructor(scope: cdk.App, id: string) { 210 | super(scope, id); 211 | 212 | const lambdaFn = new lambda.Function(this, "singleton", { 213 | code, 214 | handler: "index.handler", 215 | timeout: cdk.Duration.seconds(300), 216 | runtime: lambda.Runtime.PYTHON_3_6, 217 | }); 218 | 219 | const rule = new events.Rule(this, "rule", { 220 | schedule: events.Schedule.expression("cron(0 18 ? * MON-FRI *)"), 221 | }); 222 | 223 | rule.addTarget(new targets.LambdaFunction(lambdaFn)); 224 | } 225 | } 226 | 227 | class App extends cdk.App { 228 | constructor() { 229 | new Stack(this, "my-stack"); 230 | } 231 | } 232 | 233 | new App().synth(); 234 | ``` 235 | 236 |
237 | 238 | ## Contributing 239 | 240 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 241 | 242 | ## License 243 | 244 | This project is licensed under the Apache-2.0 License. 245 | -------------------------------------------------------------------------------- /docs/guide.md: -------------------------------------------------------------------------------- 1 | ```ts 2 | import {C} from "concise-constructs"; 3 | ``` 4 | 5 | The `C` utility lets us make new construct constructors with less boilerplate. The base constructor––from which you'd typically extend––is the first argument to `C`. The second argument is a producer function, from which we can optionally return data to be used as members of the `C`-returned constructor's instances. 6 | 7 | ```ts 8 | import * as cdk from "@aws-cdk/core"; 9 | import {C} from "concise-constructs"; 10 | 11 | const Stack = C(cdk.Stack, (define) => { 12 | // ^ 13 | // we'll get to this soon 14 | 15 | return {hi: "Sam"}; 16 | }); 17 | 18 | const app = new cdk.App(); 19 | const stack = new Stack(app, "my-stack"); 20 | stack.hi; // "Sam" 21 | ``` 22 | 23 | To reiterate: calling `C` gives us a construct constructor, extending the supplied base (arg 0). The resulting constructor contains closure-returned data as members of any instance. 24 | 25 | This new constructor can be used by classical constructs. Aka., concise constructs are 1st class citizens! Users can mix and match as they please. 26 | 27 | ```ts 28 | import {Construct} from "@aws-cdk/core"; 29 | import {C} from "concise-constructs"; 30 | 31 | const B = C(Construct, (define) => { 32 | // we pass the construct ID via tags on `define` 33 | define`child`(Construct); 34 | }); 35 | 36 | class C extends Construct { 37 | constructor(scope: Construct, id: string) { 38 | super(scope, id); 39 | 40 | new B(this, "b"); 41 | } 42 | } 43 | 44 | class D extends C(Construct, (define) => { 45 | define`extended`(C); 46 | }) {} 47 | 48 | class E extends D { 49 | constructor(scope: Construct, id: string, props: {name: string}) { 50 | super(scope, id); 51 | 52 | console.log(`Hello ${name}`); 53 | } 54 | } 55 | 56 | const stack = new E(undefined, "root", {name: "Elad"}); 57 | ``` 58 | 59 | Note how we can extend the `C`-returned constructor (as seen by `D`), as to define another constructor. 60 | 61 | To define custom props on the resulting constructor, we add a second parameter to the init function: 62 | 63 | ```ts 64 | interface MyProps { 65 | hello: string; 66 | } 67 | 68 | const Stack = C(cdk.Stack, (define, props: MyProps) => { 69 | // ... 70 | }); 71 | 72 | const stack = new Stack(scope, "my-id"); // type-error: expected 3rd argument 73 | const stack = new Stack(scope, "my-id", {hello: "world"}); 74 | ``` 75 | 76 | The constructor will also respect optionality. 77 | 78 | ```diff 79 | interface MyProps { 80 | hello: string; 81 | } 82 | 83 | - const Stack = C(cdk.Stack, (define, props: MyProps) => { 84 | + const Stack = C(cdk.Stack, (define, props?: MyProps) => { 85 | // ... 86 | }); 87 | 88 | - const stack = new Stack(scope, "my-id"); // type-error: expected 3rd argument 89 | + const stack = new Stack(scope, "my-id"); // no longer a type error 90 | const stack = new Stack(scope, "my-id", {hello: "world"}); 91 | ``` 92 | 93 | To correctly handle calls to super, one can supply a third argument to `C`: a mapping function, (in this case, an identity) which accepts the producer function's props and returns the inherited constructor's props. 94 | 95 | ```ts 96 | const Stack = C( 97 | cdk.Stack, 98 | (define, props?: cdk.StackProps) => { 99 | // ... 100 | }, 101 | (props) => props, 102 | ); 103 | ``` 104 | 105 | Within the closure of arg 1, we have access to `define`, a function. We can use this function to instantiate constructs without supplying scope. 106 | 107 | ```ts 108 | import * as cdk from "@aws-cdk/core"; 109 | import * as lambda from "@aws-cdk/aws-lambda"; 110 | import {C} from "concise-constsructs"; 111 | 112 | const Stack = C(cdk.Stack, (define) => { 113 | define`handler`(lambda.Function, { 114 | code: new lambda.InlineCode(`...`), 115 | handler: "handler", 116 | runtime: lambda.Runtime.NODEJS_12_X, 117 | }); 118 | }); 119 | ``` 120 | 121 | The value returned from define is the instance of `lambda.Function`. Let's capture it in a variable, and ensure that it is a member of the resulting construct constructor: 122 | 123 | ```ts 124 | const Stack = C(cdk.Stack, (define) => { 125 | const fn = define`handler`(lambda.Function, { 126 | code: new lambda.InlineCode(`...`), 127 | handler: "handler", 128 | runtime: lambda.Runtime.NODEJS_12_X, 129 | }); 130 | 131 | return {fn}; 132 | }); 133 | ``` 134 | 135 | The resulting constructor will have `fn` as a member of its instances. 136 | 137 | ```ts 138 | type Stack = typeof Stack; 139 | type Instance = InstanceType; 140 | declare const instance: Instance; 141 | instance.fn; // lambda.Function 142 | ``` 143 | 144 | Scope is also accessible on the `define` function (just incase). 145 | 146 | ```ts 147 | C(cdk.Construct, (define) => { 148 | define.scope; // cdk.Construct 149 | }); 150 | ``` 151 | -------------------------------------------------------------------------------- /examples/graphql-api/codegen.yml: -------------------------------------------------------------------------------- 1 | generates: 2 | lambda/generated-types.ts: 3 | schema: schema.gql 4 | overwrite: true 5 | plugins: 6 | - typescript 7 | config: 8 | useIndexSignature: true 9 | -------------------------------------------------------------------------------- /examples/graphql-api/index.ts: -------------------------------------------------------------------------------- 1 | import {C} from "../../src"; 2 | import * as appsync from "@aws-cdk/aws-appsync"; 3 | import * as cdk from "@aws-cdk/core"; 4 | import * as ddb from "@aws-cdk/aws-dynamodb"; 5 | import * as lambda from "@aws-cdk/aws-lambda"; 6 | import path from "path"; 7 | 8 | const code = new lambda.AssetCode(path.resolve(__dirname, "lambda", "dist")); 9 | 10 | const Stack = C(cdk.Stack, (def) => { 11 | const api = def`api`(appsync.GraphqlApi, { 12 | name: "api", 13 | schema: appsync.Schema.fromAsset("schema.gql"), 14 | xrayEnabled: true, 15 | }); 16 | 17 | def`graphqlUrl`(cdk.CfnOutput, {exportName: "graphqlUrl", value: api.graphqlUrl!}); 18 | def`apiKey`(cdk.CfnOutput, {exportName: "apiKey", value: api.apiKey!}); 19 | 20 | const db = def`db`(ddb.Table, { 21 | billingMode: ddb.BillingMode.PAY_PER_REQUEST, 22 | partitionKey: { 23 | name: "id", 24 | type: ddb.AttributeType.STRING, 25 | }, 26 | }); 27 | 28 | [ 29 | {typeName: "Query", fieldName: "note", access: "dynamodb:GetItem"}, 30 | {typeName: "Query", fieldName: "notes", access: "dynamodb:PutItem"}, 31 | {typeName: "Mutation", fieldName: "createNote", access: "dynamodb:Scan"}, 32 | {typeName: "Mutation", fieldName: "deleteNote", access: "dynamodb:DeleteItem"}, 33 | ].forEach(({access, ...props}) => { 34 | const handler = def`${props.fieldName}Handler`(lambda.Function, { 35 | code, 36 | environment: {TABLE_NAME: db.tableName}, 37 | handler: `index.${props.fieldName}Handler`, 38 | runtime: lambda.Runtime.NODEJS_12_X, 39 | }); 40 | 41 | db.grant(handler, access); 42 | 43 | api.addLambdaDataSource(`${props.fieldName}DataSource`, handler).createResolver(props); 44 | }); 45 | }); 46 | 47 | const App = C(cdk.App, (def) => { 48 | def`stack`(Stack); 49 | }); 50 | 51 | new App().synth(); 52 | -------------------------------------------------------------------------------- /examples/graphql-api/lambda/common.ts: -------------------------------------------------------------------------------- 1 | import {DynamoDB} from "aws-sdk"; 2 | 3 | export const db = new DynamoDB.DocumentClient(); 4 | 5 | export const TableName = process.env.TABLE_NAME as string; 6 | -------------------------------------------------------------------------------- /examples/graphql-api/lambda/create-note.ts: -------------------------------------------------------------------------------- 1 | import {AppSyncResolverHandler} from "aws-lambda"; 2 | import {db, TableName} from "./common"; 3 | import * as t from "./generated-types"; 4 | 5 | export const handler: AppSyncResolverHandler = async ({arguments: {in: Item}}) => { 6 | await db.put({TableName, Item}).promise(); 7 | return Item; 8 | }; 9 | -------------------------------------------------------------------------------- /examples/graphql-api/lambda/delete-note.ts: -------------------------------------------------------------------------------- 1 | import {AppSyncResolverHandler} from "aws-lambda"; 2 | import {db, TableName} from "./common"; 3 | import * as t from "./generated-types"; 4 | 5 | export const handler: AppSyncResolverHandler = async ({arguments: {id}}) => { 6 | try { 7 | await db.delete({TableName, Key: {id}}).promise(); 8 | return id; 9 | } catch (e) {} 10 | }; 11 | -------------------------------------------------------------------------------- /examples/graphql-api/lambda/index.ts: -------------------------------------------------------------------------------- 1 | export {handler as noteHandler} from "./note"; 2 | export {handler as notesHandler} from "./notes"; 3 | export {handler as createNoteHandler} from "./create-note"; 4 | export {handler as deleteNoteHandler} from "./delete-note"; 5 | -------------------------------------------------------------------------------- /examples/graphql-api/lambda/note.ts: -------------------------------------------------------------------------------- 1 | import {AppSyncResolverHandler} from "aws-lambda"; 2 | import {db, TableName} from "./common"; 3 | import * as t from "./generated-types"; 4 | 5 | export const handler: AppSyncResolverHandler = async ({arguments: {id}}) => { 6 | try { 7 | const {Item} = await db.get({TableName, Key: {id}}).promise(); 8 | return Item as t.Query["note"]; 9 | } catch (e) {} 10 | }; 11 | -------------------------------------------------------------------------------- /examples/graphql-api/lambda/notes.ts: -------------------------------------------------------------------------------- 1 | import {AppSyncResolverHandler} from "aws-lambda"; 2 | import {db, TableName} from "./common"; 3 | import * as t from "./generated-types"; 4 | 5 | export const handler: AppSyncResolverHandler = async () => { 6 | try { 7 | const {Items} = await db.scan({TableName}).promise(); 8 | return Items as t.Query["notes"]; 9 | } catch (e) { 10 | return []; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /examples/graphql-api/schema.gql: -------------------------------------------------------------------------------- 1 | type Note { 2 | id: ID! 3 | name: String! 4 | completed: Boolean! 5 | } 6 | 7 | type Query { 8 | note(id: String!): Note 9 | notes: [Note!]! 10 | } 11 | 12 | input CreateNoteInput { 13 | id: ID! 14 | name: String! 15 | completed: Boolean! 16 | } 17 | 18 | type Mutation { 19 | createNote(in: CreateNoteInput!): Note 20 | deleteNote(id: String!): String 21 | } 22 | -------------------------------------------------------------------------------- /examples/index.ts: -------------------------------------------------------------------------------- 1 | import {buildSync} from "esbuild"; 2 | import cp from "child_process"; 3 | import del from "del"; 4 | import fs from "fs"; 5 | import path from "path"; 6 | 7 | const command = process.argv.pop(); 8 | if (!command) { 9 | throw new Error("Must specify a CDK command."); 10 | } 11 | 12 | const app = process.argv.pop(); 13 | if (!app) { 14 | throw new Error(`Must specify one of the example directory names.`); 15 | } 16 | 17 | const appPath = path.resolve(__dirname, app); 18 | const execSyncOptions: cp.ExecSyncOptions = {cwd: appPath, stdio: "inherit"}; 19 | 20 | function gqlCodeGen() { 21 | if (fs.existsSync(path.resolve(appPath, "codegen.yml"))) { 22 | cp.execSync("graphql-codegen", execSyncOptions); 23 | } 24 | } 25 | 26 | if (command === "gql-code-gen") { 27 | gqlCodeGen(); 28 | } else { 29 | if ( 30 | ({ 31 | deploy: true, 32 | destroy: true, 33 | diff: true, 34 | synth: true, 35 | } as Record)[command] 36 | ) { 37 | gqlCodeGen(); 38 | 39 | if (fs.existsSync(path.resolve(appPath, "lambda"))) { 40 | del.sync(path.join(appPath, "lambda", "dist")); 41 | const lambdaPath = path.join(appPath, "lambda"); 42 | buildSync({ 43 | minify: true, 44 | entryPoints: [path.join(lambdaPath, "index.ts")], 45 | bundle: true, 46 | external: ["aws-sdk"], 47 | format: "cjs", 48 | outfile: path.join(lambdaPath, "dist", "index.js"), 49 | sourcemap: "inline", 50 | target: "node12.2", 51 | }); 52 | } 53 | } 54 | 55 | cp.execSync(["cdk", command, `--app 'ts-node .'`, `--outputs-file ./outputs.json`].join(" "), execSyncOptions); 56 | } 57 | -------------------------------------------------------------------------------- /examples/rest-api/index.ts: -------------------------------------------------------------------------------- 1 | import {C} from "../../src"; 2 | import * as apigw from "@aws-cdk/aws-apigateway"; 3 | import * as cdk from "@aws-cdk/core"; 4 | import * as lambda from "@aws-cdk/aws-lambda"; 5 | import path from "path"; 6 | 7 | const code = new lambda.AssetCode(path.resolve(__dirname, "lambda", "dist")); 8 | 9 | const Stack = C(cdk.Stack, (def, environment?: Record) => { 10 | const handler = def`handler`(lambda.Function, { 11 | code, 12 | handler: "index.helloConciseConstructsHandler", 13 | runtime: lambda.Runtime.NODEJS_12_X, 14 | environment, 15 | }); 16 | 17 | def`api`(apigw.LambdaRestApi, {handler}); 18 | }); 19 | 20 | const App = C(cdk.App, (def) => { 21 | def`stack`(Stack, {SOME_ENV_VAR: "Lorem ipsum dolor!"}); 22 | }); 23 | 24 | new App().synth(); 25 | -------------------------------------------------------------------------------- /examples/rest-api/lambda/hello-concise-constructs.ts: -------------------------------------------------------------------------------- 1 | import {APIGatewayProxyHandler} from "aws-lambda"; 2 | import aws from "aws-sdk"; 3 | 4 | export const handler: APIGatewayProxyHandler = async (event) => { 5 | console.log("lambda start..."); 6 | console.log(process.env.SOME_ENV_VAR); 7 | console.log("request:", JSON.stringify(event, undefined, 2)); 8 | console.log("We don't end up bundling the `aws-sdk`, few!", aws); 9 | 10 | return { 11 | statusCode: 200, 12 | headers: {"Content-Type": "text/plain"}, 13 | body: `Hello concise constructs! The current path is '${event.path}'\n`, 14 | }; 15 | }; 16 | -------------------------------------------------------------------------------- /examples/rest-api/lambda/index.ts: -------------------------------------------------------------------------------- 1 | export {handler as helloConciseConstructsHandler} from "./hello-concise-constructs"; 2 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/package", 3 | "name": "concise-constructs", 4 | "version": "0.0.2", 5 | "license": "Apache-2.0", 6 | "main": "cjs/index.js", 7 | "types": "cjs/index.d.ts", 8 | "sideEffects": false, 9 | "private": false, 10 | "publishConfig": { 11 | "access": "public" 12 | }, 13 | "files": [ 14 | "cjs" 15 | ], 16 | "description": "A functional-feeling DX for the AWS CDK and other construct libraries", 17 | "repository": "github:awslabs/concise-constructs", 18 | "keywords": [ 19 | "concise", 20 | "constructs", 21 | "aws", 22 | "cdk", 23 | "cdk8s", 24 | "terraform", 25 | "cloud", 26 | "development", 27 | "kit" 28 | ], 29 | "dependencies": { 30 | "@aws-cdk/core": "^1.86.0", 31 | "constructs": "^3.2.116" 32 | }, 33 | "devDependencies": { 34 | "@aws-cdk/aws-apigateway": "^1.86.0", 35 | "@aws-cdk/aws-appsync": "^1.86.0", 36 | "@aws-cdk/aws-lambda": "^1.86.0", 37 | "@aws-cdk/aws-s3": "^1.86.0", 38 | "@graphql-codegen/cli": "^1.20.1", 39 | "@graphql-codegen/typescript": "^1.20.2", 40 | "@types/aws-lambda": "^8.10.71", 41 | "@types/jest": "^26.0.20", 42 | "@types/node": "^14.14.22", 43 | "aws-cdk": "^1.86.0", 44 | "aws-sdk": "^2.831.0", 45 | "cdk8s": "^1.0.0-beta.6", 46 | "conditional-type-checks": "^1.0.5", 47 | "del": "^6.0.0", 48 | "esbuild": "^0.8.36", 49 | "graphql": "^15.5.0", 50 | "husky": "^4.3.8", 51 | "javascript-stringify": "^2.0.1", 52 | "jest": "^26.6.3", 53 | "prettier": "^2.2.1", 54 | "standard-version": "^9.1.0", 55 | "ts-jest": "^26.4.4", 56 | "ts-node": "^9.1.1", 57 | "typescript": "^4.1.3" 58 | }, 59 | "jest": { 60 | "cache": false, 61 | "globals": { 62 | "ts-jest": { 63 | "diagnostics": true, 64 | "tsconfig": "tsconfig.json" 65 | } 66 | }, 67 | "preset": "ts-jest", 68 | "testEnvironment": "node", 69 | "testMatch": [ 70 | "**/*.test.ts", 71 | "**/tests/**/*" 72 | ], 73 | "testPathIgnorePatterns": [ 74 | "node_modules" 75 | ], 76 | "verbose": false 77 | }, 78 | "husky": { 79 | "hooks": { 80 | "pre-commit": "npm run format", 81 | "pre-push": "npm run test --bail && npm run build" 82 | } 83 | }, 84 | "scripts": { 85 | "clean": "rm -rf cjs examples/*/{cdk.out,outputs.json,lambda/{dist,generated-types.ts}} node_modules", 86 | "format": "prettier --write . --ignore=node_modules --loglevel=error", 87 | "test": "jest", 88 | "build": "tsc -P tsconfig.build.json", 89 | "watch": "tsc -P tsconfig.build.json --watch", 90 | "release": "standard-version", 91 | "release-next": "npm run release -- --prerelease next", 92 | "example": "ts-node examples" 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/ctor.test.ts: -------------------------------------------------------------------------------- 1 | import {assert, IsExact} from "conditional-type-checks"; 2 | import {Ctor} from "./ctor"; 3 | import type * as cdk from "@aws-cdk/core"; 4 | import type * as cdk8s from "cdk8s"; 5 | 6 | describe("Ctor", () => { 7 | it("IsRoot Type", () => { 8 | expect.assertions(0); 9 | assert, true>>(true); 10 | assert, false>>(true); 11 | assert, false>>(true); 12 | assert, true>>(true); 13 | assert, false>>(true); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /src/ctor.ts: -------------------------------------------------------------------------------- 1 | import {Construct} from "constructs"; 2 | import type * as cdk from "@aws-cdk/core"; 3 | 4 | export namespace Ctor { 5 | type Self = Ctor; 6 | 7 | export type Make = new (...args: Args) => Instance; 8 | 9 | export namespace Root { 10 | export type Make = Ctor.Make<[props: Props], Instance>; 11 | 12 | export type Props = ConstructorParameters[0]; 13 | } 14 | export type Root = Root.Make; 15 | 16 | export namespace Child { 17 | export type Make = Ctor.Make< 18 | [scope: Scope, id: string, props: Props], 19 | Instance 20 | >; 21 | 22 | export type Props = ConstructorParameters[2]; 23 | } 24 | export type Child = Child.Make; 25 | 26 | export type IsRoot = Ctor extends Child 27 | ? ConstructorParameters extends [] 28 | ? true 29 | : false 30 | : Ctor extends Root 31 | ? true 32 | : InstanceType extends cdk.App 33 | ? true 34 | : false; 35 | 36 | export type Props = IsRoot extends true ? Root.Props : Child.Props; 37 | } 38 | 39 | export type Ctor = Ctor.Make; 40 | -------------------------------------------------------------------------------- /src/define.test.ts: -------------------------------------------------------------------------------- 1 | import {assert, IsExact} from "conditional-type-checks"; 2 | import {Define} from "./define"; 3 | import * as cdk from "@aws-cdk/core"; 4 | import * as lambda from "@aws-cdk/aws-lambda"; 5 | 6 | const stackScope = new cdk.Stack(); 7 | const define = Define(stackScope); 8 | const handler = define`handler`(lambda.Function, { 9 | code: new lambda.InlineCode("..."), 10 | handler: "handler", 11 | runtime: lambda.Runtime.NODEJS_12_X, 12 | }); 13 | 14 | describe("Define", () => { 15 | it("Types", () => { 16 | expect.assertions(1); 17 | assert>>(true); 18 | assert>(true); 19 | expect(define.scope instanceof cdk.Stack).toBeTruthy(); 20 | }); 21 | 22 | it("Mounts Child Construct", () => { 23 | expect.assertions(1); 24 | expect(stackScope.node.children[0]).toBe(handler); 25 | }); 26 | }); 27 | -------------------------------------------------------------------------------- /src/define.ts: -------------------------------------------------------------------------------- 1 | import {Construct} from "constructs"; 2 | import {Ctor} from "./ctor"; 3 | import * as u from "./util"; 4 | 5 | /** 6 | * A callable object, used to define construct instances within the context of `C` scope. 7 | */ 8 | export interface Define { 9 | (quasis: TemplateStringsArray, ...rest: string[]): >( 10 | Ctor: Ctor, 11 | ...rest: u.InRest.Props, false> 12 | ) => InstanceType; 13 | /** 14 | * The parent `Construct` instance. 15 | */ 16 | scope: Scope; 17 | } 18 | 19 | export function Define(scope: Scope): Define { 20 | const define: Define = (quasis, ...rest) => { 21 | const id = u.recombineTaggedTemplateArgs(quasis, ...rest); 22 | 23 | return (Ctor, ...[props]) => { 24 | return new Ctor(scope, id, props) as any; 25 | }; 26 | }; 27 | define.scope = scope; 28 | return define; 29 | } 30 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import {Ctor} from "./ctor"; 2 | import {Define} from "./define"; 3 | import * as u from "./util"; 4 | 5 | /** 6 | * @param BaseCtor The base constructor from which your construct's constructor should extend. 7 | * @param produce A function which utilizes its exposed `Define` to instantiate constructs and return to-be 8 | * members for the "produced" constructor. 9 | * @param basePropsOrMapper In cases where the base construct accepts props, this argument can be a mapping 10 | * function from `Parameters[1]` to the base constructor's props. This argument cannot be supplied 11 | * should the base constructor not accept props. 12 | */ 13 | export function C< 14 | BaseCtor extends Ctor, 15 | BaseInstance extends InstanceType, 16 | Produce extends (define: Define, props: any) => (Partial & u.AnyRec) | void, 17 | Props extends Parameters[1], 18 | AdditionalMembers extends ReturnType 19 | >( 20 | BaseCtor: BaseCtor, 21 | produce: Produce, 22 | ...[basePropsOrMapper]: u.InRest.BasePropsOrMapper> 23 | ): Ctor.Make< 24 | Ctor.IsRoot extends true 25 | ? u.InRest.Props 26 | : [scope: ConstructorParameters[0], id: string, ...rest: u.InRest.Props], 27 | AdditionalMembers extends void ? BaseInstance : BaseInstance & AdditionalMembers 28 | > { 29 | return class extends BaseCtor { 30 | constructor(...[parentOrProps, idOrUndef, propsOrUndef]: any[]) { 31 | const props = propsOrUndef || parentOrProps; 32 | const propsForSuper = typeof basePropsOrMapper === "function" ? (basePropsOrMapper as any)(props) : props; 33 | super(...(idOrUndef ? [parentOrProps, idOrUndef, propsForSuper] : [propsForSuper])); 34 | const define = Define(this as any); 35 | const produced = produce(define, props); 36 | produced && Object.assign(this, produced); 37 | } 38 | } as any; 39 | } 40 | -------------------------------------------------------------------------------- /src/tests/basic.ts: -------------------------------------------------------------------------------- 1 | import {C} from ".."; 2 | import * as cdk from "@aws-cdk/core"; 3 | import * as s3 from "@aws-cdk/aws-s3"; 4 | 5 | describe("Basic", () => { 6 | it("S3", () => { 7 | expect.assertions(1); 8 | 9 | class ClassicalS3Stack extends cdk.Stack { 10 | constructor(app: cdk.App) { 11 | super(app, "stack-id"); 12 | 13 | new s3.Bucket(this, "bucket-id", { 14 | encryption: s3.BucketEncryption.KMS, 15 | }); 16 | } 17 | } 18 | const classicalApp = new cdk.App(); 19 | new ClassicalS3Stack(classicalApp); 20 | 21 | const ConciseS3Stack = C(cdk.Stack, (def) => { 22 | def`bucket-id`(s3.Bucket, { 23 | encryption: s3.BucketEncryption.KMS, 24 | }); 25 | }); 26 | const ConciseApp = C(cdk.App, (def) => { 27 | def`stack-id`(ConciseS3Stack); 28 | }); 29 | const conciseAppStacks = new ConciseApp().synth().stacks; 30 | 31 | classicalApp.synth().stacks.forEach((e, i) => { 32 | expect(e?.template).toStrictEqual(conciseAppStacks[i]?.template); 33 | }); 34 | }); 35 | }); 36 | -------------------------------------------------------------------------------- /src/tests/overwrites.ts: -------------------------------------------------------------------------------- 1 | import {C} from ".."; 2 | import * as cdk from "@aws-cdk/core"; 3 | 4 | describe("Overwrites", () => { 5 | it("Conflicting type fails", () => { 6 | expect.assertions(0); 7 | 8 | // @ts-expect-error 9 | C(cdk.Stack, () => { 10 | return { 11 | environment: 123, 12 | }; 13 | }); 14 | }); 15 | 16 | it("Compatible type succeeds", () => { 17 | expect.assertions(0); 18 | 19 | C(cdk.Stack, () => { 20 | return { 21 | environment: "hello", 22 | }; 23 | }); 24 | }); 25 | 26 | it("Narrowing the chain", () => { 27 | expect.assertions(0); 28 | 29 | const StackA = C(cdk.Stack, () => { 30 | return { 31 | environment: "literal" as "literal" | undefined, 32 | }; 33 | }); 34 | 35 | // @ts-expect-error 36 | C(StackA, () => { 37 | return { 38 | environment: "something-else", 39 | }; 40 | }); 41 | 42 | const StackB = C(StackA, () => { 43 | return { 44 | environment: "literal", 45 | }; 46 | }); 47 | 48 | // @ts-expect-error 49 | C(StackB, () => { 50 | return { 51 | environment: "yo", 52 | }; 53 | }); 54 | 55 | C(StackA, () => { 56 | return { 57 | environment: undefined, 58 | }; 59 | }); 60 | }); 61 | }); 62 | -------------------------------------------------------------------------------- /src/tests/types.ts: -------------------------------------------------------------------------------- 1 | import {assert, IsExact} from "conditional-type-checks"; 2 | import {C} from ".."; 3 | import {Construct} from "constructs"; 4 | 5 | namespace fixtures { 6 | export class Root extends Construct { 7 | constructor() { 8 | super((undefined as unknown) as Construct, "root"); 9 | } 10 | } 11 | 12 | export namespace Root { 13 | export class WithProps extends Root { 14 | constructor(public props: string) { 15 | super(); 16 | } 17 | } 18 | 19 | export class WithOptionalProps extends Root { 20 | constructor(public props?: string) { 21 | super(); 22 | } 23 | } 24 | 25 | export class WithPropsOrUndef extends Root { 26 | constructor(public props: string | undefined) { 27 | super(); 28 | } 29 | } 30 | } 31 | 32 | export class Child extends Construct { 33 | constructor(scope: Construct, id: string) { 34 | super(scope, id); 35 | } 36 | } 37 | 38 | export namespace Child { 39 | export class WithProps extends Child { 40 | constructor(scope: Construct, id: string, public props: string) { 41 | super(scope, id); 42 | } 43 | } 44 | 45 | export class WithOptionalProps extends Child { 46 | constructor(scope: Construct, id: string, public props?: string) { 47 | super(scope, id); 48 | } 49 | } 50 | 51 | export class WithPropsOrUndef extends Child { 52 | constructor(scope: Construct, id: string, public props: string | undefined) { 53 | super(scope, id); 54 | } 55 | } 56 | } 57 | } 58 | 59 | interface Props { 60 | a: string; 61 | } 62 | const props: Props = {a: "a"}; 63 | const scope = (undefined as unknown) as Construct; 64 | 65 | describe("Produced Types", () => { 66 | it("Roots", () => { 67 | expect.assertions(0); 68 | 69 | (() => { 70 | const Ctor0 = C(fixtures.Root, () => {}); 71 | const instance0 = new Ctor0(); 72 | assert>(true); 73 | // @ts-expect-error 74 | C(fixtures.Root, () => {}, ""); 75 | C( 76 | fixtures.Root, 77 | () => {}, 78 | // @ts-expect-error 79 | () => undefined as any, 80 | ); 81 | 82 | const Ctor1 = C(fixtures.Root, (_def, _props: Props) => {}); 83 | const instance1 = new Ctor1(props); 84 | assert>(true); 85 | // @ts-expect-error 86 | C(fixtures.Root, (_def, _props: Props) => {}, ""); 87 | C( 88 | fixtures.Root, 89 | (_def, _props: Props) => {}, 90 | // @ts-expect-error 91 | () => undefined as any, 92 | ); 93 | 94 | const Ctor2 = C(fixtures.Root, (_def, _props?: Props) => {}); 95 | const instance2_0 = new Ctor2(props); 96 | assert>(true); 97 | const instance2_1 = new Ctor2(); 98 | assert>(true); 99 | // @ts-expect-error 100 | C(fixtures.Root, (_def, _props?: Props) => {}, ""); 101 | C( 102 | fixtures.Root, 103 | (_def, _props?: Props) => {}, 104 | // @ts-expect-error 105 | () => undefined as any, 106 | ); 107 | })(); 108 | 109 | (() => { 110 | const Ctor0 = C(fixtures.Root.WithProps, () => {}, ""); 111 | const instance0 = new Ctor0(); 112 | assert>(true); 113 | // @ts-expect-error 114 | C(fixtures.Root.WithProps, () => {}); 115 | // @ts-expect-error 116 | C(fixtures.Root.WithProps, () => {}, true); 117 | C( 118 | fixtures.Root.WithProps, 119 | () => {}, 120 | // @ts-expect-error 121 | () => true, 122 | ); 123 | 124 | const Ctor1 = C(fixtures.Root.WithProps, (_def, _props: Props) => {}, ""); 125 | const instance1 = new Ctor1(props); 126 | assert>(true); 127 | // @ts-expect-error 128 | C(fixtures.Root.WithProps, (_def, _props: Props) => {}); 129 | // @ts-expect-error 130 | C(fixtures.Root.WithProps, (_def, _props: Props) => {}, true); 131 | C( 132 | fixtures.Root.WithProps, 133 | (_def, _props: Props) => {}, 134 | // @ts-expect-error 135 | (_props) => true, 136 | ); 137 | 138 | const Ctor2 = C(fixtures.Root.WithProps, (_def, _props?: Props) => {}, ""); 139 | const instance2_0 = new Ctor2(props); 140 | assert>(true); 141 | const instance2_1 = new Ctor2(); 142 | assert>(true); 143 | // @ts-expect-error 144 | C(fixtures.Root.WithProps, (_def, _props?: Props) => {}); 145 | // @ts-expect-error 146 | C(fixtures.Root.WithProps, (_def, _props?: Props) => {}, true); 147 | C( 148 | fixtures.Root.WithProps, 149 | (_def, _props?: Props) => {}, 150 | // @ts-expect-error 151 | () => true, 152 | ); 153 | })(); 154 | 155 | (() => { 156 | const Ctor0 = C(fixtures.Root.WithOptionalProps, () => {}); 157 | const instance0 = new Ctor0(); 158 | assert>(true); 159 | // @ts-expect-error 160 | C(fixtures.Root.WithOptionalProps, () => {}, true); 161 | C( 162 | fixtures.Root.WithOptionalProps, 163 | () => {}, 164 | // @ts-expect-error 165 | () => true, 166 | ); 167 | 168 | const Ctor1 = C(fixtures.Root.WithOptionalProps, (_def, _props: Props) => {}); 169 | const instance1 = new Ctor1(props); 170 | assert>(true); 171 | // @ts-expect-error 172 | C(fixtures.Root.WithOptionalProps, (_def, _props: Props) => {}, true); 173 | C( 174 | fixtures.Root.WithOptionalProps, 175 | (_def, _props: Props) => {}, 176 | // @ts-expect-error 177 | () => true, 178 | ); 179 | 180 | const Ctor2 = C(fixtures.Root.WithOptionalProps, (_def, _props?: Props) => {}); 181 | const instance2_0 = new Ctor2(props); 182 | assert>(true); 183 | const instance2_1 = new Ctor2(); 184 | assert>(true); 185 | // @ts-expect-error 186 | C(fixtures.Root.WithOptionalProps, (_def, _props?: Props) => {}, true); 187 | C( 188 | fixtures.Root.WithOptionalProps, 189 | (_def, _props?: Props) => {}, 190 | // @ts-expect-error 191 | () => true, 192 | ); 193 | })(); 194 | 195 | (() => { 196 | const Ctor0 = C(fixtures.Root.WithOptionalProps, () => {}, ""); 197 | const instance0 = new Ctor0(); 198 | assert>(true); 199 | C(fixtures.Root.WithOptionalProps, () => {}); 200 | // @ts-expect-error 201 | C(fixtures.Root.WithOptionalProps, () => {}, true); 202 | C( 203 | fixtures.Root.WithOptionalProps, 204 | () => {}, 205 | // @ts-expect-error 206 | () => true, 207 | ); 208 | 209 | const Ctor1 = C(fixtures.Root.WithOptionalProps, (_def, _props: Props) => {}, ""); 210 | const instance1 = new Ctor1(props); 211 | assert>(true); 212 | C(fixtures.Root.WithOptionalProps, (_def, _props: Props) => {}); 213 | // @ts-expect-error 214 | C(fixtures.Root.WithOptionalProps, (_def, _props: Props) => {}, true); 215 | C( 216 | fixtures.Root.WithOptionalProps, 217 | (_def, _props: Props) => {}, 218 | // @ts-expect-error 219 | () => true, 220 | ); 221 | 222 | const Ctor2 = C(fixtures.Root.WithOptionalProps, (_def, _props?: Props) => {}, ""); 223 | const instance2_0 = new Ctor2(props); 224 | assert>(true); 225 | const instance2_1 = new Ctor2(); 226 | assert>(true); 227 | C(fixtures.Root.WithOptionalProps, (_def, _props?: Props) => {}); 228 | // @ts-ignore 229 | C(fixtures.Root.WithOptionalProps, (_def, _props?: Props) => {}, true); 230 | C( 231 | fixtures.Root.WithOptionalProps, 232 | (_def, _props?: Props) => {}, 233 | // @ts-ignore 234 | () => true, 235 | ); 236 | })(); 237 | 238 | (() => { 239 | const Ctor0 = C(fixtures.Root.WithPropsOrUndef, () => {}, ""); 240 | const instance0 = new Ctor0(); 241 | assert>(true); 242 | C(fixtures.Root.WithPropsOrUndef, () => {}); 243 | // @ts-expect-error 244 | C(fixtures.Root.WithPropsOrUndef, () => {}, true); 245 | C( 246 | fixtures.Root.WithPropsOrUndef, 247 | () => {}, 248 | // @ts-expect-error 249 | () => true, 250 | ); 251 | 252 | const Ctor1 = C(fixtures.Root.WithPropsOrUndef, (_def, _props: Props) => {}, ""); 253 | const instance1 = new Ctor1(props); 254 | assert>(true); 255 | C(fixtures.Root.WithPropsOrUndef, (_def, _props: Props) => {}); 256 | // @ts-expect-error 257 | C(fixtures.Root.WithPropsOrUndef, (_def, _props: Props) => {}, true); 258 | C( 259 | fixtures.Root.WithPropsOrUndef, 260 | (_def, _props: Props) => {}, 261 | // @ts-expect-error 262 | () => true, 263 | ); 264 | 265 | const Ctor2 = C(fixtures.Root.WithPropsOrUndef, (_def, _props?: Props) => {}, ""); 266 | const instance2_0 = new Ctor2(props); 267 | assert>(true); 268 | const instance2_1 = new Ctor2(); 269 | assert>(true); 270 | C(fixtures.Root.WithPropsOrUndef, (_def, _props?: Props) => {}); 271 | // @ts-expect-error 272 | C(fixtures.Root.WithPropsOrUndef, (_def, _props?: Props) => {}, true); 273 | C( 274 | fixtures.Root.WithPropsOrUndef, 275 | (_def, _props?: Props) => {}, 276 | // @ts-expect-error 277 | () => true, 278 | ); 279 | })(); 280 | 281 | (() => { 282 | const Ctor0 = C(fixtures.Root.WithPropsOrUndef, () => {}, ""); 283 | const instance0 = new Ctor0(); 284 | assert>(true); 285 | C(fixtures.Root.WithPropsOrUndef, () => {}); 286 | // @ts-expect-error 287 | C(fixtures.Root.WithPropsOrUndef, () => {}, true); 288 | C( 289 | fixtures.Root.WithPropsOrUndef, 290 | () => {}, 291 | // @ts-expect-error 292 | () => true, 293 | ); 294 | 295 | const Ctor1 = C(fixtures.Root.WithPropsOrUndef, (_def, _props: Props) => {}, ""); 296 | const instance1 = new Ctor1(props); 297 | assert>(true); 298 | C(fixtures.Root.WithPropsOrUndef, (_def, _props: Props) => {}); 299 | // @ts-expect-error 300 | C(fixtures.Root.WithPropsOrUndef, (_def, _props: Props) => {}, true); 301 | C( 302 | fixtures.Root.WithPropsOrUndef, 303 | (_def, _props: Props) => {}, 304 | // @ts-expect-error 305 | () => true, 306 | ); 307 | 308 | const Ctor2 = C(fixtures.Root.WithPropsOrUndef, (_def, _props?: Props) => {}, ""); 309 | const instance2_0 = new Ctor2(props); 310 | assert>(true); 311 | const instance2_1 = new Ctor2(); 312 | assert>(true); 313 | C(fixtures.Root.WithPropsOrUndef, (_def, _props?: Props) => {}); 314 | // @ts-expect-error 315 | C(fixtures.Root.WithPropsOrUndef, (_def, _props?: Props) => {}, true); 316 | C( 317 | fixtures.Root.WithPropsOrUndef, 318 | (_def, _props?: Props) => {}, 319 | // @ts-expect-error 320 | () => true, 321 | ); 322 | })(); 323 | }); 324 | 325 | it("Children", () => { 326 | (() => { 327 | const Ctor0 = C(fixtures.Child, () => {}); 328 | const instance0 = new Ctor0(scope, "a"); 329 | assert>(true); 330 | // @ts-expect-error 331 | C(fixtures.Child, () => {}, ""); 332 | 333 | const Ctor1 = C(fixtures.Child, (_def, _props: Props) => {}); 334 | const instance1 = new Ctor1(scope, "b", props); 335 | assert>(true); 336 | // @ts-expect-error 337 | C(fixtures.Child, (_def, _props: Props) => {}, ""); 338 | 339 | const Ctor2 = C(fixtures.Child, (_def, _props?: Props) => {}); 340 | const instance2_0 = new Ctor2(scope, "c", props); 341 | assert>(true); 342 | const instance2_1 = new Ctor2(scope, "d"); 343 | assert>(true); 344 | // @ts-expect-error 345 | C(fixtures.Child, (_def, _props?: Props) => {}, ""); 346 | })(); 347 | 348 | (() => { 349 | const Ctor0 = C(fixtures.Child.WithProps, () => {}, ""); 350 | const instance0 = new Ctor0(scope, "e"); 351 | assert>(true); 352 | // @ts-expect-error 353 | C(fixtures.Child.WithProps, () => {}); 354 | // @ts-expect-error 355 | C(fixtures.Child.WithProps, () => {}, true); 356 | C( 357 | fixtures.Child.WithProps, 358 | () => {}, 359 | // @ts-expect-error 360 | () => true, 361 | ); 362 | 363 | const Ctor1 = C(fixtures.Child.WithProps, (_def, _props: Props) => {}, ""); 364 | const instance1 = new Ctor1(scope, "f", props); 365 | assert>(true); 366 | // @ts-expect-error 367 | C(fixtures.Child.WithProps, (_def, _props: Props) => {}); 368 | // @ts-expect-error 369 | C(fixtures.Child.WithProps, (_def, _props: Props) => {}, true); 370 | C( 371 | fixtures.Child.WithProps, 372 | (_def, _props: Props) => {}, 373 | // @ts-expect-error 374 | () => true, 375 | ); 376 | 377 | const Ctor2 = C(fixtures.Child.WithProps, (_def, _props?: Props) => {}, ""); 378 | const instance2_0 = new Ctor2(scope, "g", props); 379 | assert>(true); 380 | const instance2_1 = new Ctor2(scope, "h"); 381 | assert>(true); 382 | // @ts-expect-error 383 | C(fixtures.Child.WithProps, (_def, _props?: Props) => {}); 384 | // @ts-expect-error 385 | C(fixtures.Child.WithProps, (_def, _props?: Props) => {}, true); 386 | C( 387 | fixtures.Child.WithProps, 388 | (_def, _props?: Props) => {}, 389 | // @ts-expect-error 390 | () => true, 391 | ); 392 | })(); 393 | 394 | (() => { 395 | const Ctor0 = C(fixtures.Child.WithOptionalProps, () => {}, ""); 396 | const instance0 = new Ctor0(scope, "i"); 397 | assert>(true); 398 | C(fixtures.Child.WithOptionalProps, () => {}); 399 | // @ts-expect-error 400 | C(fixtures.Child.WithOptionalProps, () => {}, true); 401 | C( 402 | fixtures.Child.WithOptionalProps, 403 | () => {}, 404 | // @ts-expect-error 405 | () => true, 406 | ); 407 | 408 | const Ctor1 = C(fixtures.Child.WithOptionalProps, (_def, _props: Props) => {}); 409 | const instance1 = new Ctor1(scope, "j", props); 410 | assert>(true); 411 | C(fixtures.Child.WithOptionalProps, (_def, _props: Props) => {}, ""); 412 | // @ts-expect-error 413 | C(fixtures.Child.WithOptionalProps, (_def, _props: Props) => {}, true); 414 | C( 415 | fixtures.Child.WithOptionalProps, 416 | (_def, _props: Props) => {}, 417 | // @ts-expect-error 418 | () => true, 419 | ); 420 | 421 | const Ctor2 = C(fixtures.Child.WithOptionalProps, (_def, _props?: Props) => {}, ""); 422 | const instance2_0 = new Ctor2(scope, "k", props); 423 | assert>(true); 424 | const instance2_1 = new Ctor2(scope, "l"); 425 | assert>(true); 426 | C(fixtures.Child.WithOptionalProps, (_def, _props?: Props) => {}); 427 | // @ts-expect-error 428 | C(fixtures.Child.WithOptionalProps, (_def, _props?: Props) => {}, true); 429 | C( 430 | fixtures.Child.WithOptionalProps, 431 | (_def, _props?: Props) => {}, 432 | // @ts-expect-error 433 | () => true, 434 | ); 435 | })(); 436 | 437 | (() => { 438 | const Ctor0 = C(fixtures.Child.WithOptionalProps, () => {}, ""); 439 | const instance0 = new Ctor0(scope, "m"); 440 | assert>(true); 441 | // @ts-expect-error 442 | C(fixtures.Child.WithOptionalProps, () => {}, true); 443 | C( 444 | fixtures.Child.WithOptionalProps, 445 | () => {}, 446 | // @ts-expect-error 447 | () => true, 448 | ); 449 | 450 | const Ctor1 = C(fixtures.Child.WithOptionalProps, (_def, _props: Props) => {}, ""); 451 | const instance1 = new Ctor1(scope, "n", props); 452 | assert>(true); 453 | C(fixtures.Child.WithOptionalProps, (_def, _props: Props) => {}); 454 | // @ts-expect-error 455 | C(fixtures.Child.WithOptionalProps, (_def, _props: Props) => {}, true); 456 | C( 457 | fixtures.Child.WithOptionalProps, 458 | (_def, _props: Props) => {}, 459 | // @ts-expect-error 460 | () => true, 461 | ); 462 | 463 | const Ctor2 = C(fixtures.Child.WithOptionalProps, (_def, _props?: Props) => {}, ""); 464 | const instance2_0 = new Ctor2(scope, "o", props); 465 | assert>(true); 466 | const instance2_1 = new Ctor2(scope, "p"); 467 | assert>(true); 468 | // @ts-expect-error 469 | C(fixtures.Child.WithOptionalProps, (_def, _props?: Props) => {}, true); 470 | C( 471 | fixtures.Child.WithOptionalProps, 472 | (_def, _props?: Props) => {}, 473 | // @ts-expect-error 474 | () => true, 475 | ); 476 | })(); 477 | 478 | (() => { 479 | const Ctor0 = C(fixtures.Child.WithPropsOrUndef, () => {}, ""); 480 | const instance0 = new Ctor0(scope, "q"); 481 | assert>(true); 482 | C(fixtures.Child.WithPropsOrUndef, () => {}); 483 | // @ts-expect-error 484 | C(fixtures.Child.WithPropsOrUndef, () => {}, true); 485 | C( 486 | fixtures.Child.WithPropsOrUndef, 487 | () => {}, 488 | // @ts-expect-error 489 | () => true, 490 | ); 491 | 492 | const Ctor1 = C(fixtures.Child.WithPropsOrUndef, (_def, _props: Props) => {}, ""); 493 | const instance1 = new Ctor1(scope, "r", props); 494 | assert>(true); 495 | C(fixtures.Child.WithPropsOrUndef, (_def, _props: Props) => {}); 496 | // @ts-expect-error 497 | C(fixtures.Child.WithPropsOrUndef, (_def, _props: Props) => {}, true); 498 | C( 499 | fixtures.Child.WithPropsOrUndef, 500 | (_def, _props: Props) => {}, 501 | // @ts-expect-error 502 | () => true, 503 | ); 504 | 505 | const Ctor2 = C(fixtures.Child.WithPropsOrUndef, (_def, _props?: Props) => {}, ""); 506 | const instance2_0 = new Ctor2(scope, "s", props); 507 | assert>(true); 508 | const instance2_1 = new Ctor2(scope, "t"); 509 | assert>(true); 510 | C(fixtures.Child.WithPropsOrUndef, (_def, _props?: Props) => {}); 511 | // @ts-expect-error 512 | C(fixtures.Child.WithPropsOrUndef, (_def, _props?: Props) => {}, true); 513 | C( 514 | fixtures.Child.WithPropsOrUndef, 515 | (_def, _props?: Props) => {}, 516 | // @ts-expect-error 517 | () => true, 518 | ); 519 | })(); 520 | 521 | (() => { 522 | const Ctor0 = C(fixtures.Child.WithPropsOrUndef, () => {}, "u"); 523 | const instance0 = new Ctor0(scope, "v"); 524 | assert>(true); 525 | C(fixtures.Child.WithPropsOrUndef, () => {}); 526 | // @ts-expect-error 527 | C(fixtures.Child.WithPropsOrUndef, () => {}, true); 528 | C( 529 | fixtures.Child.WithPropsOrUndef, 530 | () => {}, 531 | // @ts-expect-error 532 | () => true, 533 | ); 534 | 535 | const Ctor1 = C(fixtures.Child.WithPropsOrUndef, (_def, _props: Props) => {}, ""); 536 | const instance1 = new Ctor1(scope, "w", props); 537 | assert>(true); 538 | C(fixtures.Child.WithPropsOrUndef, (_def, _props: Props) => {}); 539 | // @ts-expect-error 540 | C(fixtures.Child.WithPropsOrUndef, (_def, _props: Props) => {}, true); 541 | C( 542 | fixtures.Child.WithPropsOrUndef, 543 | (_def, _props: Props) => {}, 544 | // @ts-expect-error 545 | () => true, 546 | ); 547 | 548 | const Ctor2 = C(fixtures.Child.WithPropsOrUndef, (_def, _props?: Props) => {}, ""); 549 | const instance2_0 = new Ctor2(scope, "x", props); 550 | assert>(true); 551 | const instance2_1 = new Ctor2(scope, "y"); 552 | assert>(true); 553 | C(fixtures.Child.WithPropsOrUndef, (_def, _props?: Props) => {}); 554 | // @ts-expect-error 555 | C(fixtures.Child.WithPropsOrUndef, (_def, _props?: Props) => {}, true); 556 | C( 557 | fixtures.Child.WithPropsOrUndef, 558 | (_def, _props?: Props) => {}, 559 | // @ts-expect-error 560 | () => true, 561 | ); 562 | })(); 563 | }); 564 | }); 565 | -------------------------------------------------------------------------------- /src/util/in-rest.test.ts: -------------------------------------------------------------------------------- 1 | import {assert, IsExact} from "conditional-type-checks"; 2 | import {InRest} from "./in-rest"; 3 | 4 | describe("InRest", () => { 5 | it("Props", () => { 6 | expect.assertions(0); 7 | assert, [props: string]>>(true); 8 | assert, [] | [props: undefined] | [props: string]>>(true); 9 | assert, [] | [props: string]>>(true); 10 | assert, [] | [props: undefined]>>(true); 11 | assert, []>>(true); 12 | }); 13 | 14 | it("BasePropsOrMapper", () => { 15 | expect.assertions(0); 16 | assert, []>>(true); 17 | assert< 18 | IsExact< 19 | InRest.BasePropsOrMapper<{b: number}, undefined | {a: string}>, 20 | | [] 21 | | [ 22 | mapToBase: (props: { 23 | b: number; 24 | }) => { 25 | a: string; 26 | }, 27 | ] 28 | | [ 29 | baseProps: { 30 | a: string; 31 | }, 32 | ] 33 | > 34 | >(true); 35 | assert< 36 | IsExact< 37 | InRest.BasePropsOrMapper<{b: number}, {a: string}>, 38 | | [ 39 | mapToBase: (props: { 40 | b: number; 41 | }) => { 42 | a: string; 43 | }, 44 | ] 45 | | [ 46 | baseProps: { 47 | a: string; 48 | }, 49 | ] 50 | > 51 | >(true); 52 | assert< 53 | IsExact< 54 | InRest.BasePropsOrMapper<{b: number} | undefined, {a: string} | undefined>, 55 | | [] 56 | | [ 57 | mapToBase: ( 58 | ...rest: 59 | | [] 60 | | [ 61 | props: { 62 | b: number; 63 | }, 64 | ] 65 | ) => { 66 | a: string; 67 | }, 68 | ] 69 | | [ 70 | baseProps: { 71 | a: string; 72 | }, 73 | ] 74 | > 75 | >(true); 76 | assert< 77 | IsExact< 78 | InRest.BasePropsOrMapper, 79 | | [] 80 | | [ 81 | mapToBase: () => { 82 | a: string; 83 | }, 84 | ] 85 | | [ 86 | baseProps: { 87 | a: string; 88 | }, 89 | ] 90 | > 91 | >(true); 92 | }); 93 | }); 94 | -------------------------------------------------------------------------------- /src/util/in-rest.ts: -------------------------------------------------------------------------------- 1 | import {AnyRec} from "./molecules"; 2 | 3 | export namespace InRest { 4 | export type Props = Props extends undefined 5 | ? [] | (EmptyIfUndef extends true ? never : [props: undefined]) 6 | : undefined extends Props 7 | ? [props?: Props] 8 | : [props: Props]; 9 | 10 | export type BasePropsOrMapper

= B extends undefined 11 | ? [] 12 | : undefined extends B 13 | ? P extends undefined 14 | ? [baseProps?: B] 15 | : [mapToBase?: (...rest: Props

) => B] | [baseProps?: B] 16 | : [mapToBase: (...rest: Props

) => B] | [baseProps: B]; 17 | } 18 | -------------------------------------------------------------------------------- /src/util/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./in-rest"; 2 | export * from "./molecules"; 3 | export * from "./recombine-tagged-template-args"; 4 | -------------------------------------------------------------------------------- /src/util/molecules.ts: -------------------------------------------------------------------------------- 1 | export type AnyRec = Record; 2 | export namespace AnyRec { 3 | export type Or = AnyRec | O; 4 | export namespace Or { 5 | export type Undef = Or; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/util/recombine-tagged-template-args.test.ts: -------------------------------------------------------------------------------- 1 | import {recombineTaggedTemplateArgs} from "./recombine-tagged-template-args"; 2 | 3 | const A = "A"; 4 | const B = "8"; 5 | const C = "Three"; 6 | 7 | function argumentsOf(quasis: TemplateStringsArray, ...rest: string[]): [TemplateStringsArray, ...string[]] { 8 | return [quasis, ...rest]; 9 | } 10 | 11 | describe("Recombine Tagged Template Args", () => { 12 | it("Without Quasis", () => { 13 | expect.assertions(1); 14 | const withoutQuasis = argumentsOf`Nice kicks man... those Air Jordan Retros?`; 15 | expect(recombineTaggedTemplateArgs(...withoutQuasis)).toStrictEqual("Nice kicks man... those Air Jordan Retros?"); 16 | }); 17 | 18 | it("Starting With Quasis", () => { 19 | expect.assertions(1); 20 | const startingWithQuasis = argumentsOf`${A} good way to code is to just close your eyes & hope for the ${B}est.`; 21 | expect(recombineTaggedTemplateArgs(...startingWithQuasis)).toStrictEqual( 22 | `A good way to code is to just close your eyes & hope for the 8est.`, 23 | ); 24 | }); 25 | 26 | it("With Middle Quasis", () => { 27 | expect.assertions(1); 28 | const withMiddleQuasis = argumentsOf`The number "${B}", the letter "${A}", and the spelled-number "${C}"`; 29 | expect(recombineTaggedTemplateArgs(...withMiddleQuasis)).toStrictEqual( 30 | `The number "8", the letter "A", and the spelled-number "Three"`, 31 | ); 32 | }); 33 | 34 | it("Without Literal Quasis", () => { 35 | expect.assertions(1); 36 | const withLiteralQuasis = argumentsOf`Lorem ipsum ${"dolor"}...`; 37 | expect(recombineTaggedTemplateArgs(...withLiteralQuasis)).toStrictEqual("Lorem ipsum dolor..."); 38 | }); 39 | }); 40 | -------------------------------------------------------------------------------- /src/util/recombine-tagged-template-args.ts: -------------------------------------------------------------------------------- 1 | export function recombineTaggedTemplateArgs(quasis: TemplateStringsArray, ...rest: string[]): string { 2 | return quasis.reduce((acc, e, i) => { 3 | return `${acc}${e}${rest[i] || ""}`; 4 | }, ""); 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.base.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "alwaysStrict": true, 4 | "declaration": true, 5 | "downlevelIteration": true, 6 | "esModuleInterop": true, 7 | "forceConsistentCasingInFileNames": true, 8 | "inlineSourceMap": true, 9 | "lib": ["DOM", "DOM.Iterable", "ESNext"], 10 | "module": "CommonJS", 11 | "moduleResolution": "node", 12 | "noEmitOnError": true, 13 | "noFallthroughCasesInSwitch": true, 14 | "noImplicitAny": true, 15 | "noImplicitThis": true, 16 | "noImplicitReturns": true, 17 | "noUncheckedIndexedAccess": true, 18 | "noUnusedLocals": true, 19 | "noUnusedParameters": true, 20 | "resolveJsonModule": true, 21 | "strict": true, 22 | "strictBindCallApply": true, 23 | "strictFunctionTypes": true, 24 | "strictNullChecks": true, 25 | "strictPropertyInitialization": true, 26 | "stripInternal": true, 27 | "target": "ES2018", 28 | "typeRoots": ["node_modules/@types"], 29 | "useDefineForClassFields": true 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "cjs" 4 | }, 5 | "exclude": ["**/*.test.ts", "**/tests/**/*", "example", "node_modules"], 6 | "extends": "./tsconfig.base.json", 7 | "include": ["src"] 8 | } 9 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": true, 3 | "exclude": ["node_modules"], 4 | "extends": "./tsconfig.base.json", 5 | "include": ["example", "src"] 6 | } 7 | --------------------------------------------------------------------------------