### Install dependencies with npm install
Source: https://github.com/squint-cljs/squint/blob/main/examples/windowjs/README.md
Run this command in the project root to install required dependencies before starting the development server.
```bash
npm install
```
--------------------------------
### Install and start development environment
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Run these commands after cloning the repository to set up dependencies and start the development server. Requires Babashka, Clojure, Node, npm, and pnpm. `pnpm install` uses the checked-in lockfile, and `bb dev` installs playground dependencies and starts the compiler watcher and dev server.
```shell
cd squint
pnpm install
bb dev
```
--------------------------------
### Install and run the browser REPL dev server
Source: https://github.com/squint-cljs/squint/blob/main/examples/browser-repl/README.md
Run these commands in the example directory to install dependencies and start the Vite dev server, which compiles ClojureScript, hot-reloads the page, and runs an nREPL server. After starting, connect your editor to `.nrepl-port` (or `localhost:1339`) to eval in the running page.
```bash
npm install
```
```bash
npm run dev
```
--------------------------------
### Build production website with Vite
Source: https://github.com/squint-cljs/squint/blob/main/examples/game-of-life/README.md
Build the production website using Vite, outputting to the public directory.
```bash
$ npx vite build public
```
--------------------------------
### Start nREPL server with squint nrepl-server
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Starts an nREPL server on Node.js using the `squint nrepl-server` command with a specified port. The implementation is currently immature; users are encouraged to try it and file issues.
```clojure
squint nrepl-server :port 1888
```
--------------------------------
### Start Expo dev server
Source: https://github.com/squint-cljs/squint/blob/main/examples/expo-react-native/README.md
Starts the Expo development server.
```bash
$ npx expo start
```
--------------------------------
### Install squint-cljs with npm
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Sets up a new project directory and installs the squint-cljs package. Run these commands in a terminal to create a project and install the latest version.
```shell
$ mkdir squint-test && cd squint-test
$ npm init -y
$ npm install squint-cljs@latest
```
--------------------------------
### Install and Run AJV Example
Source: https://github.com/squint-cljs/squint/blob/main/examples/ajv/Readme.md
Commands to install dependencies and run the AJV example with squint. The output shows validation results for valid and invalid users, with the invalid user failing due to a missing 'email' property.
```sh
nmp i
npx squint run ajv.cljs
```
```text
[squint] Running ajv.cljs
Valid user: ✅ Valid null
Invalid user: ❌ Invalid [
{
instancePath: '',
schemaPath: '#/required',
keyword: 'required',
params: { missingProperty: 'email' },
message: "must have required property 'email'"
}
]
```
--------------------------------
### Install squint-cljs dependency
Source: https://github.com/squint-cljs/squint/blob/main/examples/game-of-life/README.md
Install the squint-cljs package as a dependency for the project.
```bash
$ npm install squint-cljs
```
--------------------------------
### Create example.cljs
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Example ClojureScript file that requires Node.js modules and defines a function. Demonstrates using squint's interop with JavaScript modules and destructuring.
```clojure
(ns example
(:require ["fs" :as fs]
["url" :refer [fileURLToPath]]))
(println (fs/existsSync (fileURLToPath js/import.meta.url)))
(defn foo [{:keys [a b c]}]
(+ a b c))
(println (foo {:a 1 :b 2 :c 3}))
```
--------------------------------
### Basic JSX with #jsx tag
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Use the `#jsx` tag to produce JSX syntax. The example outputs `
Hello
` and automatically uses the `.jsx` extension.
```clojure
#jsx [:div "Hello"]
```
```html
Hello
```
--------------------------------
### Install dependencies with npm
Source: https://github.com/squint-cljs/squint/blob/main/examples/expo-react-native/README.md
Installs project dependencies for the Expo React Native example.
```bash
$ npm i
```
--------------------------------
### Unsafe HTML with [:$ ...]
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Use `[:$ ...]` to produce unsafe (unescaped) HTML. The example shows a full HTML document string.
```clojure
(str #html
[:<> [:$ ""]
[:html [:head] [:body]]])
;;=> ""
```
--------------------------------
### Run development server with bb dev
Source: https://github.com/squint-cljs/squint/blob/main/examples/vite-react/README.md
Starts squint watch and vite dev server. Compiled files are generated in public/js.
```bash
bb dev
```
--------------------------------
### Async function with await
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Mark a function with `^:async` to use `await` inside it. The example shows an async function returning a promise and awaiting it, printing 10.
```clojure
(defn ^:async foo [] (js/Promise.resolve 10))
(def x (await (foo)))
(println x) ;;=> 10
```
--------------------------------
### Run dev server with npm run dev
Source: https://github.com/squint-cljs/squint/blob/main/examples/windowjs/README.md
Starts the development workflow: compiles .cljs to .js and runs the Vite server. Use this for local development.
```bash
npm run dev
```
--------------------------------
### squint.edn with :deps git dependency
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Example squint.edn configuration with :paths and :deps using :git/url and :git/sha. Requires clojure CLI on PATH to resolve source directories.
```clojure
{:paths ["src"]
:deps {io.github.cjohansen/replicant {:git/sha "..."}}}
```
--------------------------------
### Async generator function with ^:async and ^:gen
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Mark a function with both `^:async` and `^:gen` to create an async generator. The example yields values after awaiting a promise.
```clojure
(defn ^:async ^:gen nums []
(js-yield (await (js/Promise.resolve 1)))
(js-yield 2))
```
--------------------------------
### Static asset import with JSON type
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Use this syntax to import a static asset with a type attribute, which tools like Vite can inline at compile time. The example shows importing a JSON file with `:with {:type :json}`.
```clojure
[./test.json$default :as json :with {:type :json}]
```
```javascript
import data from "../test.json$default" with { type: "json" };
```
--------------------------------
### Render into #app element in playground
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Use this snippet to draw into the page from a playground example. The playground shows the #app element in a resizable frame; DOM elements added elsewhere still render but sit outside that frame.
```clojure
(let [el (js/document.getElementById "app")] ...)
```
--------------------------------
### Set VITE_APP_ID in .env
Source: https://github.com/squint-cljs/squint/blob/main/examples/instantdb/README.md
Fill in your InstantDB App ID in the .env file using the VITE_APP_ID variable. This is required before running the dev server.
```plaintext
VITE_APP_ID=...
```
--------------------------------
### Import raw asset with ?raw suffix
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Use this syntax to import other types of assets when using Vite with the `?raw` suffix.
```clojure
["logo.svg?raw" :as logo]
```
--------------------------------
### Compile and run example.cljs
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Compiles and runs the example.cljs file using squint's run command. The output shows 'true' and '6' as the result of the script.
```shell
$ npx squint run example.cljs
true
6
```
--------------------------------
### Run Node with --enable-source-maps for stack traces
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Run the compiled JavaScript with Node's --enable-source-maps flag to get .cljs locations in stack traces. This is useful for debugging when source maps are enabled.
```bash
node --enable-source-maps src/app.mjs
```
--------------------------------
### Run tests watch with bb test:watch
Source: https://github.com/squint-cljs/squint/blob/main/examples/vite-react/README.md
Starts squint watch on tests and vitest test watcher. Files are generated in public/test.
```bash
bb test:watch
```
--------------------------------
### doseq with ^:await binding for async iterables
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Mark a `doseq` binding with `^:await` to iterate async iterables, emitting `for await`. The example prints 1 and 2.
```clojure
(doseq [^:await x (nums)] ;; emits `for await`
(println x))
;; prints 1, 2
```
--------------------------------
### Error stack trace output from npm start
Source: https://github.com/squint-cljs/squint/blob/main/examples/source-maps/README.md
Example output showing the error stack trace with source locations in app.cljs.
```text
Error: not a number: x
at parse_age (.../src/app.cljs:6:14)
at (.../src/app.cljs:10:27)
...
at average_age (.../src/app.cljs:11:8)
```
--------------------------------
### Build production bundle with bb build
Source: https://github.com/squint-cljs/squint/blob/main/examples/vite-react/README.md
Generates a production ready build in public/dist and a bundle status report at ./bundle-visualization.html.
```bash
bb build
```
--------------------------------
### Passing props with :& in #jsx
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Use `:&` to pass props to a component in JSX. The example passes a map of props to the `App` component.
```clojure
(let [props {:a 1}]
#jsx [App {:& props}])
```
--------------------------------
### Run npm start to show source locations in error stack trace
Source: https://github.com/squint-cljs/squint/blob/main/examples/source-maps/README.md
Run this command to start the demo and display source locations in the error stack trace.
```bash
npm start
```
--------------------------------
### Build with vite build public
Source: https://github.com/squint-cljs/squint/blob/main/examples/windowjs/README.md
Compiles the project for production using Vite, outputting to the public directory.
```bash
vite build public
```
--------------------------------
### Using metadata with #html for lit-html
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Metadata can modify the tag function, e.g., to use with lit-html. The example requires the `lit` library and uses `^lit/html` metadata to produce a lit-html template.
```clojure
(ns my-app
(:require ["lit" :as lit]))
#html ^lit/html [:div "Hello"]
```
```clojure
lit/html`Hello
`
```
--------------------------------
### HTML content escaping
Source: https://github.com/squint-cljs/squint/blob/main/README.md
HTML content is escaped by default. The example shows that special characters like `<>` are escaped to `<>`.
```clojure
(my-html #html [:div "<>"]) ;;=> Html {s: "Hello
<>
"}
```
--------------------------------
### doseq with ^:await on binding vector for nested async iteration
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Tag the binding vector with `^:await` to apply to all bindings, enabling nested `for await` loops. The example prints pairs [1 1], [1 2], [2 1], [2 2].
```clojure
(doseq ^:await [x (nums) ;; outer `for await`
y (nums)] ;; inner `for await`
(println [x y]))
;; prints [1 1], [1 2], [2 1], [2 2]
```
--------------------------------
### Generator function with ^:gen
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Mark a function with `^:gen` to create a generator function. The example yields values and uses `js-yield*` for multiple values, resulting in [1 2 3 4].
```clojure
(defn ^:gen foo []
(js-yield 1)
(js-yield* [2 3])
(let [x (inc 3)]
(js-yield x)))
(vec (foo)) ;;=> [1 2 3 4]
```
--------------------------------
### package.json scripts for dev and build
Source: https://github.com/squint-cljs/squint/blob/main/doc/browser-repl.md
Defines `npm run dev` to start Vite dev server with nREPL, and `npm run build` for optimized production bundle without REPL/HMR.
```json
{
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build"
}
}
```
--------------------------------
### Nested HTML objects
Source: https://github.com/squint-cljs/squint/blob/main/README.md
HTML objects can be nested. The example defines a function that returns an HTML object and calls it with another HTML object, producing a combined HTML string.
```clojure
(defn my-html [x] #html [:<> [:div "Hello"] x])
(my-html #html [:div "Goodbye"]) ;;=> Html {s: "Hello
Goodbye
"}
```
--------------------------------
### Initialize a new Expo app
Source: https://github.com/squint-cljs/squint/blob/main/examples/expo-react-native/README.md
Creates a new Expo app named 'expo-react-native'.
```bash
$ npx create-expo-app expo-react-native
```
--------------------------------
### Basic HTML with #html tag
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Use the `#html` tag to produce HTML as strings using hiccup notation. The variable `my-html` is set to an HTML object equal to `Hello
`. Call `str` on it to produce a string.
```clojure
(def my-html #html [:div "Hello"])
```
--------------------------------
### Vite config with optimizeDeps.include
Source: https://github.com/squint-cljs/squint/blob/main/doc/browser-repl.md
Pre-bundles dependencies to avoid REPL state loss on first require. Include deps you use at the REPL.
```javascript
export default defineConfig({
optimizeDeps: {
include: ['preact', 'preact/hooks', 'preact/jsx-runtime', 'preact/jsx-dev-runtime'],
},
plugins: [squint()],
});
```
--------------------------------
### Run squint watcher
Source: https://github.com/squint-cljs/squint/blob/main/examples/expo-react-native/README.md
Runs the squint watcher to compile and hot-reload the project.
```bash
$ npx squint watch
```
--------------------------------
### compileString JS API example
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Imports `compileString` from `squint-cljs` and compiles a Clojure expression to JavaScript, then evaluates it. The `context` option is set to `"expr"` and `elide-imports` to `true`. The compiled function returns 1 when called.
```javascript
import { compileString } from 'squint-cljs';
const f = eval(compileString("(fn [] 1)"
, {"context": "expr",
"elide-imports": true}
));
console.log(f()); // prints 1
```
--------------------------------
### index.html placeholder for injected main entry
Source: https://github.com/squint-cljs/squint/blob/main/doc/browser-repl.md
The plugin injects the compiled `:main` entry as a script into this HTML file. The `#plain` div is where the app renders.
```html
```
--------------------------------
### Anonymous async function with ^:async
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Anonymous functions must have `^:async` on the `fn` symbol or the function's name to use `await`.
```clojure
(^:async fn [] (await {}) 3)
```
--------------------------------
### Arrow function with ^:=> metadata
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Use `^:=>` metadata on a function expression to emit an arrow function `() => ...` instead of a regular `function`. The metadata can be placed on the function expression, `fn` symbol, or argument vector.
```clojure
(fn ^:=> [] 1)
```
--------------------------------
### Hot reload after-load function
Source: https://github.com/squint-cljs/squint/blob/main/doc/browser-repl.md
Function tagged with `^:dev/after-load` runs after hot reload. Use `^:dev/before-load` for pre-reload logic.
```clojure
(defn ^:dev/after-load re-render []
(swap! store identity))
```
--------------------------------
### Require macros from .cljc file in Clojure
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Loads a macro from foo/macros.cljc using :require-macros and invokes it. Requires a squint.edn file with {:paths ["src-squint"]} to locate macro files.
```clojure
(ns foo (:require-macros [foo.macros :refer [my-macro]]))
(my-macro 1 2 3)
```
--------------------------------
### Anonymous generator function with ^:gen
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Anonymous functions must have `^:gen` on the `fn` symbol to use generator features.
```clojure
(^:gen fn [] (js-yield 1) (js-yield 2))
```
--------------------------------
### squint.edn configuration for browser REPL
Source: https://github.com/squint-cljs/squint/blob/main/doc/browser-repl.md
Defines source paths, output directory, extension, and main entry for the squint vite plugin. The `:main` entry is injected by the plugin into `index.html`.
```edn
{:paths ["src"]
:output-dir "js"
:extension "js"
:main plain}
```
--------------------------------
### squint.edn :deps configuration for Replicant
Source: https://github.com/squint-cljs/squint/blob/main/examples/replicant/README.md
Defines the project paths and pulls in Replicant as a git dependency. The :deps key uses the same format as deps.edn; source directories are resolved with the clojure CLI and implicitly added to :paths. Only git and :local/root libraries are supported.
```clojure
{:paths ["src"]
:deps {io.github.cjohansen/replicant {:git/sha ""}}}
```
--------------------------------
### Vite config with sourcemap for production build
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Configure Vite to include source maps in a production build by setting build.sourcemap to true. The plugin's sourceMap option or :source-map in squint.edn overrides this setting.
```js
export default defineConfig({
plugins: [squint()],
build: { sourcemap: true },
});
```
--------------------------------
### Set App.js entry point
Source: https://github.com/squint-cljs/squint/blob/main/examples/expo-react-native/README.md
Replaces the contents of App.js to import the compiled app from './out-js/App'. This is necessary so Expo can see the app entry point.
```js
import App from './out-js/App';
export default App;
```
--------------------------------
### vite.config.js with squint plugin
Source: https://github.com/squint-cljs/squint/blob/main/doc/browser-repl.md
Configures Vite to use the squint plugin for hot reloading and nREPL support. Supports Vite v5-v8.
```javascript
import { defineConfig } from 'vite';
import squint from 'squint-cljs/vite';
export default defineConfig({ plugins: [squint()] });
```
--------------------------------
### Correct CommonJS Import Using $default
Source: https://github.com/squint-cljs/squint/blob/main/examples/ajv/Readme.md
Correct way to import 'ajv-formats' in squint by using the '$default' suffix and :as to access the module's exports.
```cljs
;; correct. note the `$default
(ns ajv (:require ["ajv-formats$default" :as addFormats))
```
--------------------------------
### Dynamic var with binding and set! in Clojure
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Defines a dynamic var *x* with ^:dynamic, reads it in a function, and shows binding and set! behavior. The box object is shared by reference, so binding is visible across separately-compiled ESM modules.
```clojure
(def ^:dynamic *x* 1)
(defn f [] *x*)
(f) ;; => 1
(binding [*x* 2]
(f)) ;; => 2
(set! *x* 3)
(f) ;; => 3
```
--------------------------------
### Compile with source map using npx squint compile --source-map
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Use this command to compile a ClojureScript file and write a .map file next to the compiled output. The --source-map flag is required; squint watch writes source maps by default, but you can disable them with --no-source-map or :source-map false in squint.edn.
```bash
npx squint compile --source-map src/app.cljs
```
--------------------------------
### Clojure expressions inside #jsx
Source: https://github.com/squint-cljs/squint/blob/main/README.md
Clojure expressions can be used within `#jsx` expressions. When inside a Clojure expression, you escape the JSX context, so use `#jsx` again to return more JSX.
```clojure
(let [x 1] #jsx [:div (inc x)])
```
```clojure
(let [x 1]
#jsx [:div
(if (odd? x)
#jsx [:span "Odd"]
#jsx [:span "Even"])])
```
--------------------------------
### squint.edn with JSX runtime for React/Preact
Source: https://github.com/squint-cljs/squint/blob/main/doc/browser-repl.md
Enables JSX support by setting `:jsx-runtime` to emit `jsx()`/`jsxs()` calls. The plugin uses dev runtime under `vite dev` and production runtime for `vite build`.
```edn
{:paths ["src"]
:output-dir "js"
:extension "js"
:main [plain preact reagami-app]
:jsx-runtime {:import-source "preact"}} ; or "react"
```
--------------------------------
### Setup and Animation Loop for Three.js Playground
Source: https://github.com/squint-cljs/squint/blob/main/examples/threejs/playground.html
Initializes a Three.js scene with a points-based sphere, applies post-processing effects (UnrealBloomPass, FilmPass) via an EffectComposer, and runs an animation loop with dat.GUI controls and Stats.js. Uses async script loading for external libraries and a custom easing function for animation.
```clojure
["three/addons/postprocessing/FilmPass.js" :refer [FilmPass]] ["easing$default" :as easing] ["bezier-easing" :as BezierEasing])) (def BezierEasing js/globalThis.BezierEasing) (def Math js/globalThis.Math) (defn ^:async eval-script [url] (let [resp (js-await (js/fetch url)) script (js-await (.text resp))] (js/eval.call js/globalThis script))) (js-await (eval-script "https://unpkg.com/dat.gui@0.7.9/build/dat.gui.js")) (def dat js/globalThis.dat) (js-await (eval-script "https://unpkg.com/stats.js@0.17.0/build/stats.min.js")) (def Stats js/globalThis.Stats) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; controls (def params {:magnitude 0.1 :x-scale 1.0 :y-scale 0.5 :sin-x-scale 0.0 :cos-y-scale 1.0}) (def gui (doto (dat/GUI.) (.add params "magnitude" 0.0 0.5) (.add params "x-scale" 0.0 2.0) (.add params "y-scale" 0.0 2.0) (.add params "sin-x-scale" 0.0 2.0) (.add params "cos-y-scale" 0.0 2.0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; basic three.js setup (def scene (three/Scene.)) (def origin (three/Vector3.)) (def height (/ (.-innerHeight js/window) 2)) (def width (min (* 2 height) (.-innerWidth js/window))) (def camera (doto (three/PerspectiveCamera. 75 (/ width height) 0.1 1000) (-> :position ((fn [pos] (.set pos 0 0 70)))) (.lookAt origin))) (def renderer (doto (three/WebGLRenderer. (clj->js {:antialias true})) (.setPixelRatio (.-devicePixelRatio js/window)) (.setSize width height) (-> (assoc! :toneMapping three/ReinhardToneMapping :toneMappingExposure (Math/pow 1.4 5.0)) (-> :domElement js/document.body.prepend)))) ;; effects composer for after effects (def composer (let [w (get js/window :innerWidth) h (get js/window :innerHeight)] (doto (EffectComposer. renderer) (.addPass (RenderPass. scene camera)) (.addPass (UnrealBloomPass. (three/Vector2. w h) ; viewport resolution 0.3 ; strength 0.2 ; radius 0.8)) ; threshold (.addPass (assoc! (FilmPass. 0.25 ; noise intensity 0.26 ; scanline intensity 648 ; scanline count false); grayscale :renderToScreen true))))) ;; animation helpers (def current-frame (atom 0)) (def linear (easing 76 "linear" {:endToEnd true})) (def bezier (mapv (BezierEasing. 0.74 -0.01 0.21 0.99) (range 0 1 (/ 1.0 76)))) (defn fix-zero [n] (if (zero? n) 1 n)) (def mesh (let [m (three/Points. (three/SphereGeometry. 11 64 64) (three/PointsMaterial. {:vertexColors true :size 0.7 :transparent true :alphaTest 0.5 :blending three/AdditiveBlending}))] (.add scene m) m)) (defn render [] (let [num-frames 76] (swap! current-frame #(mod (inc %) num-frames)) (let [sphere (three/SphereGeometry. 11 64 64) sphere-verts (.getAttribute sphere "position") points (mapv #(let [sv (.fromBufferAttribute (three/Vector3.) sphere-verts %)] (.addScaledVector sv sv (* (:magnitude params) (fix-zero (* (:x-scale params) (.-x sv))) (fix-zero (* (:y-scale params) (.-y sv))) (fix-zero (* (:sin-x-scale params) (Math/sin (.-x sv)))) (fix-zero (* (:cos-y-scale params) (Math/cos (.-y sv)))) (nth linear @current-frame)))) (range (:count sphere-verts))) dists (mapv #(.distanceTo origin %) points) min-dist (apply min dists) max-dist (- (apply max dists) min-dist)] (doto (.-geometry mesh) (.setFromPoints points) (.setAttribute "color" (three/Float32BufferAttribute. (mapcat #(let [c (three/Color.)] ;; mutate the color object and return the resulting RGB values (.setHSL c (+ 0.3 (* 0.5 (max (min 1.0 (/ (- (get dists %) min-dist) max-dist)) 0))) 0.8 0.2) [(.-r c) (.-g c) (.-b c)]) (range (:count sphere-verts))) 3)))) (squint/assoc-in! mesh [:rotation :y] (* 1.5 Math/PI (nth bezier @current-frame)))) (.render composer (nth bezier @current-frame))) ; render from the effects composer (defn animate [s] (.begin s) (render) (.end s) (.requestAnimationFrame js/window #(animate s))) (defn ^:async init [] (let [s (Stats.
```
--------------------------------
### Incorrect CommonJS Import of ajv-formats
Source: https://github.com/squint-cljs/squint/blob/main/examples/ajv/Readme.md
Shows an incorrect import of 'ajv-formats' using a named export, which fails because the module is CommonJS and does not support named exports. The error suggests using the default export instead.
```cljs
(ns ajv (:require ["ajv-formats" :refer [addFormats]]))
```
```text
;; [squint] Running ajv.cljs
;; file:///Users/zcpowers/Documents/Projects/squint/examples/ajv/ajv.mjs:3
;; import { addFormats } from 'ajv-formats';
;; ^^^^^^^^^^
;; SyntaxError: Named export 'addFormats' not found. The requested module 'ajv-formats' is a CommonJS module, which may not support all module.exports as named exports.
;; CommonJS modules can always be imported via the default export, for example using:
;;
;; import pkg from 'ajv-formats';
;; const { addFormats } = pkg;
```
--------------------------------
### Shift segments with sm/shift-segments
Source: https://github.com/squint-cljs/squint/blob/main/doc/source-maps.md
Use `shift-segments` to move segments past the text that precedes their JavaScript. The example shifts `[[0 0 0 0]]` by `"var x = 1;\n"` and returns `[[1 0 0 0]]`.
```clojure
(sm/shift-segments [[0 0 0 0]] "var x = 1;\n")
;;=> [[1 0 0 0]]
```
--------------------------------
### Run script with QuickJS
Source: https://github.com/squint-cljs/squint/blob/main/examples/quickjs/README.md
Executes the bundled script using the qjs command. Output shows 'Hello world!' and the transposed matrix result.
```bash
$ qjs main.min.mjs
Hello world!
[[1,4,7],[2,5,8],[3,6,9]]
```
--------------------------------
### Create standalone executable with qjsc
Source: https://github.com/squint-cljs/squint/blob/main/examples/quickjs/README.md
Compiles the bundled script into a standalone executable named 'hello' using qjsc.
```bash
$ qjsc -o hello main.min.mjs
```
--------------------------------
### Execute standalone executable
Source: https://github.com/squint-cljs/squint/blob/main/examples/quickjs/README.md
Runs the standalone executable 'hello'. Output matches the QuickJS run. The executable is about 750kb.
```bash
$ ./hello
Hello world!
[[1,4,7],[2,5,8],[3,6,9]]
```
--------------------------------
### Bundle main.mjs with esbuild
Source: https://github.com/squint-cljs/squint/blob/main/examples/quickjs/README.md
Bundles the compiled main.mjs into a minified ESM file main.min.mjs for QuickJS, since QuickJS doesn't load NPM dependencies. Output shows bundle size and completion.
```bash
$ npx esbuild main.mjs --bundle --minify --platform=node --outfile=main.min.mjs --format=esm
main.min.mjs 842b
⚡ Done in 11ms
```
--------------------------------
### Compile main.cljs with ClavaScript
Source: https://github.com/squint-cljs/squint/blob/main/examples/quickjs/README.md
Compiles the main.cljs script to main.mjs using ClavaScript. Output shows the compilation messages.
```bash
$ npx clava main.cljs
[clava] Compiling CLJS file: main.cljs
[clava] Wrote JS file: main.mjs
```
--------------------------------
### EncMap class: native Map keyed on encoded string
Source: https://github.com/squint-cljs/squint/blob/main/doc/dev/composite-map-keys.md
Map backed by native `Map` keyed on the encoded string, storing `[origKey, val]` so iteration roundtrips without decoding. Constructor accepts an optional encoder function (defaults to `encKey`). Methods: `set`, `get`, `has`, and a generator `keys` that yields original keys.
```javascript
class EncMap {
constructor(enc) { this.m = new Map(); this.enc = enc || encKey; }
set(k, v) { this.m.set(this.enc(k), [k, v]); return this; }
get(k) { const e = this.m.get(this.enc(k)); return e === undefined ? undefined : e[1]; }
has(k) { return this.m.has(this.enc(k)); }
*keys() { for (const e of this.m.values()) yield e[0]; }
}
```
--------------------------------
### Variadic fn compilation with native rest and apply hint
Source: https://github.com/squint-cljs/squint/blob/main/doc/ai/adr/0001-variadic-fn-native-rest.md
Shows the compiled output for a variadic function: a facade using native rest params delegates to an impl, and the impl is stored under the string property 'squint$lang$variadic' as the apply hint. Direct calls avoid 'arguments' and are self-contained; apply uses the hint to pass the rest as an unrealized seq.
```javascript
var foo = /* @__PURE__ */ (() => {
const impl = function (x, xs) { ... }; // body; xs is a seq/array
const foo = function (x, ...xs) { // facade: native rest
return impl(x, xs.length === 0 ? null : xs); // empty rest -> nil
};
foo["squint$lang$variadic"] = impl; // the apply hint
return foo;
})();
```
--------------------------------
### Multi-arity fn compilation with variadic arity and apply hint
Source: https://github.com/squint-cljs/squint/blob/main/doc/ai/adr/0001-variadic-fn-native-rest.md
Shows the compiled output for a multi-arity function: each arity has its own impl, a facade switches on args.length and passes raw args, and the variadic arity (if any) is stored under 'squint$lang$variadic'. The facade must pass raw params to the impl to avoid destructuring forms being emitted as literals.
```javascript
var foo = /* @__PURE__ */ (() => {
const impl1 = function (a) { ... };
const impl2 = function (a, b) { ... };
const implV = function (a, b, r) { ... }; // r is a seq
const foo = function (...args) {
switch (args.length) {
case 1: return impl1(args[0]);
case 2: return impl2(args[0], args[1]);
default: { const rest = args.slice(2);
return implV(args[0], args[1], rest.length === 0 ? null : rest); }
}
};
foo["squint$lang$variadic"] = implV; // only if a variadic arity
return foo;
})();
```
--------------------------------
### AOC 2017 Day 2 solution in ClojureScript
Source: https://github.com/squint-cljs/squint/blob/main/examples/aoc/solutions.md
Interactive solution for Advent of Code 2017 Day 2 using squint. Includes helper functions fetch-input, append, and spy. Defines input parsing, line-nums, solve1, and solve2. solve1 computes sum of max-min per line; solve2 computes sum of even division results.
```clojure
;; Helper functions:
;; (fetch-input year day) - get AOC input
;; (append str) - append str to DOM
;; (spy x) - log x to console and return x
(comment
(warn-on-lazy-reusage!)
)
(def input (->> (js-await (fetch-input 2017 2))
#_spy
str/trim
str/split-lines))
(defn- line-nums [line]
(js/JSON.parse (str "[" (str/replace line "\t" ",") "]")))
(comment
(line-nums (first input))
)
(defn solve1 [lines]
(letfn [(line-diff [line]
(->> (line-nums line)
spy
((juxt #(apply max %) #(apply min %)))
(apply -)))]
(transduce (map line-diff) + 0 lines)))
(comment
(solve1 input)
)
(defn solve2 [lines]
(letfn [(line-div [line]
(first
(for [[x & ys] (->> (line-nums line)
(iterate (comp vec rest)))
y ys
:when (or (zero? (mod x y))
(zero? (mod y x)))]
(/ (max x y) (min x y)))))]
(transduce (map line-div) + 0 lines)))
(comment
(solve2 input)
)
```
--------------------------------
### Day 12 solution (squint CLJS)
Source: https://github.com/squint-cljs/squint/blob/main/examples/aoc/solutions.md
Solution for Advent of Code 2023 day 12, using helper functions fetch-input, append, and spy. Original solution by @alexyakushev. Includes commented-out calls to solve for parts 1 and 2.
```clojure
;; Helper functions:
;; (fetch-input year day) - get AOC input
;; (append str) - append str to DOM
;; (spy x) - log x to console and return x
;; original solution by @alexyakushev
;; Remember to update the year and day in the fetch-input call.
(def lines (->> (js-await (fetch-input 2023 12))
str/split-lines))
(defn parse [task]
(vec (for [line lines]
(let [[field hints] (str/split line #" ")]
(case task
1 [(str "." field ".") (map parse-long (str/split hints #","))]
2 [(str "." (str/join "?" (repeat 5 field)) ".")
(into [] (apply concat (repeat 5 (map parse-long (str/split hints #",")))))]))))
(defn variants [[[String field hints]]]
(let [cache {}]
(letfn [(f [i j start c]
(let [key (+ (* 10000 i) j)]
(or (and (nil? c) (nil? start) (get cache key))
(let [c (or c (when (< i (.length field))
(.charAt field i)))]
(if-not c (if (= j (count hints)) 1 0)
(case c
\. (if start
(let [len (- i start)]
(if (= len (nth hints j nil))
(recur (inc i) (inc j) nil nil)
0))
(recur (inc i) j nil nil))
\# (recur (inc i) j (or start i) nil)
\? (let [res (+ (f i j start \.)
(f i j start \#))]
(when (nil? start)
(assoc! cache key res))
res))))))]
(f 0 0 nil nil))))
(defn solve [task]
(time (reduce + (map variants (parse task)))))
#_(solve 1)
#_(solve 2)
```
--------------------------------
### Day 18 Part 1 solution using shoelace formula
Source: https://github.com/squint-cljs/squint/blob/main/examples/aoc/solutions.md
Solves Day 18 Part 1 by parsing instructions, computing polygon points, and applying the shoelace formula. Uses helper functions fetch-input, append, and spy. The solution is based on an original Clojure solution linked in the comments.
```clojure
;; Helper functions:
;; (fetch-input year day) - get AOC input
;; (append str) - append str to DOM
;; (spy x) - log x to console and return x
;; original solution:
;; https://github.com/rjray/advent-2023-clojure/blob/master/src/advent_of_code/day18.clj
;; Remember to update the year and day in the fetch-input call.
(def input (js-await (fetch-input 2023 18)))
(def delta {:U [-1 0] :R [0 1] :D [1 0] :L [0 -1]})
;; Parse an instruction line into a tuple of (direction, steps, color).
(defn- parse-inst [line]
(let [[[_ dir len color] (re-matches #"^([URDL]) (\d+) \\(#([0-9a-f]{6})\\)"
line)]
(list dir (parse-long len) color)))
;; Do the "shoelace" calculation.
(defn- shoelace [[[y1 x1] [y2 x2]]]
(- (* x1 y2) (* y1 x2)))
;; Do the full calculation. Use overlapping partitioning to iterate calls to
;; `shoelace` over adjacent pairs. Then add in a call between the last and first
;; points.
(defn- calculate [points]
(+ (shoelace (list (last points) (first points)))
(reduce + (map shoelace (partition 2 1 points)))))
;; Find the points that describe the polygons, based on the list of instructions
;; given. Once all are found, call `calculate` and apply the last bit of math
;; to get the answer.
(defn- solve [insts]
(loop [[inst & insts] insts,poly (list [0 0]),p_cnt 0]
(if (nil? inst)
(inc (quot (+ (calculate (reverse poly))) p_cnt) 2))
(let [[dir len] inst
lp (first poly)
newpos (mapv + lp (mapv * [len len] (get delta dir)))]
(recur insts (cons newpos poly) (+ p_cnt len))))))
(defn part-1
"Day 18 Part 1"
[input]
(->> input
str/split-lines
(mapv parse-inst)
solve))
(comment
(part-1 input)
)
```
--------------------------------
### 2017 Day 6: Solve with state tracking
Source: https://github.com/squint-cljs/squint/blob/main/examples/aoc/solutions.md
Solves Advent of Code 2017 day 6 by simulating redistribution of memory blocks. Uses a map keyed by state strings to detect cycles. The solution returns the number of steps until a repeated state is found.
```clojure
(require '[clojure.string :as str])
(def input (str/trim "4\t1\t15\t12\t0\t9\t9\t5\t5\t8\t7\t3\t14\t5\t12\t3\n"))
(defn data []
(as-> input $
(str/split $ #"\s")
(mapv parse-long $)))
(defn first-max-pos
[nums]
(reduce (fn [[_ max-val :as m]
[_ cur-val :as c]]
(if (> cur-val max-val)
c m))
(map vector (range) nums)))
(defn next-pos
[state cur-pos]
(mod (inc cur-pos) (count state)))
(defn next-state
[state]
(let [[[max-pos max-val] (first-max-pos state)
dist-size (->
(/ max-val (count state))
(js/Math.ceil))]
(loop [state state
pos (next-pos state max-pos)]
(let [left (get state max-pos)]
(if (or
(zero? left)
(= pos max-pos))
state
(recur
(->
state
(update pos + dist-size)
(update max-pos - dist-size))
(next-pos state pos)))))))
(defn state-key [state]
(str/join "," state))
(defn solve
[data]
(loop [;; we store arrays by key of string representation since objects work only
;; with string keys
states {(state-key data) data}
state data
n 1]
(let [state' (next-state state)
k (state-key state')]
(if (contains? states k)
[state' n]
;; we use assoc! because this is much faster than deep-cloning
;; thousands of kvs and the states object isn't shared anywhere else
(recur (assoc! states k state')
state'
(inc n))))))
(defn solve-1 []
(second (solve (data))))
(defn solve-2 []
(second (solve (first (solve (data))))))
(comment
(time (solve-1))
(time (solve-2))
)
```
--------------------------------
### Day 9 solution by bhauman
Source: https://github.com/squint-cljs/squint/blob/main/examples/aoc/solutions.md
Alternative 2023 day 9 solution by bhauman. Parses input with JSON.parse, computes differences, and uses next-num/prev-num for part 1 and part 2. Includes commented debug calls.
```clojure
;; Helper functions:
;; (fetch-input year day) - get AOC input
;; (append str) - append str to DOM
;; (spy x) - log x to console and return x
;; Solution by bhauman:
;; https://github.com/bhauman/adv2023/blob/main/src/adv2023/day09/sol.clj
(def input
(->> (js-await (fetch-input 2023 9))
(str/split-lines)
(map #(as-> % x
(str "[" x "]")
(str/replace x " " ",")
(js/JSON.parse x)))))
(defn diffs [l]
(->> l (partition 2 1) (mapv #(apply - (reverse %)))))
(defn next-num [num-seq]
(let [ds (diffs num-seq)
(if (every? zero? ds)
(last num-seq)
(+ (last num-seq)
(next-num ds)))))
;; part 1
(comment
(reduce + (map next-num input))
)
(defn prev-num [num-seq]
(let [ds (diffs num-seq)
(if (every? zero? ds)
(first num-seq)
(- (first num-seq)
(prev-num ds)))))
;; part 2
(comment
(reduce + (map prev-num input))
)
```
--------------------------------
### Define JavaScript classes with defclass
Source: https://github.com/squint-cljs/squint/blob/main/doc/defclass.md
Shows the defclass syntax for defining JavaScript classes in squint, including fields, static fields, constructors, methods, static methods, extends, super calls, async methods, getters/setters, and toString. Requires squint v0.1.15+ and importing defclass from squint.core.
```clojure
(ns my-class
(:require [squint.core :refer [defclass]]))
(defclass class-1
(field -x)
(field -y :dude) ;; default
(^:static field a)
(^:static field b :dude) ;; default
(constructor [this x] (set! -x x))
Object
(get-name-separator [_] (str "-" -x))
(^:static static-method [_] (str "static field: " a)))
(defclass Class2
(extends class-1)
(field -y 1)
(constructor [_ x y]
(super (+ x y)))
Object
(dude [_]
(str -y (super.get-name-separator)))
(^:async fetch [_]
(js/fetch "https://clojure.org"))
(^:get doubled [_] (* 2 -y))
(^:set doubled [_ v] (set! -y (/ v 2)))
(toString [this] (str "<<<<" (.dude this) ">>>>") ))
(def c (new Class2 1 2))
```