Full Code of StediInc/cdk-clj for AI

master 8de0174c47ef cached
26 files
70.9 KB
19.3k tokens
1 requests
Download .txt
Repository: StediInc/cdk-clj
Branch: master
Commit: 8de0174c47ef
Files: 26
Total size: 70.9 KB

Directory structure:
gitextract_cux68rya/

├── .github/
│   └── workflows/
│       └── build.yaml
├── .gitignore
├── LICENSE
├── README.md
├── deps.edn
├── examples/
│   ├── basics/
│   │   ├── cdk/
│   │   │   └── stedi/
│   │   │       └── basics/
│   │   │           └── cdk.clj
│   │   ├── cdk.json
│   │   ├── deps.edn
│   │   └── src/
│   │       └── stedi/
│   │           └── lambada.clj
│   └── depswatch/
│       ├── cdk/
│       │   └── depswatch/
│       │       └── cdk.clj
│       ├── cdk.json
│       ├── deps.edn
│       └── src/
│           └── depswatch/
│               └── lambada.clj
├── package.json
├── src/
│   └── stedi/
│       ├── cdk/
│       │   ├── alpha.clj
│       │   └── main.clj
│       └── jsii/
│           ├── alpha/
│           │   ├── assembly.clj
│           │   ├── client.clj
│           │   ├── fqn.clj
│           │   ├── impl.clj
│           │   ├── import.clj
│           │   └── spec.clj
│           └── alpha.clj
└── test/
    └── stedi/
        ├── cdk/
        │   ├── alpha_test.clj
        │   └── examples_test.clj
        └── jsii/
            └── alpha_test.clj

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/workflows/build.yaml
================================================
name: build
on: [push, pull_request]
jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v1
      - uses: DeLaGuardo/clojure-lint-action@v1
        with:
          clj-kondo-args: --lint .
          github_token: ${{ secrets.GITHUB_TOKEN }}
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v1
      - uses: actions/cache@v1
        with:
          path: ~/.m2/repository
          key: ${{ runner.os }}-maven-${{ hashFiles('**/deps.edn') }}
      - uses: actions/cache@v1
        with:
          path: ~/.gitlibs
          key: ${{ runner.os }}-gitlibs-${{ hashFiles('**/deps.edn') }}
      - uses: actions/cache@v1
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
      - uses: actions/setup-node@v1
        with:
          node-version: '10.x'
      - run: npm install
      - uses: actions/setup-java@v1
        with:
          java-version: '1.8'
      - uses: DeLaGuardo/setup-clojure@2.0
        with:
          tools-deps: '1.10.1.469'
      - run: clojure -A:dev:test


================================================
FILE: .gitignore
================================================
.cpcache
.nrepl-port
target
/.clj-kondo
**/cdk.out
**/classes
**/node_modules


================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   Copyright 2019 Stedi, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
# Current Status (January 16, 2020)

After developing and using this Clojure wrapper for [AWS CDK][1] for the past
six months, we've decided to use TypeScript and AWS' library directly. We are
discontinuing maintenance moving forward. If a member of the community would
like to volunteer for future maintenance, please file an issue or reach out
directly to discuss a possible transfer.

# cdk-clj

[![GitHub Action Status](https://github.com/stediinc/cdk-clj/workflows/build/badge.svg)](https://github.com/stediinc/cdk-clj/actions)

[#cdk-clj on Clojurians](https://clojurians.slack.com/archives/CQVV1N7QD)

This library is a Clojure wrapper for [AWS Cloud Development Kit (AWS CDK)][1].

This is an alpha release. We use this library internally and consider it
stable. Nonetheless, we may still make minor changes to the API.

## Purpose

From [AWS][1]:

>The AWS Cloud Development Kit (AWS CDK) is an open-source software development
>framework to define cloud infrastructure in code and provision it through AWS
>CloudFormation.
>
>It offers a high-level object-oriented abstraction to define AWS resources
>imperatively using the power of modern programming languages. Using the CDK's
>library of infrastructure constructs, you can easily encapsulate AWS best
>practices in your infrastructure definition and share it without worrying about
>boilerplate logic.

CDK is built on Amazon's [jsii][2] project, which allows TypeScript projects to
be shared across Python, JavaScript, Java and C# via code generation.

`cdk-clj` taps into this ecosystem directly by consuming the `jsii` protocol and
bringing infrastructure to the REPL. REPL-driven infrastructure turns a
frustrating practice with long feedback cycles into an enjoyable experience with
immediate feedback and makes it possible for Clojure code to be deployed to AWS
with minimal configuration.

For a general introduction, watch the Clojure/Conj talk:

[![Goodbye YAML: Infrastructure as Code in Clojure](https://img.youtube.com/vi/TbDmupZyuXk/0.jpg)][video]

## Prerequisites

`cdk-clj` requires:

1. [Clojure][clojure]
1. [Node.js][node-js]
1. [AWS CDK CLI][cdk-cli]

## Quick Start

0. Ensure you have configured appropriate [AWS Credentials][aws-creds].
   The following commands assume a [default profile][aws-profile].

1. Install `aws-cdk`:

``` shell
npm install -g aws-cdk
```

2. Create a new project directory with the following in a `deps.edn`
   file. You will also need to include the Maven dependency for any
   CDK modules you are using. You can find all the available modules
   [here][maven-deps].

``` clojure
{:paths   ["src"]
 :deps    {org.clojure/clojure {:mvn/version "1.10.1"}}
 :aliases {:dev {:extra-paths ["cdk"]
                 :extra-deps  {stedi/cdk-clj {:git/url "https://github.com/StediInc/cdk-clj.git"
                                              :sha     "<LATEST SHA HERE>"}
                               ;; Required in order to use the "@aws-cdk/aws-s3" module below
                               software.amazon.awscdk/s3 {:mvn/version "1.20.0"}
                               }}}}
```

3. Create a CDK infrastructure file with the path `./cdk/stedi/my_app/cdk.clj`.

``` clojure
(ns stedi.my-app.cdk
  (:require [stedi.cdk.alpha :as cdk]))

(cdk/import [[Stack] :from "@aws-cdk/core"]
            [[Bucket] :from "@aws-cdk/aws-s3"])

(defn AppStack
  [scope id props]
  (let [stack (Stack scope id props)]
    (Bucket stack "my-bucket" {:versioned true})))

(cdk/defapp app
  [this]
  (AppStack this "my-app-dev" {}))
```

4. Create
   [`cdk.json`](https://docs.aws.amazon.com/cdk/latest/guide/tools.html#cli) in
   the root of your project to tell the CDK toolchain how to invoke the app:
```json
{"app":"clojure -A:dev -i cdk/stedi/my_app/cdk.clj"}
```

where the argument to `-i` is the path to the file in which the cdk-clj app is
defined.

5. List your stacks to verify correct configuration:

``` shell
cdk ls
# should return `my-app-dev`
```

6. See the YAML that this deployment will produce for CloudFormation:

```
cdk synth my-app-dev
```

7. Deploy the stack to AWS:

```
cdk deploy my-app-dev
```

## Implementation Details

[jsii][2] is a protocol that allows TypeScript classes and objects to be
consumed via an RPC protocol. This protocol exposes the ability to:

- Create objects from classes with optionally overloaded methods
- Get properties from objects
- Set properties on objects
- Call methods on objects
- Get static properties on classes
- Set static properties on classes
- Call static methods on classes
- Respond to callbacks on overloaded objects

CDK exposes its functionality via this API to allow non-JavaScript programming
languages to benefit from the functionality it provides.
`cdk-clj` maps these operations into Clojure friendly equivalents. The CDK library
relies heavily on object oriented principles and `cdk-clj` does not shy away from
those concepts. Instead, it embraces them and maps them into a Clojure-friendly
interface. In doing so, it makes the [CDK documentation][3] directly mappable to
Clojure.

There are two types introduced by this library: `CDKClass` and
`CDKObject`. Together, they expose all of the functionality of the `jsii`
protocol by implementing the `clojure.lang.ILookup` and `clojure.lang.IFn`
interfaces:

**Instantiate an object from a class**

``` clojure
;; Creates a bucket based on the CDK class @aws-cdk/aws-s3.Bucket
(cdk/import [[Bucket] :from "@aws-cdk/aws-s3"])
(def bucket (Bucket parent "my-bucket" {}))
```

**Get property of an object**
``` clojure
;; Gets the bucketArn property off of the bucket instance
(:bucketArn bucket)
```

**Set property of an object**
``` clojure
;; TODO: not implemented yet
```

**Call a method on an object**
``` clojure
;; Grants READ permission to the lambda-function object
(cdk/import [[Bucket] :from "@aws-cdk/aws-s3"])
(Bucket/grantRead bucket lambda-function)
```

**Get static property of a class**
``` clojure
(cdk/import [[Runtime] :from "@aws-cdk/aws-lambda"])
;; Get the JAVA8 runtime instance
(:JAVA_8 Runtime)
```

**Set static property of an object**
``` clojure
;; TODO: not implemented yet
```

**Call static method on class**
``` clojure
(cdk/import [[Code] :from "@aws-cdk/aws-lambda"])
;; Refer to the src directory as an asset to be uploaded
(Code/asset "src")
```

## Next Steps

* Check out the [example app][4] to see the minimum setup required to get a
  [Lambda][stedilambda] deployed behind API Gateway
* Check out the [CDK API Docs][5] to see what modules are available and how to
  use them

## Troubleshooting

### Cannot find the 'jsii-runtime' executable (JSII_RUNTIME or PATH)

[This error][jsii-404] is non-specific and is raised on any failure to launch
the runtime process, not just the missing executable named; that the causative
exception is not chained makes this harder to debug.

One possible cause is not having the [Node.js][node-js] executable (i.e.,
`node`) on the `PATH` given to the JVM. If you're using a Node version or
[virtual environment][nodeenv] manager, add the appropriate directory to the JVM
environment.

## Contributing

Contributors are welcome to submit issues, bug reports, and feature
requests. Presently, we do not accept pull requests.

## License

cdk-clj is distributed under the [Apache License, Version 2.0][apache-2].

See [LICENSE](LICENSE) for more information.

[1]: https://github.com/aws/aws-cdk#aws-cloud-development-kit-aws-cdk
[2]: https://github.com/aws/jsii
[3]: https://docs.aws.amazon.com/cdk/api/latest/
[4]: https://github.com/StediInc/cdk-clj/tree/master/examples/basics
[5]: https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html

[apache-2]: https://www.apache.org/licenses/LICENSE-2.0
[aws-creds]: https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html
[aws-profile]: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html
[cdk-cli]: https://docs.aws.amazon.com/cdk/latest/guide/tools.html
[clojure]: https://clojure.org/guides/getting_started
[jsii-404]: https://github.com/aws/jsii/blob/850f42bea4218f2563d221aff28926da16692f62/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiRuntime.java#L220
[node-js]: https://nodejs.org/en/
[nodeenv]: https://github.com/ekalinin/nodeenv
[stedilambda]: https://github.com/StediInc/lambda
[maven-deps]: https://search.maven.org/search?q=software.amazon.awscdk
[video]: https://www.youtube.com/watch?v=TbDmupZyuXk


================================================
FILE: deps.edn
================================================
{:paths   ["resources" "src"]
 :deps    {org.clojure/clojure                 {:mvn/version "1.10.1"}
           org.apache.commons/commons-compress {:mvn/version "1.19"}
           org.clojure/data.json               {:mvn/version "0.2.6"}
           org.clojure/tools.cli               {:mvn/version "0.4.2"}
           org.clojure/tools.namespace         {:mvn/version "0.3.1"}
           software.amazon.awscdk/core         {:mvn/version "1.20.0"}}
 :aliases {:dev  {:extra-paths ["test"]
                  :extra-deps  {clj-kondo                     {:mvn/version "2019.09.22-alpha"}
                                com.cognitect/test-runner
                                {:git/url "https://github.com/cognitect-labs/test-runner.git"
                                 :sha     "209b64504cb3bd3b99ecfec7937b358a879f55c1"}
                                software.amazon.awscdk/lambda {:mvn/version "1.20.0"}}}
           :lint {:main-opts ["-m" "clj-kondo.main" "--lint" "."]}
           :unit {:main-opts ["-m" "cognitect.test-runner" "--exclude" "integration"]}
           :test {:main-opts ["-m" "cognitect.test-runner"]}}}


================================================
FILE: examples/basics/cdk/stedi/basics/cdk.clj
================================================
(ns stedi.basics.cdk
  (:require [clojure.edn :as edn]
            [clojure.java.io :as io]
            [stedi.cdk.alpha :as cdk]
            [uberdeps.api :as uberdeps]))

;; CDK is a framework released by Amazon that allows developers to
;; deploy CloudFormation-based infrastructure using their prefered
;; language.

;; It is built from TypeScript and made available to other languages
;; through the JSii protocol by Amazon. JSii allows other languages to
;; interact with JavaScript classes through an RPC protocol.

;; cdk-clj wraps the JSii protocol for CDK classes in Clojure.

;; The best way of getting information about what is availble via CDK
;; is to call `(cdk/browse)` in the REPL. This will take you to the
;; AWS CDK API reference documentation.

(comment
  (cdk/browse)
  )

;; CDK applications consist of Constructs arranged into a tree
;; structure. Constructs represent one or more AWS resources. All CDK
;; applications have an App construct at the root of the
;; tree. `cdk-clj` exposes access to these constructs through the
;; `cdk/import` macro.

(cdk/import [[App] :from "@aws-cdk/core"])

;; Import does two things:
;; 1. makes App resolvable to a jsii-class in the local namespace
;; 2. aliases the ns for "@aws-cdk/core.App" to App

;; App will now resolve to a jsii-class
App

;; Invoking the class calls its constructor and returns a
;; jsii-instance:
(def app (App))

;; These constructor vars also have docstrings
App

;; Import also makes an alias to the ns that contains all the static
;; and instance methods for App
App/isApp
App/synth

;; You can also browse to a constructs documentation via browse on
;; the constructor or an instance:

(comment
  (cdk/browse app)
  (cdk/browse App)
  )

;; Applications are composed of one or more Stacks, each representing
;; a CloudFormation Stack. A Stack is a Construct as well.

(cdk/import [[Stack] :from "@aws-cdk/core"])

;; Child constructs are connected to their parent by passing in the
;; parent as the scope of the child's constructor function.

(def stack (Stack app "cdk-clj-basics"))

;; Class instances implement the ILookup interface so they work with
;; keyword lookups

(:stackName stack)

;; A stack needs at least one resource Construct in order to be
;; deployable so lets add a bucket.

(cdk/import [[Bucket] :from "@aws-cdk/aws-s3"])

;; cdk-clj generates specs for and instruments all jsii constructors
;; and functions:

(comment
  (Bucket stack nil) ; Fails with spec error

  ;; Worth noting that the CDK specs are closed

  (Bucket stack "id" {:does-not-exist :foo}) ; Fails due to specs being closed
  )

(def bucket (Bucket stack "bucket"))

;; Buckets aren't particularly interesting, and lambdas + serverless
;; are all the rage so lets add a lambda function as well.

(cdk/import [[Code Function Runtime] :from "@aws-cdk/aws-lambda"])

(defn- clean
  []
  (->> (io/file "classes")
       (file-seq)
       (reverse)
       (map io/delete-file)
       (dorun)))

(def jarpath "target/app.jar")

;; Build an uberjar with the compiled source + dependency classes

(let [deps (edn/read-string (slurp "deps.edn"))]
  (when (.exists (io/file "classes")) (clean))
  (with-out-str
    (io/make-parents "classes/.")
    (io/make-parents jarpath)
    (compile 'stedi.lambada)
    (uberdeps/package deps jarpath {:aliases [:classes]})))

(comment
  (cdk/browse Function)
  )

(def my-fn
  (Function stack
            "my-fn"
            {:code        (Code/fromAsset jarpath)        ;; Calling a static method
             :handler     "stedi.cdk.basics.Hello"
             :runtime     (:JAVA_8 Runtime)               ;; Getting a static property
             :environment {"BUCKET" (:bucketName bucket)} ;; Getting an instance property
             }))

(comment
  ;; See it bound to the construct tree
  (map (comp :path :node)
       (get-in stack [:node :children]))
  )

;; We can grant the function write access to the bucket using an
;; instance method

(Bucket/grantWrite bucket my-fn)

;; CDK constructs often have functions for granting permissions,
;; adding metrics and triggering events.

;; This app can now be deployed using `cdk-cli` in a shell with AWS
;; credentials configured.

;; Synth:
;; cdk synth

;; Deploy:
;; cdk deploy

;; Destroy:
;; cdk destroy


================================================
FILE: examples/basics/cdk.json
================================================
{"app":"clojure -C:dev -R:dev -m stedi.cdk.main synth"}

================================================
FILE: examples/basics/deps.edn
================================================
{:paths   ["src"]
 :deps    {org.clojure/clojure {:mvn/version "1.10.1"}
           uswitch/lambada     {:mvn/version "0.1.2"}}
 :aliases {:cdk     {:main-opts ["-m" "stedi.cdk.main"]}
           :classes {:extra-paths ["classes"]}
           :dev     {:extra-paths ["cdk"]
                     :extra-deps  {software.amazon.awscdk/s3     {:mvn/version "1.20.0"}
                                   software.amazon.awscdk/lambda {:mvn/version "1.20.0"}
                                   stedi/cdk-clj                 {:local/root "../../"}
                                   uberdeps                      {:mvn/version "0.1.6"}}}}}


================================================
FILE: examples/basics/src/stedi/lambada.clj
================================================
(ns stedi.lambada
  (:require [uswitch.lambada.core :refer [deflambdafn]]))

(deflambdafn stedi.cdk.basics.Hello
  [in out ctx]
  (let [bucket-name (System/getenv "BUCKET")]
    (.write out (.getBytes (format "Hello! Bucket Name: %s" bucket-name)))))


================================================
FILE: examples/depswatch/cdk/depswatch/cdk.clj
================================================
(ns depswatch.cdk
  (:require [clojure.edn :as edn]
            [clojure.java.io :as io]
            [stedi.cdk.alpha :as cdk]
            [uberdeps.api :as uberdeps]))

(cdk/import [[App Construct Duration Stack] :from "@aws-cdk/core"]
            [[LambdaRestApi] :from "@aws-cdk/aws-apigateway"]
            [[AttributeType Table] :from "@aws-cdk/aws-dynamodb"]
            [[Rule Schedule] :from "@aws-cdk/aws-events"]
            [[SfnStateMachine] :from "@aws-cdk/aws-events-targets"]
            [[Code Function Runtime Tracing] :from "@aws-cdk/aws-lambda"]
            [[Chain Choice Condition Data
              Map StateMachine Succeed Task] :from "@aws-cdk/aws-stepfunctions"]
            [[InvokeFunction StartExecution] :from "@aws-cdk/aws-stepfunctions-tasks"])

(defn- clean
  []
  (let [f (io/file "classes")]
    (when (.exists f)
      (->> f
           (file-seq)
           (reverse)
           (map io/delete-file)
           (dorun)))))

(def code
  (let [jarpath "target/app.jar"
        deps    (edn/read-string (slurp "deps.edn"))]
    (with-out-str
      (clean)
      (io/make-parents "classes/.")
      (io/make-parents jarpath)
      (compile 'depswatch.lambada)
      (uberdeps/package deps jarpath {:aliases [:classes]}))
    (Code/fromAsset jarpath)))

(defn LambadaFunction
  [scope id props]
  (Function scope
            id
            (merge {:code       code
                    :memorySize 2048
                    :runtime    (:JAVA_8 Runtime)
                    :tracing    Tracing/ACTIVE}
                   props)))

(defn TaskFunction
  [scope id {:keys [handler resultPath]}]
  (let [construct (Construct scope id)
        fn        (LambadaFunction construct "fn" {:handler handler})
        task      (Task construct
                        id
                        {:task       (InvokeFunction fn)
                         :resultPath (or resultPath "$")})]
    task))

(defn RunJobStateMachine
  [scope id]
  (let [construct (Construct scope id)
        definition
        (-> (Chain/start
              (TaskFunction construct
                            "get-deps-edn"
                            {:handler    "depswatch.GetDepsEdn"
                             :resultPath "$.depsEdn"}))
            (Chain/next
              (TaskFunction construct
                            "check-newer"
                            {:handler    "depswatch.CheckNewer"
                             :resultPath "$.newer"}))
            (Chain/next
              (TaskFunction construct
                            "check-sent"
                            {:handler    "depswatch.CheckSent"
                             :resultPath "$.sent"}))
            (Chain/next
              (doto (Choice construct "was-sent")
                (Choice/when (Condition/booleanEquals "$.sent" true)
                  (Succeed construct "already-sent"))

                (Choice/when (Condition/booleanEquals "$.sent" false)
                  (TaskFunction construct
                                "notify-slack"
                                {:handler "depswatch.NotifySlack"})))))]
    (StateMachine construct "sfn" {:definition definition})))

(defn StartJobsStateMachine
  [scope id {:keys [run-job]}]
  (let [construct (Construct scope id)
        task      (StartExecution run-job
                                  {:input {:owner (Data/stringAt "$.owner")
                                           :repo  (Data/stringAt "$.repo")}})
        definition
        (doto (TaskFunction construct
                            "get-repos"
                            {:handler "depswatch.GetRepos"})
          (Task/next
            (doto (Map construct "run-jobs")
              (Map/iterator
                (Task construct "run-job" {:task task})))))]
    (StateMachine construct "sfn" {:definition definition})))

(defn AppStack
  [scope id {:keys [timer?]}]
  (let [stack         (Stack scope id)
        watched-repos (Table stack
                             "watched-repos"
                             {:partitionKey {:name "owner"
                                             :type AttributeType/STRING}})
        slack-hook    (LambadaFunction stack
                                       "slack-hook"
                                       {:handler "depswatch.SlackHook"
                                        :environment
                                        {"WATCHED_REPOS" (:tableName watched-repos)}})
        run-job       (RunJobStateMachine stack "run-job")
        start-jobs    (StartJobsStateMachine stack "start-jobs" {:run-job run-job})]
    (when timer?
      (Rule stack
            "timer"
            {:schedule (Schedule/rate
                         (Duration/minutes 1))
             :targets  [(SfnStateMachine start-jobs)]}))
    (Table/grantReadWriteData watched-repos slack-hook)
    (LambdaRestApi slack-hook "api" {:handler slack-hook})
    stack))

(def app (App))

(AppStack app "depswatch-dev" {:timer? false})
(AppStack app "depswatch-prod" {:timer? true})


================================================
FILE: examples/depswatch/cdk.json
================================================
{"app":"clojure -C:dev -R:dev -m stedi.cdk.main synth"}

================================================
FILE: examples/depswatch/deps.edn
================================================
{:paths ["src"]
 :deps  {org.clojure/clojure {:mvn/version "1.10.1"}

         org.clojure/data.json {:mvn/version "0.2.6"}
         uswitch/lambada       {:mvn/version "0.1.2"}}
 :aliases {:cdk     {:main-opts ["-m" "stedi.cdk.main"]}
           :classes {:extra-paths ["classes"]}
           :dev     {:extra-paths ["cdk"]
                     :extra-deps  {stediinc/cdk-clj {:local/root "../../"}

                                   uberdeps {:mvn/version "0.1.6"}

                                   software.amazon.awscdk/apigateway          {:mvn/version "1.20.0"}
                                   software.amazon.awscdk/dynamodb            {:mvn/version "1.20.0"}
                                   software.amazon.awscdk/events              {:mvn/version "1.20.0"}
                                   software.amazon.awscdk/events-targets      {:mvn/version "1.20.0"}
                                   software.amazon.awscdk/lambda              {:mvn/version "1.20.0"}
                                   software.amazon.awscdk/stepfunctions       {:mvn/version "1.20.0"}
                                   software.amazon.awscdk/stepfunctions-tasks {:mvn/version "1.20.0"}}}}}


================================================
FILE: examples/depswatch/src/depswatch/lambada.clj
================================================
(ns depswatch.lambada
  (:require [clojure.data.json :as json]
            [uswitch.lambada.core :refer [deflambdafn]]))

(deflambdafn depswatch.GetRepos
  [in out ctx]
  (.write out
          (.getBytes
            (json/write-str
              [{:owner "stediinc"
                :repo  "cdk-clj"}]))))

(deflambdafn depswatch.GetDepsEdn
  [in out ctx]
  (.write out
          (.getBytes
            (json/write-str
              (pr-str
                {:deps {'midje {:mvn/version "1.9.8"}}})))))

(deflambdafn depswatch.CheckNewer
  [in out ctx]
  (.write out
          (.getBytes
            (json/write-str
              (pr-str
                {'midje {:old-version "1.9.8"
                         :new-version "1.9.9"}})))))

(deflambdafn depswatch.CheckSent
  [in out ctx]
  (.write out
          (.getBytes
            (json/write-str
              false))))

(deflambdafn depswatch.NotifySlack
  [in out ctx]
  (.write out
          (.getBytes
            (json/write-str
              "Slack notified"))))


================================================
FILE: package.json
================================================
{
  "name": "cdk-clj",
  "version": "1.0.0",
  "description": "This library is a Clojure wrapper for [AWS Cloud Development Kit (AWS CDK)][1].",
  "main": "index.js",
  "directories": {
    "example": "examples",
    "test": "test"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/stediinc/cdk-clj.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/stediinc/cdk-clj/issues"
  },
  "homepage": "https://github.com/stediinc/cdk-clj#readme",
  "devDependencies": {
    "aws-cdk": "^1.16.3"
  }
}


================================================
FILE: src/stedi/cdk/alpha.clj
================================================
(ns stedi.cdk.alpha
  (:refer-clojure :exclude [import])
  (:require [clojure.java.browse :as browse]
            [clojure.spec.alpha :as s]
            [clojure.string :as string]
            [stedi.jsii.alpha :as jsii]))

(def ^:private docs-prefix
  "https://docs.aws.amazon.com/cdk/api/latest")

(defn browse
  "Browse to CDK documentation by CDK fqn, CDK object or CDK
  class. Calling without any arguments opens the root documentation.

  Examples:

  ;; Opening module documentation
  (cdk/browse \"@aws-cdk/core\") ;; open core module
  (cdk/browse \"core\") ;; also opens core module

  ;; Opening class documentation
  (import [\"@aws-cdk/core\" Stack])

  (cdk/browse \"@aws-cdk/aws-lambda.Stack\")
  (cdk/browse Stack)   ;; can open docs from a class
  (cdk/browse (Stack)) ;; can also open docs from an instance
  "
  ([] (browse/browse-url docs-prefix))
  ([obj-class-or-fqn]
   (letfn [(cdk-class? [fqn]
             (re-find #"\.[A-Za-z]+$" fqn))

           (fqn->url [fqn]
             (let [url-formatted-fqn
                   (if (cdk-class? fqn)
                     (string/replace fqn "/" "_")
                     (str (string/replace fqn "@aws-cdk/" "")
                          "-readme"))]
               (format "%s/docs/%s.html" docs-prefix url-formatted-fqn)))]
     (cond
       (string? obj-class-or-fqn)
       (browse/browse-url (fqn->url obj-class-or-fqn))

       (jsii/jsii-primitive? obj-class-or-fqn)
       (browse (jsii/fqn obj-class-or-fqn))))))

(s/def ::bindings
  (s/+
    (s/alt :alias (s/cat :alias symbol?)
           :as    (s/cat :class symbol?
                         :as    #{:as}
                         :alias symbol?))))

(s/def ::import-args
  (s/or :v0 (s/coll-of
              (s/cat :module string?
                     :bindings ::bindings))
        :v1 (s/coll-of
              (s/cat :bindings (s/spec ::bindings)
                     :from #{:from}
                     :module string?))))

(s/fdef import
  :args ::import-args
  :ret  any?)

(defmacro import
  "Imports jsii classes and binds them to an alias. Allows for multiple
  module requirement bindings.

  Example:

  (cdk/import [[App Stack] :from \"@aws-cdk/core\"])"
  [& imports]
  (let [[version import-list] (s/conform ::import-args imports)]
    (when (= :v0 version)
      (println
       (str "Warning: Using outdated import format. Please use "
            "the :from syntax. See `cdk/import` docstring for "
            "example.")))
    (doseq [{:keys [module bindings]} import-list

            [_ {:keys [class alias]}] bindings]
      (jsii/import-fqn (str module "." (or class alias)) alias))))

(defmacro defapp
  "The @aws-cdk/core.App class is the main class for a CDK project.

  `defapp` is a convenience macro that creates an extension for an app
  with a signature similar to defn. The first argument will be the app
  itself and is to be used in the body to wire in children constructs.

  After declaring itself, the app extension instantiates itself which
  forces cdk validations to occur to streamline the repl-workflow.

  Example:

  (cdk/defapp app
    [this]
    (stack this \"MyDevStack\" {}))"
  [name args & body]
  (jsii/reset-runtime!)
  `(do (import [[~'App] :from "@aws-cdk/core"])
       (let [app# (~'App {})]
         ((fn ~args ~@body) app#)
         (def ~name
           (doto app#
             (App/synth))))))


================================================
FILE: src/stedi/cdk/main.clj
================================================
(ns stedi.cdk.main
  (:require [clojure.data.json :as json]
            [clojure.java.classpath :as cp]
            [clojure.tools.cli :as cli]
            [clojure.tools.namespace.find :as ctn.find]
            [stedi.cdk.alpha :as cdk]
            [stedi.jsii.alpha :as jsii]))

(cdk/import [[App] :from "@aws-cdk/core"])

(defn load-project-files
  []
  (->> (cp/classpath-directories)
       (ctn.find/find-namespaces)
       (map #(try (require %) % (catch Exception _)))
       (remove nil?)
       (doall)))

(defn find-app
  []
  (let [apps (->> (load-project-files)
                  (mapcat ns-publics)
                  (map second)
                  (filter (comp #(and (jsii/jsii-primitive? %)
                                      (App/isApp %))
                                deref)))]
    (assert (not-empty apps) "No app was found.")
    (assert (= 1 (count apps)) "More than one app was found.")
    (deref (first apps))))

(defn config
  [{:keys [aliases]}]
  (spit "cdk.json"
        (json/write-str
          {:app (str "clojure"
                     (when aliases
                       (str " -C:" aliases " -R:" aliases))
                     " -m stedi.cdk.main synth")}
          :escape-slash false)))

(defn synth
  [_]
  (let [app (find-app)]
    (App/synth app)))

(def actions
  {:config {:cli-options [[nil "--aliases ALIASES" "Colon seperated classpath aliases to use during synth"]]
            :handler     config}
   :synth  {:handler synth}})

(defn do-main
  [args]
  (let [action-kw         (keyword (first args))
        {:keys [cli-options
                handler]} (get actions action-kw)
        {:keys [options]} (cli/parse-opts args (or cli-options []))]
    (handler options)))

(defn -main [& args]
  (try
    (do-main args)
    (finally
      (shutdown-agents))))


================================================
FILE: src/stedi/jsii/alpha/assembly.clj
================================================
(ns stedi.jsii.alpha.assembly
  (:require [clojure.data.json :as json]
            [clojure.java.io :as io]
            [clojure.string :as string])
  (:import (java.util.zip GZIPInputStream)
           (org.apache.commons.compress.archivers.tar TarArchiveInputStream))
  (:refer-clojure :exclude [methods]))

(defn- classpath-jsii-archives
  []
  (->> (-> (System/getProperty "java.class.path")
           (string/split #":"))
       (filter #(string/ends-with? % ".jar"))
       (map io/file)
       (map #(java.util.jar.JarFile. %))
       (mapcat (comp enumeration-seq #(.entries %)))
       (filter (comp #(.endsWith % "jsii.tgz") str))
       (map str)))

(defn- keywordize-alpha
  [x]
  (if (and (string? x)
           (re-find #"^[A-Za-z]" x))
    (keyword x)
    x))

(defn- read-spec
  [input-stream]
  (-> input-stream
      (io/reader)
      (json/read :key-fn keywordize-alpha)))

(defn- load-assembly-resource [resource]
  (with-open [is (-> resource
                     (io/resource)
                     (io/input-stream)
                     (GZIPInputStream.)
                     (TarArchiveInputStream.))]
    (loop []
      (when-let [entry (.getNextTarEntry is)]
        (if (= (.getName entry) "package/.jsii")
          (assoc (read-spec is) ::bundle (str "/" resource))
          (recur))))))

(defn- load-all-assemblies
  []
  (into []
        (map load-assembly-resource)
        (classpath-jsii-archives)))

(defn- indexed-types
  []
  (->> (load-all-assemblies)
       (map :types)
       (apply merge)))

(defonce ^:private all-types* (map second (indexed-types)))

(defn all-types [] all-types*)

(def get-type
  (memoize
    (fn [fqn]
      (->> (all-types)
           (filter (comp #{fqn} :fqn))
           (first)))))

(def get-assembly
  (memoize
    (fn [module-name]
      (->> (load-all-assemblies)
           (filter (comp #{module-name} :name))
           (first)))))

(defn arities
  [parameters]
  (let [base     (take-while (complement :optional) parameters)
        optional (drop-while (complement :optional) parameters)]
    (concat
      (list base)
      (for [n (map inc (range (count optional)))]
        (concat base (take n optional))))))

(defn- interfaces*
  [fqn]
  (let [t            (get-type fqn)
        t-interfaces (:interfaces t)]
    (lazy-cat (when (= "interface" (:kind t))
                (list fqn))
              t-interfaces
              (mapcat interfaces* t-interfaces)
              (when-let [base (:base t)]
                (interfaces* base)))))

(defn interfaces
  [fqn]
  (set (interfaces* fqn)))

(defn class-heirarchy
  [fqn]
  (when-let [t (get-type fqn)]
    (lazy-seq (cons fqn (class-heirarchy (:base t))))))

(defn- dedupe-by-name
  [coll]
  (sequence (comp (map second)
                  (map last))
            (group-by :name coll)))

(defn- properties*
  [fqn]
  (when-let [t (get-type fqn)]
    (lazy-cat (when-let [interfaces (:interfaces t)]
                (mapcat properties* interfaces))
              (when-let [base (:base t)]
                (properties* base))
              (:properties t))))

(defn properties
  [fqn]
  (dedupe-by-name (remove :protected (properties* fqn))))

(defn- methods*
  [fqn]
  (when-let [t (get-type fqn)]
    (lazy-cat (when-let [base (:base t)]
                (methods* base))
              (:methods t))))

(defn methods
  [fqn]
  (dedupe-by-name (remove :protected (methods* fqn))))


================================================
FILE: src/stedi/jsii/alpha/client.clj
================================================
(ns stedi.jsii.alpha.client
  (:require [clojure.data.json :as json]
            [clojure.string :as string]
            [stedi.jsii.alpha.assembly :as assm])
  (:import (com.fasterxml.jackson.databind ObjectMapper)
           (software.amazon.jsii JsiiRuntime JsiiModule JsiiObjectRef)))

(defonce ^:private object-mapper (ObjectMapper.))

(defonce ^:private jsii-runtime (atom (JsiiRuntime.)))

(defonce ^:private loaded-modules (atom #{}))

(defn- ->module [{:keys [module-name module-version module-bundle]}]
  (let [this (proxy [JsiiModule] [module-name module-version nil module-bundle])]
    (proxy [JsiiModule] [module-name module-version (class this) module-bundle])))

(defn reset-runtime!
  []
  (reset! jsii-runtime (JsiiRuntime.))
  (reset! loaded-modules #{}))

(defn- client
  []
  (.getClient @jsii-runtime))

(defn load-module [fqn]
  (let [module-name (first (string/split fqn #"\."))]
    (when-not (@loaded-modules module-name)
      (let [{:keys [::assm/bundle
                    version
                    dependencies]} (assm/get-assembly module-name)

            module (->module {:module-name    module-name
                              :module-version version
                              :module-bundle  bundle})]
        (doseq [dep (map first dependencies)]
          (load-module dep))
        (.loadModule (client) module)
        (swap! loaded-modules conj module-name)))))

(defn- json-node->edn [json-node]
  (some-> json-node
          (.toString)
          (json/read-str)))

(defn- edn->json-node [data]
  (->> data
       (json/write-str)
       (.readTree object-mapper)))

(defn create-object
  ([fqn initializer-args]
   (load-module fqn)
   (let [initializer-args (map edn->json-node initializer-args)
         overrides []
         interfaces []]
     (-> (.createObject (client) fqn initializer-args overrides interfaces)
         (.toJson)
         (json-node->edn)))))

(defn delete-object
  [object-ref]
  (.deleteObject (client) object-ref))

(defn get-property-value
  [object-id property]
  (let [object-ref (JsiiObjectRef/fromObjId object-id)]
    (-> (.getPropertyValue (client) object-ref property)
        (json-node->edn))))

(defn set-property-value
  [object-ref property value]
  (.setPropertyValue (client) object-ref property (edn->json-node value)))

(defn get-static-property-value
  [fqn property]
  (load-module fqn)
  (-> (.getStaticPropertyValue (client) fqn property)
      (json-node->edn)))

(defn set-static-property-value
  [fqn property value]
  (load-module fqn)
  (.setStaticPropertyValue (client) fqn property (edn->json-node value)))

(defn call-static-method
  [fqn method args]
  (load-module fqn)
  (-> (.callStaticMethod (client) fqn method (edn->json-node args))
      (json-node->edn)))

(defn call-method
  [object-id method args]
  (let [object-ref (JsiiObjectRef/fromObjId object-id)]
    (-> (.callMethod (client) object-ref method (edn->json-node args))
        (json-node->edn))))


================================================
FILE: src/stedi/jsii/alpha/fqn.clj
================================================
(ns stedi.jsii.alpha.fqn
  (:require [clojure.string :as string]))

(defn- tokenize
  [fqn & parts]
  (-> (string/join "." (concat [fqn] parts))
      (string/replace "@" "")
      (string/replace "/" ".")
      (string/split #"\.")))

(defn fqn->ns-sym
  [fqn & parts]
  (symbol
    (->> (apply tokenize fqn parts)
         (string/join "."))))

(defn fqn->qualified-keyword
  [fqn & parts]
  (-> (apply tokenize fqn parts)
      ((juxt butlast last))
      (update 0 (partial string/join "."))
      ((partial string/join "/"))
      (keyword)))

(defn fqn->qualified-symbol
  [fqn & parts]
  (symbol
    (apply fqn->qualified-keyword fqn parts)))


================================================
FILE: src/stedi/jsii/alpha/impl.clj
================================================
(ns stedi.jsii.alpha.impl
  (:require [clojure.data.json :as json]
            [clojure.walk :as walk]
            [stedi.jsii.alpha.assembly :as assm]
            [stedi.jsii.alpha.client :as client]
            [stedi.jsii.alpha.fqn :as fqn])
  (:import (software.amazon.jsii JsiiObjectRef)))

(def ^:private valid-tokens
  #{"$jsii.byref"
    "$jsii.enum"
    "$jsii.date"
    "$jsii.map"})

(defn- jsii-type
  [x]
  (and (map? x)
       (some valid-tokens (keys x))))

;; This is to encompass conversions of different JSON-serialized jsii
;; types. Only $jsii.byref is currently implemented because we have
;; not seen examples of the other serializations yet. However, the
;; link below implies that we may run into additional types that need
;; to be implemented.
;; https://github.com/aws/jsii/blob/master/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiObjectMapper.java
(defmulti ^:private ->type jsii-type)

(defn- ->clj
  [m]
  (walk/postwalk
    (fn [x]
      (if (jsii-type x)
        (->type x)
        x))
    m))

(defprotocol Invocable
  (-invoke [_ req]))

(defn get-type-info
  [t]
  (assm/get-type (.-fqn t)))

(defn- props
  [x pred?]
  (into #{}
        (comp (filter pred?)
              (map :name)
              (map keyword))
        (assm/properties (.-fqn x))))

(deftype JsiiObject [fqn interfaces objId]
  clojure.lang.ILookup
  (valAt [this k]
    (->clj (client/get-property-value objId (name k))))

  Invocable
  (-invoke [_ {:keys [op args]}]
    (->clj (client/call-method objId (name op) (or args []))))

  java.lang.Object
  (toString [this]
    (when (some (comp #{"toString"} :name)
                (assm/methods fqn))
      (-invoke this {:op :toString})))

  json/JSONWriter
  (-write [object out]
    (.write out (format "{\"$jsii.byref\": \"%s\"}" objId))))

(defmethod ->type "$jsii.byref"
  [x]
  (let [id         (-> x first second)
        interfaces (get x "$jsii.interfaces" [])
        ref        (JsiiObjectRef/fromObjId id)]
    (->JsiiObject (.getFqn ref) interfaces id)))

(defmethod print-method JsiiObject
  [this w]
  (.write w (format "#jsii-object[%s]"
                    (pr-str {:id         (.-objId this)
                             :interfaces (.-interfaces this)
                             :props      (props this (complement :static))}))))

(defn- call-initializer
  [this args]
  (let [sym  (fqn/fqn->qualified-symbol (.-fqn this) "impl" "-initializer")
        ctor (requiring-resolve sym)]
    (apply ctor args)))

(deftype JsiiClass [fqn]
  clojure.lang.ILookup
  (valAt [this k]
    (->clj (client/get-static-property-value fqn (name k))))

  Invocable
  (-invoke [_ {:keys [op args]}]
    (->clj (client/call-static-method fqn (name op) (or args []))))

  clojure.lang.IFn
  (applyTo [this arglist]
    (call-initializer this arglist))
  (invoke [this]
    (call-initializer this []))
  (invoke [this a1]
    (call-initializer this [a1]))
  (invoke [this a1 a2]
    (call-initializer this [a1 a2]))
  (invoke [this a1 a2 a3]
    (call-initializer this [a1 a2 a3])))

(defmethod print-method JsiiClass
  [this w]
  (.write w (format "#jsii-class[%s]"
                    (pr-str {:fqn   (.-fqn this)
                             :props (props this :static)}))))

(deftype JsiiEnumMember [fqn value]
  json/JSONWriter
  (-write [object out]
    (.write out (format "{\"$jsii.enum\": \"%s\"}"
                        (str fqn "/" (name value))))))

(defmethod print-method JsiiEnumMember
  [this w]
  (.write w (format "#jsii-enum-member[%s]"
                    (pr-str (str (.-fqn this) "/" (name (.-value this)))))))

(declare member-values)

(deftype JsiiEnumClass [fqn]
  clojure.lang.ILookup
  (valAt [_ k]
    (let [valid-values (member-values fqn)
          value
          (or (valid-values k)
              (throw (ex-info "Invalid enumeration value"
                              {:k            k
                               :valid-values valid-values})))]
      (JsiiEnumMember. fqn value))))

(defmethod print-method JsiiEnumClass
  [this w]
  (.write w (format "#jsii-enum-class[%s]"
                    (pr-str {:fqn     (.-fqn this)
                             :members (member-values (.-fqn this))}))))

;;------------------------------------------------------------------------------

(defn create
  [c args]
  (let [fqn        (.-fqn c)
        object     (client/create-object fqn (or args []))
        interfaces (get object "$jsii.interfaces" [])
        oid        (get object "$jsii.byref")]
    (->JsiiObject fqn interfaces oid)))

(defn get-class
  [fqn]
  (let [{:keys [kind]}
        (or (assm/get-type fqn)
            (throw (Exception.
                     (str "No class available for fqn: " fqn))))]
    (case kind
      "enum"  (->JsiiEnumClass fqn)
      "class" (->JsiiClass fqn))))

(defn member-values
  [fqn]
  (->> (:members (assm/get-type fqn))
       (map :name)
       (map keyword)
       (set)))

(defn class-instance?
  [fqn x]
  (boolean
    (and (instance? JsiiObject x)
         (some #{fqn} (assm/class-heirarchy (.-fqn x))))))

(defn enum-member?
  [fqn x]
  (boolean
    (and (instance? JsiiEnumMember x)
         (= fqn (.-fqn x))
         ((member-values fqn) (.-value x)))))

(defn satisfies-interface?
  [fqn x]
  (boolean
    (and (instance? JsiiObject x)
         (let [interfaces (.-interfaces x)]
           (some #{fqn} (into #{}
                              (mapcat assm/interfaces)
                              (conj interfaces (.-fqn x))))))))


================================================
FILE: src/stedi/jsii/alpha/import.clj
================================================
(ns stedi.jsii.alpha.import
  (:require [clojure.spec.test.alpha :as stest]
            [clojure.string :as string]
            [stedi.jsii.alpha.assembly :as assm]
            [stedi.jsii.alpha.fqn :as fqn]
            [stedi.jsii.alpha.impl :as impl]
            [stedi.jsii.alpha.spec :as spec]))

(defn- arg-lists
  [parameters]
  (reverse
    (into (list)
          (map (partial into []
                        (mapcat (fn [{:keys [variadic name]}]
                                  (if variadic
                                    (list '& (symbol name))
                                    (list (symbol name)))))))
          (assm/arities parameters))))

(defn- render-constructor-docstring
  [{:keys [docs]}]
  (let [{:keys [default stability summary deprecated remarks]} docs]
    (->> [(str)
          (when stability (format "stability: [%s]" stability))
          (str)
          (when summary summary)
          (when deprecated deprecated)
          (when default (format "default: %s" stability))
          (when remarks (format "remarks: %s" remarks))]
         (remove nil?)
         (string/join "\n"))))

(defn- intern-initializer
  [impl-ns-sym class-sym c]
  (let [fqs
        (symbol
          (intern impl-ns-sym '-initializer
                  (fn [& args]
                    (impl/create c args))))
        assembly   (assm/get-type (.-fqn c))
        parameters (-> assembly
                       (:initializer)
                       (:parameters))]
    (spec/load-spec fqs)
    (stest/instrument fqs)
    (intern impl-ns-sym
            (with-meta class-sym
              {:arglists (arg-lists parameters)
               :doc      (render-constructor-docstring assembly)})
            c)
    (spec/load-spec (symbol (name impl-ns-sym) (name class-sym)))))

(defn- render-method-docstring
  [{:keys [docs]}]
  (let [{:keys [default stability summary deprecated]} docs]
    (->> [(str)
          (when stability (format "stability: [%s]" stability))
          (str)
          (when summary summary)
          (when deprecated deprecated)
          (when default (format "default: %s" stability))]
         (remove nil?)
         (string/join "\n"))))

(defn- intern-methods
  [target-ns-sym methods c]
  (doseq [{:keys [static] :as method} methods]
    (let [method-sym (-> method (:name) (symbol))
          parameters (:parameters method)
          deprecated (get-in method [:docs :deprecated])
          fqs
          (symbol
            (intern target-ns-sym
                    (with-meta method-sym
                      (cond-> {:arglists (arg-lists
                                           (concat (when-not static
                                                     (list {:name "this"}))
                                                   parameters))
                               :doc      (render-method-docstring method)}
                        deprecated (assoc :deprecated true)))
                    (fn [& args]
                      (impl/-invoke
                        (if static c (first args))
                        {:op   method-sym
                         :args (if static args (rest args))}))))]
      (spec/load-spec fqs)
      (stest/instrument fqs))))

(defn- intern-enum-members
  [target-ns-sym members c]
  (doseq [member members]
    (let [member-sym  (-> member (:name) (symbol))
          member-k    (keyword member-sym)
          enum-member (get c member-k)]
      (intern target-ns-sym member-sym enum-member))))

(defn import-fqn
  [fqn alias-sym]
  (let [target-ns-sym (fqn/fqn->ns-sym fqn)
        class-sym     (-> fqn (string/split #"\.") (last) (symbol))
        impl-ns-sym   (symbol (str target-ns-sym ".impl"))
        c             (impl/get-class fqn)

        {:keys [members]} (impl/get-type-info c)
        methods           (assm/methods fqn)]
    (create-ns target-ns-sym)
    (create-ns impl-ns-sym)
    (ns-unmap impl-ns-sym class-sym)
    (intern-initializer impl-ns-sym class-sym c)
    (intern-methods target-ns-sym methods c)
    (intern-enum-members target-ns-sym members c)
    (alias alias-sym target-ns-sym)
    (ns-unmap *ns* alias-sym)
    (refer impl-ns-sym
           :only [class-sym]
           :rename {class-sym alias-sym})))


================================================
FILE: src/stedi/jsii/alpha/spec.clj
================================================
(ns stedi.jsii.alpha.spec
  (:require [clojure.spec.alpha :as s]
            [clojure.spec.gen.alpha :as sgen]
            [stedi.jsii.alpha.assembly :as assm]
            [stedi.jsii.alpha.fqn :as fqn]
            [stedi.jsii.alpha.impl :as impl]))

(s/def ::string-like
  (s/or :string string?
        :keyword keyword?))

(s/def ::json
  (s/or :string ::string-like
        :int integer?
        :float float?
        :boolean boolean?
        :vector (s/coll-of ::json :kind vector?)
        :map (s/map-of ::string-like ::json)))

(defn- metatype
  [{:keys [datatype kind]}]
  (cond
    datatype :datatype
    :else    (keyword kind)))

(defmulti ^:private spec-form ffirst)

(defmethod spec-form :union
  [{:keys [union]}]
  (let [{:keys [types]} union]
    `(s/or ~@(mapcat (juxt (constantly :opt)
                           spec-form)
                     types))))

(defmethod spec-form :fqn
  [{:keys [fqn]}]
  (fqn/fqn->qualified-keyword fqn))

(defmethod spec-form :primitive
  [{:keys [primitive]}]
  (case primitive
    "string"  `string?
    "any"     `any?
    "boolean" `boolean?
    "number"  `number?
    "date"    `inst?
    "json"    ::json))

(defmethod spec-form :collection
  [{:keys [collection]}]
  (let [{:keys [elementtype kind]} collection
        element-form               (spec-form elementtype)]
    (case kind
      "map"   `(s/map-of ::string-like ~element-form)
      "array" `(s/coll-of ~element-form :kind vector?))))

(defn- prop-spec-k
  [t prop]
  (fqn/fqn->qualified-keyword (:fqn t) (:name prop)))

(defn gen-class-instance
  [fqn]
  (sgen/return (impl/->JsiiObject fqn [] nil)))

(defn- class-spec-definition
  [{:keys [fqn]}]
  `(s/def ~(fqn/fqn->qualified-keyword fqn)
     (s/spec #(impl/class-instance? ~fqn %)
             :gen (partial gen-class-instance ~fqn))))

(defn gen-enum-member
  [fqn]
  (sgen/bind
    (sgen/elements (impl/member-values fqn))
    (fn [value]
      (sgen/return
        (impl/->JsiiEnumMember fqn value)))))

(defn- enum-spec-definition
  [{:keys [fqn]}]
  `(s/def ~(fqn/fqn->qualified-keyword fqn)
     (s/spec #(impl/enum-member? ~fqn %)
             :gen (partial gen-enum-member ~fqn))))

(defn gen-satisfies-interface
  [fqn]
  (sgen/return
    ;; TODO: fqn for object-id is no longer a correct assumption
    (impl/->JsiiObject fqn [fqn] nil)))

(defn- interface-spec-definition
  [{:keys [fqn]}]
  `(s/def ~(fqn/fqn->qualified-keyword fqn)
     (s/spec #(impl/satisfies-interface? ~fqn %)
             :gen (partial gen-satisfies-interface ~fqn))))

(defn- datatype-spec-definition
  [{:keys [fqn] :as t}]
  (let [properties (assm/properties fqn)
        req-un     (into []
                         (comp (remove :optional)
                               (map (partial prop-spec-k t)))
                         properties)
        opt-un     (into []
                         (comp (filter :optional)
                               (map (partial prop-spec-k t)))
                         properties)]
    `(s/def ~(fqn/fqn->qualified-keyword fqn)
       (s/and (s/keys :req-un ~req-un
                      :opt-un ~opt-un)
              #(every? ~(into #{}
                              (comp (map name)
                                    (map keyword))
                              (concat req-un opt-un))
                       (keys %))))))

(defn- method-arity-form
  [parameters]
  `(s/cat ~@(mapcat (juxt (comp keyword :name)
                          (fn [{:keys [optional variadic] :as param}]
                            (let [form (spec-form (:type param))]
                              (cond optional `(s/nilable ~form)
                                    variadic `(s/* ~form)
                                    :else    form))))
                    parameters)))

(defn- method-arg-spec-form
  [{:keys [fqn]} {:keys [static parameters overrides]}]
  (let [arities* (assm/arities
                   (concat (when-not static
                             (list {:name "this"
                                    :type (if overrides
                                            {:fqn overrides}
                                            {:fqn fqn})}))
                           parameters))]
    (if (= 1 (count arities*))
      (method-arity-form (first arities*))
      `(s/alt
         ~@(mapcat
             (fn [arity-params]
               [(keyword (str "arity" (count arity-params)))
                (method-arity-form arity-params)])
             arities*)))))

(defn- method-spec-definition
  [{:keys [fqn] :as t} {:keys [name returns] :as method}]
  `(s/fdef ~(fqn/fqn->qualified-symbol fqn name)
                :args ~(method-arg-spec-form t method)
                :ret  ~(or (some-> returns (:type) (spec-form)) `nil?)))

(defn- initializer-spec-definition
  [{:keys [fqn] :as t} method]
  `(s/fdef ~(fqn/fqn->qualified-symbol fqn "impl" "-initializer")
     :args ~(method-arg-spec-form t (assoc method :static true))
     :ret  ~(fqn/fqn->qualified-keyword fqn)))

(defn- class-initializer-spec-definition
  [{:keys [fqn name] :as t} method]
  `(s/fdef ~(fqn/fqn->qualified-symbol fqn "impl" name)
     :args ~(method-arg-spec-form t (assoc method :static true))
     :ret  ~(fqn/fqn->qualified-keyword fqn)))

(defn- prop-spec-definition
  [t prop]
  `(s/def ~(prop-spec-k t prop)
     ~(spec-form (:type prop))))

(defn spec-definitions
  [t]
  (try
    (let [{:keys [initializer]} t

          methods    (some-> t (:fqn) (assm/methods))
          properties (some-> t (:fqn) (assm/properties))

          type-definition
          (case (metatype t)
            :class     (class-spec-definition t)
            :enum      (enum-spec-definition t)
            :datatype  (datatype-spec-definition t)
            :interface (interface-spec-definition t))

          initializer-definition            (initializer-spec-definition t initializer)
          class-initializer-spec-definition (class-initializer-spec-definition t initializer)]
      (doall
        (concat (list type-definition
                      initializer-definition
                      class-initializer-spec-definition)
                (map (partial method-spec-definition t) methods)
                (map (partial prop-spec-definition t) properties))))
    (catch Throwable e
      (throw (ex-info "Unable to build spec definition" {:t t} e)))))

(defn- index-spec-forms
  []
  (into {}
        (comp (mapcat spec-definitions)
              (map (juxt second identity)))
        (assm/all-types)))

(defonce ^:private indexed-specs (index-spec-forms))

(defn load-spec
  [k]
  (or (s/get-spec k)
      (let [definition (or (get indexed-specs k)
                           (throw (Exception. (str "No spec for k " k))))
            deps       (->> (drop 2 definition)
                            (tree-seq seqable? seq)
                            (filter qualified-keyword?))]
        ;; This is a little bit of a hack, it is possible for specs to
        ;; have circular dependencies so we load the current spec with
        ;; a placeholder before loading its dependencies.
        (eval `(s/def ~k any?))
        (dorun (map load-spec deps))
        (eval definition)))
  true)


================================================
FILE: src/stedi/jsii/alpha.clj
================================================
(ns stedi.jsii.alpha
  "A Clojure-based interface into jsii modules."
  (:require [stedi.jsii.alpha.client :as client]
            [stedi.jsii.alpha.impl :as impl]
            [stedi.jsii.alpha.import :as import]))

(defn get-class
  "Gets the jsii class for a given fqn."
  [fqn]
  (impl/get-class fqn))

(defn jsii-primitive?
  "Returns true if x is a jsii primitive."
  [x]
  (boolean
    (some #(instance? % x)
          [stedi.jsii.alpha.impl.JsiiObject
           stedi.jsii.alpha.impl.JsiiClass
           stedi.jsii.alpha.impl.JsiiEnumClass
           stedi.jsii.alpha.impl.JsiiEnumMember])))

(defn fqn
  "Returns the fqn of a jsii primitive."
  [x]
  (.-fqn x))

(defn describe
  "Describes a jsii type (class, enum or object)."
  [x]
  (impl/get-type-info x))

(defn import-fqn
  "Imports a jsii class or enum by fqn as alias-sym and refers the jsii
  class or enum artifact as alias-sym."
  [fqn alias-sym]
  (import/import-fqn fqn alias-sym))

(defn reset-runtime!
  "Resets the jsii runtime unloading any loaded modules."
  []
  (client/reset-runtime!))


================================================
FILE: test/stedi/cdk/alpha_test.clj
================================================
(ns stedi.cdk.alpha-test
  "Provides examples of interacting with CDK constructs and classes."
  (:require [clojure.test :refer [deftest is testing]]
            [stedi.cdk.alpha :as cdk]))

(cdk/import [[App :as A, Stack] :from "@aws-cdk/core"]
            [[Function Runtime] :from "@aws-cdk/aws-lambda"]
            [[StringParameter] :from "@aws-cdk/aws-ssm"])

(deftest cdk-example-test
  (testing "instantiating an object"
    (is (Stack nil "my-stack")))
  (testing "getting a property of an instance"
    (is (:region (Stack nil "my-stack"))))
  (testing "calling an instance method"
    (is (Stack/toString (Stack nil "my-stack"))))
  (testing "calling a static method"
    (is (Stack/isStack (Stack nil "my-stack"))))
  (testing "getting a static property of a class"
    (is (:JAVA_8 Runtime)))
  (testing "renaming an alias"
    (is (A/isApp (A))))
  (testing "calling a method on a returned interface"
    (let [s (Stack)]
      (is (StringParameter/grantRead
            (StringParameter/fromStringParameterName s "param" "param-name")
            (Function/fromFunctionArn s "fn" "function-arn"))))))

(defmacro with-url-spy
  "Evaluates `form` in the context of a redefintion of browse-url, capturing the
  arguments and returning them."
  [form]
  `(let [spy# (atom [])]
     (with-redefs [clojure.java.browse/browse-url
                   (fn [url#] (swap! spy# conj url#))]
       (do ~form
           (deref spy#)))))

(deftest browse-test
  (testing "opening documentation with no arguments"
    (is (= ["https://docs.aws.amazon.com/cdk/api/latest"]
           (with-url-spy (cdk/browse)))))
  (testing "opening module documentation with full path"
    (is (= ["https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html"]
           (with-url-spy (cdk/browse "@aws-cdk/core")))))
  (testing "opening module documentation for `core`"
    (is (= ["https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html"]
           (with-url-spy (cdk/browse "core")))))
  (testing "opening fully qualified documentation for a class"
    (is (= ["https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html"]
           (with-url-spy (cdk/browse "@aws-cdk/core.Stack")))))
  (testing "opening documentation for a class"
    (is (= ["https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html"]
           (with-url-spy (cdk/browse Stack)))))
  (testing "opening documentation for an instance"
    (is (= ["https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.Stack.html"]
           (with-url-spy (cdk/browse (Stack)))))))


================================================
FILE: test/stedi/cdk/examples_test.clj
================================================
(ns stedi.cdk.examples-test
  (:require [clojure.java.io :as io]
            [clojure.java.shell :as sh]
            [clojure.string :as string]
            [clojure.test :refer [deftest testing is]]))

(def cdk-bin-path "node_modules/aws-cdk/bin/cdk")

(defn example-projects
  []
  (->> (file-seq (io/file "examples"))
     (map #(.split (str %) "/"))
     (filter #(= 2 (count %)))
     (map second)))

(defn synth
  [project]
  (let [{:keys [exit out err]}
        (sh/with-sh-dir (format "examples/%s" project)
          (sh/sh (str "../../" cdk-bin-path) "synth"))]
    (when-not (= 0 exit)
      (println (format "===== [%s] failed to synth! =====" project))
      (when-not (string/blank? out)
        (println)
        (println "Out:")
        (println)
        (println out))
      (when-not (string/blank? err)
        (println)
        (println "Err:")
        (println)
        (println err))
      (throw (Exception. (str "An error occured running cdk synth. "
                              "Check logs for more info."))))
    true))

(deftest ^:integration synth-examples-test
  (assert (.exists (io/file cdk-bin-path)) "Could not find cdk executable. Did you run `npm install`?")
  (doseq [project (example-projects)]
    (testing (str "cdk synth " project)
      (is (synth project)))))


================================================
FILE: test/stedi/jsii/alpha_test.clj
================================================
(ns stedi.jsii.alpha-test
  (:require [clojure.spec.alpha :as s]
            [clojure.test :as t :refer [deftest testing is]]
            [stedi.jsii.alpha :as jsii]))

(jsii/import-fqn "@aws-cdk/core.App" 'App)
(jsii/import-fqn "@aws-cdk/core.Reference" 'Reference)
(jsii/import-fqn "@aws-cdk/core.Stack" 'Stack)
(jsii/import-fqn "@aws-cdk/core.TagType" 'TagType)
(jsii/import-fqn "@aws-cdk/aws-s3.Bucket" 'Bucket)

(deftest jsii-class-test
  (let [C (jsii/get-class "@aws-cdk/core.Stack")]
    (is (instance? stedi.jsii.alpha.impl.JsiiClass C))

    (testing "invoking a class invokes the constructor"
      (let [stack (C)]
        (is (instance? stedi.jsii.alpha.impl.JsiiObject stack))))

    (testing "classes extend ILookup for static property access"
      (is (:ACCOUNT_ID (jsii/get-class "@aws-cdk/core.Aws"))))))

(deftest jsii-object-test
  (let [C (jsii/get-class "@aws-cdk/core.Stack")
        stack (C nil "my-stack")]
    (testing "objects extend ILookup for property access"
      (is (= "my-stack" (:stackName stack))))

    (testing "toString"
      (is (.contains (str (Reference "hello" (Stack))) "TOKEN")))))

(deftest import-fqn-test
  (testing "refers a jsii primitive into the current namespace"
    (is (jsii/jsii-primitive? App)))

  (testing "creates a namespace for the specified jsii class"
    (is (find-ns 'aws-cdk.core.App)))

  (testing "aliases created namespace to the specified symbol"
    (is (= (find-ns 'aws-cdk.core.App)
           (-> (ns-aliases (find-ns 'stedi.jsii.alpha-test))
               (get 'App))))))

(deftest importing-a-class-test
  (testing "refers a jsii class into the current namespace"
    (is (instance? stedi.jsii.alpha.impl.JsiiClass App)))

  (testing "interns class functions into created namespace"
    (let [interned-symbols
          (->> (find-ns 'aws-cdk.core.App)
               (ns-map)
               (map second)
               (filter var?)
               (map symbol)
               (set))]
      (is (= '#{aws-cdk.core.App/synth
                aws-cdk.core.App/isApp
                aws-cdk.core.App/isConstruct
                aws-cdk.core.App/toString}
             interned-symbols))))

  (testing "interned functions are specced"
    (s/get-spec 'aws-cdk.core.App/synth))

  (testing "interned functions are instrumented"
    (is (.contains (str aws-cdk.core.App/synth)
                   "spec_checking_fn")))

  (testing "map specs are closed"
    (let [ex (is (thrown? Exception (Bucket (Stack) "bucket" {:does-not-exist "foo"})))]
      (is (:clojure.spec.alpha/problems (ex-data ex)))))

  (testing "interned static functions have the correct arglists"
    (is (= '([x])
           (-> (resolve 'aws-cdk.core.Stack/isStack)
               (meta)
               (:arglists)))))

  (testing "interned instance functions have the correct arglists"
    (is (= '([this target] [this target reason])
           (-> (resolve 'aws-cdk.core.Stack/addDependency)
               (meta)
               (:arglists))))))

(deftest importing-an-enum-test
  (testing "refers a jsii enum into the current namespace"
    (is (instance? stedi.jsii.alpha.impl.JsiiEnumClass TagType)))

  (testing "interns enum members into created namespace"
    (let [interned-symbols
          (->> (find-ns 'aws-cdk.core.TagType)
               (ns-map)
               (map second)
               (filter var?)
               (map symbol)
               (set))]
      (is (= '#{aws-cdk.core.TagType/STANDARD
                aws-cdk.core.TagType/AUTOSCALING_GROUP
                aws-cdk.core.TagType/MAP
                aws-cdk.core.TagType/NOT_TAGGABLE
                aws-cdk.core.TagType/KEY_VALUE}
             interned-symbols))))

  (testing "interned members are enum members"
    (is (instance? stedi.jsii.alpha.impl.JsiiEnumMember TagType/STANDARD))))

(comment
  (t/run-tests)

 )
Download .txt
gitextract_cux68rya/

├── .github/
│   └── workflows/
│       └── build.yaml
├── .gitignore
├── LICENSE
├── README.md
├── deps.edn
├── examples/
│   ├── basics/
│   │   ├── cdk/
│   │   │   └── stedi/
│   │   │       └── basics/
│   │   │           └── cdk.clj
│   │   ├── cdk.json
│   │   ├── deps.edn
│   │   └── src/
│   │       └── stedi/
│   │           └── lambada.clj
│   └── depswatch/
│       ├── cdk/
│       │   └── depswatch/
│       │       └── cdk.clj
│       ├── cdk.json
│       ├── deps.edn
│       └── src/
│           └── depswatch/
│               └── lambada.clj
├── package.json
├── src/
│   └── stedi/
│       ├── cdk/
│       │   ├── alpha.clj
│       │   └── main.clj
│       └── jsii/
│           ├── alpha/
│           │   ├── assembly.clj
│           │   ├── client.clj
│           │   ├── fqn.clj
│           │   ├── impl.clj
│           │   ├── import.clj
│           │   └── spec.clj
│           └── alpha.clj
└── test/
    └── stedi/
        ├── cdk/
        │   ├── alpha_test.clj
        │   └── examples_test.clj
        └── jsii/
            └── alpha_test.clj
Condensed preview — 26 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (77K chars).
[
  {
    "path": ".github/workflows/build.yaml",
    "chars": 1101,
    "preview": "name: build\non: [push, pull_request]\njobs:\n  lint:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@"
  },
  {
    "path": ".gitignore",
    "chars": 78,
    "preview": ".cpcache\n.nrepl-port\ntarget\n/.clj-kondo\n**/cdk.out\n**/classes\n**/node_modules\n"
  },
  {
    "path": "LICENSE",
    "chars": 10756,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 8454,
    "preview": "# Current Status (January 16, 2020)\n\nAfter developing and using this Clojure wrapper for [AWS CDK][1] for the past\nsix m"
  },
  {
    "path": "deps.edn",
    "chars": 1131,
    "preview": "{:paths   [\"resources\" \"src\"]\n :deps    {org.clojure/clojure                 {:mvn/version \"1.10.1\"}\n           org.apac"
  },
  {
    "path": "examples/basics/cdk/stedi/basics/cdk.clj",
    "chars": 4278,
    "preview": "(ns stedi.basics.cdk\n  (:require [clojure.edn :as edn]\n            [clojure.java.io :as io]\n            [stedi.cdk.alpha"
  },
  {
    "path": "examples/basics/cdk.json",
    "chars": 55,
    "preview": "{\"app\":\"clojure -C:dev -R:dev -m stedi.cdk.main synth\"}"
  },
  {
    "path": "examples/basics/deps.edn",
    "chars": 632,
    "preview": "{:paths   [\"src\"]\n :deps    {org.clojure/clojure {:mvn/version \"1.10.1\"}\n           uswitch/lambada     {:mvn/version \"0"
  },
  {
    "path": "examples/basics/src/stedi/lambada.clj",
    "chars": 251,
    "preview": "(ns stedi.lambada\n  (:require [uswitch.lambada.core :refer [deflambdafn]]))\n\n(deflambdafn stedi.cdk.basics.Hello\n  [in o"
  },
  {
    "path": "examples/depswatch/cdk/depswatch/cdk.clj",
    "chars": 5032,
    "preview": "(ns depswatch.cdk\n  (:require [clojure.edn :as edn]\n            [clojure.java.io :as io]\n            [stedi.cdk.alpha :a"
  },
  {
    "path": "examples/depswatch/cdk.json",
    "chars": 55,
    "preview": "{\"app\":\"clojure -C:dev -R:dev -m stedi.cdk.main synth\"}"
  },
  {
    "path": "examples/depswatch/deps.edn",
    "chars": 1187,
    "preview": "{:paths [\"src\"]\n :deps  {org.clojure/clojure {:mvn/version \"1.10.1\"}\n\n         org.clojure/data.json {:mvn/version \"0.2."
  },
  {
    "path": "examples/depswatch/src/depswatch/lambada.clj",
    "chars": 1020,
    "preview": "(ns depswatch.lambada\n  (:require [clojure.data.json :as json]\n            [uswitch.lambada.core :refer [deflambdafn]]))"
  },
  {
    "path": "package.json",
    "chars": 655,
    "preview": "{\n  \"name\": \"cdk-clj\",\n  \"version\": \"1.0.0\",\n  \"description\": \"This library is a Clojure wrapper for [AWS Cloud Developm"
  },
  {
    "path": "src/stedi/cdk/alpha.clj",
    "chars": 3385,
    "preview": "(ns stedi.cdk.alpha\n  (:refer-clojure :exclude [import])\n  (:require [clojure.java.browse :as browse]\n            [cloju"
  },
  {
    "path": "src/stedi/cdk/main.clj",
    "chars": 1813,
    "preview": "(ns stedi.cdk.main\n  (:require [clojure.data.json :as json]\n            [clojure.java.classpath :as cp]\n            [clo"
  },
  {
    "path": "src/stedi/jsii/alpha/assembly.clj",
    "chars": 3416,
    "preview": "(ns stedi.jsii.alpha.assembly\n  (:require [clojure.data.json :as json]\n            [clojure.java.io :as io]\n            "
  },
  {
    "path": "src/stedi/jsii/alpha/client.clj",
    "chars": 2974,
    "preview": "(ns stedi.jsii.alpha.client\n  (:require [clojure.data.json :as json]\n            [clojure.string :as string]\n           "
  },
  {
    "path": "src/stedi/jsii/alpha/fqn.clj",
    "chars": 650,
    "preview": "(ns stedi.jsii.alpha.fqn\n  (:require [clojure.string :as string]))\n\n(defn- tokenize\n  [fqn & parts]\n  (-> (string/join \""
  },
  {
    "path": "src/stedi/jsii/alpha/impl.clj",
    "chars": 5512,
    "preview": "(ns stedi.jsii.alpha.impl\n  (:require [clojure.data.json :as json]\n            [clojure.walk :as walk]\n            [sted"
  },
  {
    "path": "src/stedi/jsii/alpha/import.clj",
    "chars": 4238,
    "preview": "(ns stedi.jsii.alpha.import\n  (:require [clojure.spec.test.alpha :as stest]\n            [clojure.string :as string]\n    "
  },
  {
    "path": "src/stedi/jsii/alpha/spec.clj",
    "chars": 7173,
    "preview": "(ns stedi.jsii.alpha.spec\n  (:require [clojure.spec.alpha :as s]\n            [clojure.spec.gen.alpha :as sgen]\n         "
  },
  {
    "path": "src/stedi/jsii/alpha.clj",
    "chars": 1068,
    "preview": "(ns stedi.jsii.alpha\n  \"A Clojure-based interface into jsii modules.\"\n  (:require [stedi.jsii.alpha.client :as client]\n "
  },
  {
    "path": "test/stedi/cdk/alpha_test.clj",
    "chars": 2578,
    "preview": "(ns stedi.cdk.alpha-test\n  \"Provides examples of interacting with CDK constructs and classes.\"\n  (:require [clojure.test"
  },
  {
    "path": "test/stedi/cdk/examples_test.clj",
    "chars": 1304,
    "preview": "(ns stedi.cdk.examples-test\n  (:require [clojure.java.io :as io]\n            [clojure.java.shell :as sh]\n            [cl"
  },
  {
    "path": "test/stedi/jsii/alpha_test.clj",
    "chars": 3846,
    "preview": "(ns stedi.jsii.alpha-test\n  (:require [clojure.spec.alpha :as s]\n            [clojure.test :as t :refer [deftest testing"
  }
]

About this extraction

This page contains the full source code of the StediInc/cdk-clj GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 26 files (70.9 KB), approximately 19.3k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!