<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by samarjit.samanta on Medium]]></title>
        <description><![CDATA[Stories by samarjit.samanta on Medium]]></description>
        <link>https://medium.com/@samarjit-samanta?source=rss-a6779649b7fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3LyY21ZP8iY4sLLL.jpg</url>
            <title>Stories by samarjit.samanta on Medium</title>
            <link>https://medium.com/@samarjit-samanta?source=rss-a6779649b7fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:20:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samarjit-samanta/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[koa-router schema validation and swagger api doc generation]]></title>
            <link>https://samarjit-samanta.medium.com/koa-router-schema-validation-and-swagger-api-doc-generation-1d2c20a1824b?source=rss-a6779649b7fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d2c20a1824b</guid>
            <category><![CDATA[koa-router]]></category>
            <category><![CDATA[ajv]]></category>
            <category><![CDATA[json-schema]]></category>
            <category><![CDATA[json-schema-validator]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[samarjit.samanta]]></dc:creator>
            <pubDate>Thu, 17 Sep 2020 05:24:08 GMT</pubDate>
            <atom:updated>2020-09-17T05:24:08.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0sEalY854OQhkFeM31Kfg.gif" /></figure><p>lib: koa-router-ajv-swaggergen (woah such a big name)</p><p>Koa is a webframework very similar to expressjs. Its not a complete webframework rather a middleware framework as it allows writing middlewares easily in async way. Now that means you need a lot of plumbing to make it useful. But either way you will start off by selecting a router module of which there are many. Very soon you will realize that you need to write input validations, and eventually in a distributed team some sort of document to maintain apis and there are many more of this libs. Well granted you will need many more things to get going like authentication authorization, perhaps distributed logging, security. These are all independent libs that may require pick and choose approach. If you want everything baked in the framework, choose fastify or hapi and be happy about it. Now I like koa’s middleware framework and its flexibility.</p><p>To make things simpler lets first focus on sticking with the @koa/router, lets not rebuild yet another routers that does only ‘X’. This module does 3 things. This does not reimplement koa-router instead creates wrapper around koa-router (@koa/router). The lib might also support other routers out-of-box or with little tweak. (Feel free to fork :))</p><p>Now that we have got the router, we need to be able to support validation, and for lazy people like me I like to define a schema and get majority of the validation done through json schema. I have chosen <a href="https://ajv.js.org/">ajv</a>. Now that we have the schema, so the api doc can be derived from this schema. Before creating this lib, I started out writing jsdoc comments to generates swagger, not bad approach but it poses another burden of keeping jsdoc in sync to schema. Annotations aka decorators to create swagger doc has the same problem too, they are not directly linked to schema.</p><blockquote>Thanks to fastify-swagger, fastify-oas, koa-mapper, koa-joi-swagger for inspiration.</blockquote><ol><li>Define schema while defining router</li><li>Schema will be used for validation of queryparams, headers, pathparams, request body.</li><li>Schema will be used for generating openapi 3 json.</li></ol><p>You can open this openapi3 json in <a href="http://editor.swagger.io/">http://editor.swagger.io</a> to view the document. Optionally you can integrate swagger viewer in your application. Follow the index.js to see how it is done. Following snippet shows the main parts.</p><h3>Quick start Example</h3><p>npm install koa-router-ajv-swaggergen in your project. Additionally if want to setup swagger viewer npm install -D swagger-ui-dist</p><pre>const Koa = require(&#39;koa&#39;)<br>const Router = require(&#39;@koa/router&#39;);<br>const Myrouter = require(&#39;koa-router-ajv-swaggergen&#39;);<br>const router = new Myrouter(new Router(), &#39;prefix&#39;);</pre><pre>const app = new Koa();</pre><pre>// // requires `npm install -D swagger-ui-dist` to run swagger ui locally, otherwise comment this line<br>// Myrouter.setupSwaggerUI(router, &#39;prefix&#39;);</pre><pre>// // pass &#39;router&#39; for json error response for this router, or pass &#39;app&#39; for all errors to be converted to json<br>// Myrouter.setupJsonErrors(router); </pre><pre>router.get(&#39;/&#39;,<br>  {<br>    schema: {<br>      summary: &#39;Minimal example&#39;,<br>      description: &#39;This is a minimal setup&#39;,<br>      querystring: {<br>        type: &#39;object&#39;,<br>        required: [&#39;name&#39;],<br>        properties: {<br>          name: { type: &#39;string&#39; },<br>          excitement: { type: &#39;integer&#39; }<br>        }<br>      },<br>      response: {<br>        200: {<br>          type: &#39;object&#39;,<br>          properties: {<br>            hello: { type: &#39;string&#39; }<br>          }<br>        }<br>      }<br>    }<br>  },<br>  (ctx) =&gt; {<br>    console.log(&#39;reqId&#39;, ctx.query.name);<br>    ctx.body = { hello: ctx.query.name, excitement:  ctx.query.excitement};<br>  }<br>);</pre><pre>app.use(router.routes());</pre><pre>app.listen(3000, () =&gt; {<br>  console.log(`server listening on 3000`)<br>})</pre><p>Open browser <a href="http://localhost:3000/prefix/openapi.json">http://localhost:3000/prefix/openapi.json</a> If you have setup swagger ui viewer open in browser <a href="http://localhost:3000/swagger">http://localhost:3000/swagger</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*JrDJc-tH6ZDKJtTx.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*CGdW11RuRbW8LgB3.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*AYIgVcyzQubp_Ca-.jpg" /></figure><h3>Some more details</h3><pre>const Router = require(&#39;@koa/router&#39;);<br>const Myrouter = require(&#39;../../routerwrapper&#39;);<br>const router = new Myrouter(new Router(), &#39;prefix&#39;); // prefix is required to access different routes</pre><p>Now you can use the router object like you would use koa-router i.e. even without a schema. But you can add schema which will start showing this route in swagger json and do schema validation.</p><pre>router.get(&#39;/auth/get-user-profile&#39;, {<br>    schema: {<br>        querystring: {<br>            username: { type: &#39;string&#39; }<br>        },<br>        responses: {<br>            &#39;200&#39;: {<br>                description: &#39;returns user details or redirect url /auth/login if not logged in&#39;<br>            },<br>        }<br>    }<br>}, async (ctx) =&gt; {<br>  ctx.body = &#39;&#39;;<br>})</pre><p>Now the apidoc json is available at <a href="http://localhost/">http://localhost</a>:/prefix.openapi.json. You can have other router instances wrapped with a different prefix, and those will be available <a href="http://localhost/">http://localhost</a>:/anotherprefix.openapi.json.</p><h3>Reusable schema</h3><p>You can register schema globally in the router and reuse it in multiple routes</p><pre>router.addSchema(&#39;commonSchema&#39;, {<br>  type: &#39;object&#39;,<br>  properties: {<br>    hello: { type: &#39;string&#39; }<br>  }<br>})</pre><pre>router.post(&#39;/&#39;, {<br>  schema: {<br>    body: { $ref: &#39;#/components/schemas/commonSchema&#39; },<br>    headers: { $ref: &#39;#/components/schemas/commonSchema&#39; }<br>  }<br>}, (ctx) =&gt; { ctx.body = &#39;post /&#39;; })</pre><h3>Validation</h3><p>A more complete example, in fact this is directly taken from fastify-swagger documentation. Note the querystring and pathparams objects can be simplified as in this example. But if you need to control required then expanded format will need to be defined.</p><pre>const bodyJsonSchema = {<br>  type: &#39;object&#39;,<br>  required: [&#39;requiredKey&#39;],<br>  properties: {<br>    someKey: { type: &#39;string&#39; },<br>    someOtherKey: { type: &#39;number&#39; },<br>    requiredKey: {<br>      type: &#39;array&#39;,<br>      maxItems: 3,<br>      items: { type: &#39;integer&#39; }<br>    },<br>    nullableKey: { type: [&#39;number&#39;, &#39;null&#39;] }, // or { type: &#39;number&#39;, nullable: true }<br>    multipleTypesKey: { type: [&#39;boolean&#39;, &#39;number&#39;] },<br>    multipleRestrictedTypesKey: {<br>      oneOf: [<br>        { type: &#39;string&#39;, maxLength: 5 },<br>        { type: &#39;number&#39;, minimum: 10 }<br>      ]<br>    },<br>    enumKey: {<br>      type: &#39;string&#39;,<br>      enum: [&#39;John&#39;, &#39;Foo&#39;]<br>    },<br>    notTypeKey: {<br>      not: { type: &#39;array&#39; }<br>    }<br>  }<br>}</pre><pre>// This is less verbose way of defining schema which works for querystring and params <br>// You can choose more verbose way of defining schema in the ajv way<br>const queryStringJsonSchema = {<br>  name: { type: &#39;string&#39; }, // add required: true if you want to make it required<br>  excitement: { type: &#39;boolean&#39; } // query strings are normally strings but it is coerced to boolean and then validated<br>}</pre><pre>const paramsJsonSchema = {<br>  par1: { type: &#39;string&#39; },<br>  par2: { type: &#39;number&#39; }<br>}</pre><pre>const headersJsonSchema = {<br>  type: &#39;object&#39;,<br>  properties: {<br>    &#39;x-foo&#39;: { type: &#39;string&#39; }<br>  },<br>  required: [&#39;x-foo&#39;]<br>}</pre><pre>const schema = {<br>  body: bodyJsonSchema,<br>  querystring: queryStringJsonSchema,<br>  params: paramsJsonSchema,<br>  headers: headersJsonSchema<br>}</pre><pre>router.post(&#39;/the/url/:par1/:par2&#39;, { schema }, (ctx) =&gt; {<br>  ctx.body = &#39;post /the/url&#39;;<br>})</pre><h3>Integrating swagger viewer</h3><p>Integrating swagger viewer is trivial. Get the static distribution instead of serving static directory from node_modules, serve it and rewrite content as required. I found this is the easiest way to mount into a different directory other than root. Swagger js and css’es do not understand relative paths</p><pre>npm install -D swagger-ui-dist</pre><p>Easy way is to use a provided helper method. Myrouter.setupSwaggerUI(router, &#39;prefix&#39;);</p><p>Here is what this helper function essentially does.</p><pre>const swaggerUiAssetPath = require(&quot;swagger-ui-dist&quot;).getAbsoluteFSPath();<br>// Mount in your favourite path eg. &#39;/swagger&#39;<br>router.get(&#39;/swagger&#39;, ctx =&gt; {<br>  ctx.type = &#39;html&#39;;<br>  let fileAsString = fs.readFileSync(`${swaggerUiAssetPath}/index.html`);//<br>  ctx.body = String(fileAsString).replace(/url\: \&quot;https.*/m, `url: &quot;prefix/openapi.json&quot;,`);<br>});<br>// Following static assets do not recognize relative paths.<br>router.get(&#39;/swagger-ui.css&#39;, ctx =&gt; {<br>  ctx.type = &quot;text/css&quot;<br>  ctx.body = fs.createReadStream(`${swaggerUiAssetPath}/swagger-ui.css`);<br>});<br>router.get(&#39;/swagger-ui-bundle.js&#39;, ctx =&gt; {<br>  ctx.type = &quot;application/javascript&quot;<br>  ctx.body = fs.createReadStream(`${swaggerUiAssetPath}/swagger-ui-bundle.js`);<br>});<br>router.get(&#39;/swagger-ui-standalone-preset.js&#39;, ctx =&gt; {<br>  ctx.type = &quot;application/javascript&quot;<br>  ctx.body = fs.createReadStream(`${swaggerUiAssetPath}/swagger-ui-standalone-preset.js`);<br>});</pre><h3>For developers of this library</h3><p>Git clone the repository. Run npm install You run the node src\index-test.js or simply run npm run dev. It has a few samples to get started. Open browser at <a href="http://localhost:3000/swagger">http://localhost:3000/swagger</a></p><h3>Conclusion</h3><p>This library is very new, it does have some shortcomings like schema may not be fully compliant with openapi3 specs. Local swagger viewer is more forgiving and does not complain. There are no tests yet. I just carved out a part of my other project into this library. So, I am going to fix any major defects. PRs are also welcome <a href="https://github.com/samarjit/koa-router-ajv-swaggergen">https://github.com/samarjit/koa-router-ajv-swaggergen</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d2c20a1824b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with reactjs with Snowpack or vitejs]]></title>
            <link>https://samarjit-samanta.medium.com/getting-started-with-reactjs-with-snowpack-or-vitejs-a091491b541e?source=rss-a6779649b7fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a091491b541e</guid>
            <dc:creator><![CDATA[samarjit.samanta]]></dc:creator>
            <pubDate>Tue, 18 Aug 2020 06:14:08 GMT</pubDate>
            <atom:updated>2020-08-18T18:35:02.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pAGe2Zck2VqeFUUc" /><figcaption>Photo by <a href="https://unsplash.com/@wolfehausdesign?utm_source=medium&amp;utm_medium=referral">Nathan Wolfe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Snowpack is a tool to convert non module code into module format. It also has little dev server which serves the es6 modules (aka esm, es modules) that can be consumed by browser using import X from Ystatements.</p><p>The other reason to write this article is to delve deep into configuration so that we do not have to use babel compiler with snowpack. This is the only difference from the official snowpack template project for react.</p><p>Finally we will configure postcss for scss compilation.</p><h4>How is snowpack different from webpack?</h4><p>In reality not all that much different. webpack with 900 npm packages try to bundle (concatenate) all js files into 1 bundle.js file, without which browsers will be expecting you to write 100s of&lt;script&gt; tags for each and every the js files of your project in order to load them into client’s browser. Yay! webpack enables only one &lt;script&gt; tag line in your index.html. With snowpack its just 197 npm packages 👍, it does NOT even bundle all js files into 1 js file, but you have to write only one &lt;script&gt; tag just like webpack to import the index.js file in index.html, yay!!. Wait, how does the remaining files reach client’s browser? Glad you asked. Thanks to js modules, browsers are now smart enough to understand the import statements and fetch those files dynamically into the browser. Downside is your browser makes 100s of http calls to download all those files, unless you have heard of HTTP/2 etc. To overcome this snowpack encourages you to use webpack for production builds 🤪.</p><h4>How is vite different from snowpack?</h4><p>For me they are very similar. Snowpack does little bit more like converting normal react.js library into esm module and put it in web_modules folder. Vite expects a react.js esm module to begin with, so in package.json you will see “@pika/react”: “16.13.1”.</p><h3>Esbuild</h3><p>ESbuild is the compiler used by snowpack. Interestingly esbuild can compile jsx, yay! no need for babel with all the jsx transpiler configurations.</p><p>Lets see</p><pre><strong>snop/src/reactesbuildtest.jsx</strong><br>import React from &quot;react&quot;;<br>const App = () =&gt; &lt;div className=&quot;app&quot;&gt;hello world&lt;/div&gt;;</pre><pre>export default App;</pre><p><strong>snop&gt;</strong>node_modules\.bin\esbuild src\reactesbuildtest.jsx --outdir=build</p><pre><strong>output: snop/build/reactesbuildtest.js</strong><br>import React from &quot;react&quot;;</pre><pre>const App = () =&gt; /* @__PURE__ */ React.createElement(&quot;div&quot;, {<br>className: &quot;app&quot;<br>}, &quot;hello world&quot;);</pre><pre>export default App;</pre><p>Looks cool? It is not very powerful through, like if you are trying to import import &#39;./App.css&#39;; It wont work. Possibly importing other stuff like svg etc wont work either. This is where different loaders are required to deal with certain file types to convert them into javascript which then can be imported. Even webpack calls them loaders ‘style-loader’, ‘css-loader’ those kind of things. Some of these loaders are provided by snowpack eg the css loader, others can be added up through plugins like scss/sass files can be loaded using postcss.</p><h3>Snowpack</h3><p>Lets start creating a basic application. Start by creating the package.json as below. You can skip esbuild as it is a transitive dependency of snowpack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*hiGGiNiIcBfoE9bbMQTuZw.png" /><figcaption>folder structure</figcaption></figure><pre><strong>snop/package.json</strong><br>{<br>&quot;name&quot;: &quot;snowpack-sample&quot;,<br>&quot;scripts&quot;: {<br> &quot;start&quot;: &quot;snowpack dev&quot;,<br> &quot;build&quot;: &quot;snowpack build&quot;<br>},<br>&quot;dependencies&quot;: {<br>  &quot;react&quot;: &quot;^16.13.0&quot;,<br>  &quot;react-dom&quot;: &quot;^16.13.0&quot;<br>},<br>&quot;devDependencies&quot;: {<br>  &quot;esbuild&quot;: &quot;^0.6.25&quot;,<br>  &quot;snowpack&quot;: &quot;^2.6.4&quot;<br> }<br>}</pre><p>After you run npm install. You will get 197 node packages installed.</p><p>Lets quickly create the jsx files.</p><pre><strong>snop/src/index.jsx (Note the jsx extension, otherwise esbuild will not interpret jsx syntax)</strong></pre><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import App from &#39;./App&#39;;<br>import &#39;./index.css&#39;;</pre><pre>ReactDOM.render(&lt;App /&gt;, document.getElementById(&#39;root&#39;));</pre><pre>// Hot Module Replacement (HMR) - Remove this snippet to remove HMR.<br>// Learn more: <a href="https://www.snowpack.dev/#hot-module-replacement">https://www.snowpack.dev/#hot-module-replacement</a><br>if (import.meta.hot) {<br>  import.meta.hot.accept();<br>}</pre><pre><strong>snop/src/App.jsx (Regular react)</strong><br>import React, { useState } from &#39;react&#39;;<br>import logo from &#39;./logo.svg&#39;;<br>import &#39;./App.css&#39;;</pre><pre>function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>    &lt;img src={logo} className=&quot;App-logo&quot; width=&quot;400px&quot;/&gt; &lt;br/&gt;<br>Hello World - Hot module replacement is enabled<br>    &lt;/div&gt;<br>  )<br>}<br>export default App;</pre><pre>App.css // You can add your own css<br>logo.svg // You can add your own svg</pre><p>Next you can created snowpack.config.js. This is very basic without any plugins. There is a lot of documentation about what each of these mount commands means in snowpack website.</p><pre><strong>snop/src/snowpack.config.js for snowpack@2.6.4</strong><br>module.exports = {<br>  &quot;scripts&quot;: {<br>    &quot;mount:public&quot;: &quot;mount public --to /&quot;,<br>    &quot;mount:src&quot;: &quot;mount src --to /_dist_&quot;,<br>    &quot;mount:web_modules&quot;: &quot;mount $WEB_MODULES --to /web_modules&quot;,<br>  },<br>  &quot;plugins&quot;: []<br>}</pre><pre><strong>Running cmd<br>$npm run build</strong></pre><pre>Snowpack</pre><pre>.\build Building your application...</pre><pre>  mount:public............[DONE] mount public --to /<br>  mount:src...............[DONE] mount src --to /_dist_<br>  build:<strong>.js,.jsx,.ts,.tsx</strong>.[DONE] (default) <strong>esbuild</strong><br>  bundle:*................[SKIP]</pre><pre>▼ bundle:*</pre><pre>&quot;plugins&quot;: [&quot;<a href="http://twitter.com/snowpack/plugin-webpack">@snowpack/plugin-webpack</a>&quot;]</pre><pre>Connect a bundler plugin to optimize your build for production.<br>  Set &quot;devOptions.bundle&quot; configuration to false to remove this message.</pre><pre>▼ Console</pre><pre>[log] ! optimizing dependencies...<br>  [log]<br>    ⦿ web_modules/                 size       gzip       brotli<br>      ├─ react-dom.js              125.59 KB  39.45 KB   34.58 KB<br>      └─ react.js                  0.17 KB    0.12 KB    0.1 KB<br>    ⦿ web_modules/common/ (Shared)<br>      └─ index-3e0c732a.js         9.84 KB    3.77 KB    3.37 KB</pre><pre>▶ Build Complete!</pre><pre>Done in 7.40s.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*SpdCXU3yvoQXJ6L0Kyjy1w.png" /><figcaption>Output of $npm run build</figcaption></figure><p>One interesting thing to note here is the web_modules folder. This contains all the npm packages compiled into es modules format. These can be now directly imported by browsers using esm import statements.</p><pre>&lt;body&gt;<br>  &lt;script type=&#39;module&#39;&gt;<br>import React from &#39;react&#39;;<br>console.log(React);<br>  &lt;/script&gt;<br>&lt;/body&gt;</pre><p>Another interesting thing that happens is all the jsx files are rewritten using proper paths to vendor npm packages from web_modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*16c5s5SThBl-VJOdJ45v7g.png" /><figcaption>Compiled: build/_dist_/index.js</figcaption></figure><p>Note the react, react-dom paths are rewritten with web_modules paths. CSS files converted into a javascript files which can then be loaded as a regular esm.</p><p>Index html should be clear by now, from the script tag to import script should be _dist_/index.js. Just let the browser know it is a module.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Snowpack App&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    &lt;script type=&quot;module&quot; src=&quot;/_dist_/index.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Running is simple</p><pre><strong>Running server<br>$cd build<br>$ npx http-server<br>$ open browser with </strong><a href="http://localhost:8080/"><strong>http://localhost:8080</strong></a><strong> // react app should run</strong></pre><pre><strong>Running snowpack server<br>$ npm start</strong></pre><pre>snowpack</pre><pre><a href="http://localhost:8080/">http://localhost:8080</a> • <a href="http://192.168.254.39:8080/">http://192.168.254.39:8080</a><br>  Server started in 51ms.</pre><pre><strong>$ open browser with </strong><a href="http://localhost:8080/"><strong>http://localhost:8080</strong></a><strong> // react app should run</strong></pre><p>Almost done. Let me write a few more lines about upgraded config 2.8.0</p><pre><strong>snop/src/snowpack.config.js</strong> for version 2.8.0 <br>module.exports = {<br>  mount: {             // configuration is simplified<br>    public: &#39;/&#39;,<br>    src: &#39;/_dist_&#39;,<br>    web_modules: &#39;/web_modules&#39;<br>  },<br>  &quot;plugins&quot;: []<br>}</pre><p>The same command can be used to build.</p><pre><strong>$ npm run build or $npx snowpack build</strong></pre><pre>&gt; snowpack-sample@1.5.0 build <br>&gt; snowpack build</pre><pre>[snowpack] ! building source…<br>[snowpack] ✔ build complete [0.32s]<br>[snowpack] ! installing dependencies…<br>[snowpack] ✔ install complete [1.13s]<br>[snowpack] ! minifying javascript...<br>[snowpack] ✔ minification complete [0.35s]<br>[snowpack] ▶ Build Complete!</pre><p>Since the newer version has less verbose output during build, I purposefully elaborated with older version so that some of the inner workings are clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QN2SUJlOAUqdyisfihN5fg.png" /><figcaption>index.js with hmr injected</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*8wDovntjSI4_WAofy25Wew.png" /><figcaption>App.js</figcaption></figure><p>Additionally builds files i.e. minified concatenated files can be generated through webpack plugins <a href="https://www.snowpack.dev/#bundle-for-production">@snowpack/plugin-webpack</a>.</p><h4>Sass<em>/</em>scss</h4><p>Sass/scss support is something I am not entirely satisfied, it looks more like a workaround. But atleast we have a workaround. I would like to import &#39;./App.scss&#39;; directly instead today we have to convert to css as a separate process and then inside jsx file we need to import css.</p><pre><strong>$ npm intall sass</strong></pre><pre><strong>snop/snowpack.config.js</strong><br>module.exports = {<br>  mount: {<br>    public: &#39;/&#39;,<br>    src: &#39;/_dist_&#39;,<br>    web_modules: &#39;/web_modules&#39;<br>  },<br>  &quot;plugins&quot;: [<br>    [&quot;<a href="http://twitter.com/snowpack/plugin-run-script">@snowpack/plugin-run-script</a>&quot;, {&quot;cmd&quot;: &quot;sass src:src --no-source-map&quot;, &quot;watch&quot;: &quot;$1 --watch&quot;}]<br>  ]<br>}</pre><pre><strong>rename snop/src/App.css to snop/src/App.scss</strong></pre><pre><strong>snop/src/App.jsx  <br></strong>import &#39;./App.css&#39;; <strong>// no changes here, note no scss</strong></pre><pre><strong>$ npm start </strong></pre><pre>-- additional output of sass --<br>▼ sass</pre><pre>Compiled src\App.scss to src\App.css.<br>Sass is watching for changes. Press Ctrl-C to stop.</pre><pre>Compiled src\app.scss to src\App.css.<br>Compiled src\app.scss to src\App.css.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*5j2a5u1WoaxBmfuCNhJjpw.png" /></figure><p>The App.css is autogenerated now. I don’t see any other problem, the app.jsx imports css so its better to have the css in src folder. That said I would still like to see snowpack team to create a loader for sass so that we do not have to go through this intermediate step of generating css in src folder. Another problem I found out was that the plugin @snowpack/plugin-run-script keeps running behind the scenes even after killing the current build server. (<em>This is a bug at least in windows 10, and should be fixed by snowpack team in future</em>).</p><h3>Vite</h3><p>I wont go a lot of deep in the details but these are the configs used in vite. Note the @pika/react esm react module is required to being with since vite cannot compile normal commonjs or umd react into es modules. So snowpack has the upperhand here 👍. But more and more we are seeing esm build available for npm packages along with commonjs in dists. But its good to have competing technologies. Here is official version of their <a href="https://github.com/vitejs/create-vite-app/tree/master/template-react">starter</a> project.</p><pre><strong>C:\vite\package.json</strong><br>{<br>  &quot;name&quot;: &quot;vite-react-starter&quot;,<br>  &quot;version&quot;: &quot;0.0.0&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;vite&quot;,<br>    &quot;build&quot;: &quot;vite build&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;<a href="http://twitter.com/pika/react">@pika/react</a>&quot;: &quot;^16.13.1&quot;,<br>    &quot;<a href="http://twitter.com/pika/react-dom">@pika/react-dom</a>&quot;: &quot;^16.13.1&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;vite&quot;: &quot;^1.0.0-rc.1&quot;,<br>    &quot;vite-plugin-react&quot;: &quot;^3.0.0&quot;<br>  }<br>}</pre><pre>npm install will installs 202 npm packages. Comparable to snowpack</pre><pre><strong>C:\vite\vite.config.js</strong><br>// <a href="http://twitter.com/ts">@ts</a>-check<br>const reactPlugin = require(&#39;vite-plugin-react&#39;)</pre><pre>/**<br> * <a href="http://twitter.com/type">@type</a> { import(&#39;vite&#39;).UserConfig }<br> */<br>const config = {<br>  jsx: &#39;react&#39;,<br>  plugins: [reactPlugin]<br>}</pre><pre>module.exports = config</pre><pre><strong>C:\vite\index.html</strong><br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;Vite App&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>  &lt;script type=&quot;module&quot; src=&quot;/src/index.jsx&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><pre><strong>Other files index.jsx, App.jsx, App.css will remain same</strong></pre><pre><strong>$ npm run build  (This does bundle everything together)</strong></pre><pre>&gt; vite-react-starter@0.0.0 build<br>&gt; vite build</pre><pre>vite v1.0.0-rc.4<br>[write] dist\_assets\index.70394685.js 266.81kb, brotli: 68.12kb<br>[write] dist\_assets\style.343661e4.css 0.76kb, brotli: 0.40kb<br>[write] dist\_assets\logo.cdc95cf0.svg 2.61kb<br>[write] dist\index.html 0.35kb, brotli: 0.14kb<br>Build completed in 9.25s.</pre><pre><strong>$ npm run dev (This creates es modules)</strong></pre><pre>&gt; vite-react-starter@0.0.0 dev <br>&gt; vite</pre><pre>vite v1.0.0-rc.4</pre><pre>Dev server running at:<br>  &gt; Network:  <a href="http://192.168.254.39:3000/">http://0.0.0.0:3000/</a><br>  &gt; Local:    <a href="http://localhost:3000/">http://localhost:3000/</a><br>[vite:hmr] /src/App.jsx hot updated due to change in /src/App.jsx.<br>[vite:hmr] /src/App.jsx hot updated due to change in /src/App.jsx.</pre><p>Vite dev mode starts up a dev server, and serves everything up using es modules. It adds a small reloader in the <strong>html</strong> and<strong> each js</strong> files also has a small reloader code attached. So the hot module replacement [HMR] part is different from snowpack. Vite’s index.js does not have any special code for reloading. Vite adds sourcemaps which is a plus 👍.</p><p>Vite build by default has a bundler (powered by rollup) it combined all files into a single index.[hash].js. Snowpack also does the build but delegates to webpack via plugin <a href="https://www.snowpack.dev/#bundle-for-production">@snowpack/plugin-webpack</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3NT1t8mOr7Ib3Mfsfa5f2w.png" /><figcaption>index.js — shows @modules which is similar to web_modules, also note sourcemaps</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjaAbt82zZv6gotPdWwCiw.png" /><figcaption>App.jsx — shows @react-refresh and headers injected for hot reloading</figcaption></figure><h3>In real world</h3><p>I converted one of my projects into snowpack and it seems to be running just fine. These are the libs I am using. I might get rid of the postcss portions and go directly with sass.</p><pre>&quot;dependencies&quot;: {<br>  &quot;bootstrap&quot;: &quot;4.5.0&quot;,<br>  &quot;dayjs&quot;: &quot;^1.8.27&quot;,<br>  &quot;jquery&quot;: &quot;3.5.1&quot;,<br>  &quot;lodash&quot;: &quot;4.17.15&quot;,<br>  &quot;materialize-css&quot;: &quot;^1.0.0&quot;,<br>  &quot;node-sass&quot;: &quot;^4.14.1&quot;,<br>  &quot;popper.js&quot;: &quot;1.16.1&quot;,<br>  &quot;postcss-cli&quot;: &quot;^7.1.1&quot;,<br>  &quot;postcss-import&quot;: &quot;^12.0.1&quot;,<br>  &quot;postcss-scss&quot;: &quot;^2.1.1&quot;,<br>  &quot;react&quot;: &quot;16.13.1&quot;,<br>  &quot;react-dom&quot;: &quot;16.13.1&quot;,<br>  &quot;react-easy-swipe&quot;: &quot;0.0.18&quot;,<br>  &quot;react-router-dom&quot;: &quot;^5.2.0&quot;,<br>  &quot;react-swipeable&quot;: &quot;5.5.1&quot;,<br>  &quot;react-use-websocket&quot;: &quot;2.0.1&quot;,<br>  &quot;redux&quot;: &quot;4.0.5&quot;,<br>  &quot;src&quot;: &quot;^1.1.2&quot;<br>},<br>&quot;devDependencies&quot;: {<br>  &quot;snowpack&quot;: &quot;^2.6.4&quot;,<br>  &quot;<a href="http://twitter.com/csstools/postcss-sass">@csstools/postcss-sass</a>&quot;: &quot;^4.0.0&quot;<br>}</pre><h3>Conclusion</h3><p>Snowpack/Vite is a new way of using esmodules for running without bundling client side javascript. They both approach hot reloading in slightly different approach. But at the end experience is same. In production probably it makes more sense even today to minify concatenate js files into one file or intelligently split code into logical splits with tools like webpack. But there are areas where esmodules might be beneficial.</p><p>I can think of immediate applications where dynamic imports are required. Webpack does split and creates dynamic imports points. But imagine the you are trying to load a dynamic plugin from a different application which need not necessarily share code base with the parent webapp.</p><p>Think of microfrontends where each section is a different webapp not sharing code base. These are the really helpful if esmodules can be imported directly in browser and those modules will act as if part of same application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a091491b541e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Shopping Cart promotion engine with boolean expressions]]></title>
            <link>https://samarjit-samanta.medium.com/build-shopping-cart-promotion-engine-with-boolean-expressions-fe8ed31bb4f9?source=rss-a6779649b7fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe8ed31bb4f9</guid>
            <category><![CDATA[expression]]></category>
            <category><![CDATA[domain-specific-languages]]></category>
            <category><![CDATA[pegjs]]></category>
            <category><![CDATA[shopping-cart]]></category>
            <dc:creator><![CDATA[samarjit.samanta]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 05:19:11 GMT</pubDate>
            <atom:updated>2020-07-06T05:19:11.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OR9ov7j9uZ2MH6cv7an9Zg.png" /></figure><p>Boolean expression parser as we built in the <a href="https://medium.com/@samarjit.samanta/beginners-guide-to-building-boolean-expression-compiler-ac17c0d3fa0c">previous post</a> is used to create a domain specific language DSL. In this post we will see how to evaluate such DSL. Here we modified the language slightly to make it fit for building a promotion engine. Under the hood, we are still going to use a PEG.js based grammar. If you are unclear about how to write basic grammar I highly recommend reading the previous post.</p><p>A promotion needs to match a cart with several conditions satisfied. A very succinct way of defining all the conditions is to define it as a complex boolean expression. In this chapter we are going to look at how to evaluate such boolean expression. But lets first see how the expression might look like.</p><h3>Expression</h3><blockquote>Promotion1:</blockquote><blockquote>Buy 2 iphone and get $400 off<br><strong>productCount(productModel=&quot;IPHONE&quot;) &gt; 1</strong></blockquote><blockquote>Promotion2:</blockquote><blockquote>Buy any phone and a phone case and get $50 off</blockquote><blockquote><strong>productExists(productType=&quot;PHONE&quot; and price &gt; 600) and productExists(productType=&quot;CASE&quot;)</strong></blockquote><p>Lets breakdown the expression to see the concept behind it. Instead of calling these as regular functions lets call them as selector functions. The argument these functions take is basically a line-item selector. The function operates on the selected line-item. So <strong><em>productModel=&quot;IPHONE&quot; </em></strong>is the line-item selector. This is not an assignment operation, the <em>equal</em> symbol is a logical equality checker. Left hand side is a <em>property</em> and right hand side is a constant with which the property is matched. This <em>property</em> is expected to be present in each line-item (context). So this expression can be evaluated on any context which has these properties <em>productModel, productType</em> and <em>price</em>.</p><h3>Context/Line-Item</h3><p>Lets create a context to evaluate the above expression.</p><pre>Line 1: {&quot;productType&quot;:&quot;PHONE&quot;,&quot;productModel&quot;:&quot;IPHONE&quot;,&quot;price&quot;:800}</pre><pre>Line 2: {&quot;productType&quot;:&quot;CASE&quot;,&quot;productModel&quot;:&quot;ClearCase&quot;,&quot;price&quot;:20}</pre><p>Now let see how the above expressions should behave. For promotion1 to be satisfied two of the line-item must be a IPHONE. We have only one IPHONE in our context so the promotion1 should evaluate to false. For the promotion2 however any phone with price more than 600 should match line1. The second part is that one of the line-items must contain a CASE. So since both the conditions are matching promotion2 must should evaluate to true.</p><h3>Rules Engine</h3><p>The rules engine consists of expression tree traversal and start evaluation from the leaf nodes. Then as we go higher up in the tree combine the result from the level below and so on. Eventually at the end of traversal when you reach the root node you will have some boolean value left. That should be the result of the entire expression. Another way to look at it is, assume the expression tree to be a prefixed expression. Prefix expression evaluation seems to fit machines very well. Eg. ‘-AB’. read ‘-’ push it onto stack. After that machine knows how many variables to read before evaluation. For unary operator only one variable is required for binary two variables in this case ‘A’ and ‘B’.</p><p>The selector function is context specific. In our case the selector portion knows how to iterate over the line-items, and pass each line-item for selector expression evaluation. This is how the pseudo code would look like</p><pre>function evalRule(rule, context) {</pre><pre>handle rule for primitive operators and context</pre><pre>// recursively call child rules<br>handle rule for nested operator. call evalRule(childRule, context)</pre><pre>handle rule for selector functions<br>     loop over context line-items<br>        evalRule(selectorRule, line-items)<br>        aggregate results based on type of function</pre><pre>}</pre><h3>Interactive Example</h3><p>Finally lets see some interactive examples. You can make the changes to product line-items to match our promotion1, by adding another IPHONE line-item to the cart. Add to cart is simple, just select a product from product list and all selected products make up the cart.</p><p>If you are interested further you can create your own promotion to match the line items, or match new line-items that you can create.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmedium-promotion-engine%3Fembed%3D1%26file%3DevaluateExpression.js%26hideNavigation%3D1%26view%3Dpreview&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmedium-promotion-engine%3Fembed%3D1%26file%3DevaluateExpression.js%26hideNavigation%3D1%26view%3Dpreview&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-1d2450aadcf984376236c23cd2ab0ba231ddd1d85c9b72990ed2ede5b4974d1b.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/368026b9b6fe46c5525a502b96b6c87f/href">https://medium.com/media/368026b9b6fe46c5525a502b96b6c87f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe8ed31bb4f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginners guide to building boolean expression compiler]]></title>
            <link>https://samarjit-samanta.medium.com/beginners-guide-to-building-boolean-expression-compiler-ac17c0d3fa0c?source=rss-a6779649b7fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac17c0d3fa0c</guid>
            <category><![CDATA[dsl]]></category>
            <category><![CDATA[parser]]></category>
            <category><![CDATA[lexer]]></category>
            <category><![CDATA[pegjs]]></category>
            <category><![CDATA[domain-specific-languages]]></category>
            <dc:creator><![CDATA[samarjit.samanta]]></dc:creator>
            <pubDate>Sun, 24 Mar 2019 18:48:06 GMT</pubDate>
            <atom:updated>2020-07-06T05:32:38.737Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building compiler is a fun, you can start writing a DSL (domain specific language) following this article. Our choice is PEG grammar for this article.</h4><p>This is a two part series. This is part 1, where we will learn to create a boolean expression parser which will read the expression and convert into a abstract syntax tree. The <a href="https://medium.com/@samarjit.samanta/build-shopping-cart-promotion-engine-with-boolean-expressions-fe8ed31bb4f9">second part</a> is using that syntax tree and evaluate on a context object. The context is shopping cart and we will define a promotion as a boolean expression.</p><p>We will begin by defining the grammar in pegjs. <a href="https://pegjs.org/">PEG.js</a> is a parser generator for javascript. Our expression will be a boolean expression. It can have function calls. Lets assume this expression works on a javascript object.</p><pre>context = {<br>    name: &#39;sam&#39;,<br>    address: {<br>        addressLine: &#39;2400 Dallas Pkwy&#39;,<br>        apartment: &#39;356&#39;,<br>        state: &#39;TX&#39;<br>    },<br>    projects: [<br>        { projName: &#39;pegjs parser&#39;, year: 2019 },<br>        { projName: &#39;pratt parser&#39;, year: 2019 },<br>        { projName: &#39;MyIMX233 PCB&#39;, year: 2017 }<br>    ],<br>    blogs: [<br>        { title: &#39;naive react&#39;, year: 2019 },<br>        { title: &#39;naive redux&#39;, year: 2018 }<br>    ]<br>}</pre><h4>Lets target these rules</h4><p>These rules take the context and can evaluate to some boolean result. These are mostly like filters, we can call these kinds of expressions as predicates. Then these predicates can be grouped into parenthesis. Also there can be functions calls which may return a number or boolean. If these return number we do some math on the result whose result will be boolean. Then comes the argument of functions. The arguments take the array name as first parameter, and a predicate as second parameter.</p><p>name=&#39;sam&#39; and address.addressLine=&#39;2400 Dallas Pkwy&#39;</p><p>name=&#39;sam&#39; and count(&#39;projects&#39;, year=2019) &gt; 1</p><p>name=&#39;sam&#39; and (exists(&#39;projects&#39;) or exists(&#39;blogs&#39;))</p><p>name=&#39;XX&#39; and (address.state=&#39;TX&#39; or address.state=&#39;CA&#39;)</p><p>name=&#39;XX&#39; and address.state=&#39;TX&#39; and address.apartment=356</p><h4>Grammar</h4><p>In this whole article I will try to built the grammar and output will be AST (abstract syntax tree). The actual evaluation of AST might be part of another blog. So we are mostly working on the parser part of it. The generator is responsible of reading the AST and producing a target language syntax (ex. js, java) or object code.</p><p>This blog might get rather long, since I am going to show all steps and intermediate results. So that you get the hang of thinking process.</p><h4>Other approaches</h4><p>Another approach of parsing these expressions would be to use a hand written parser. A decent one can be written using recursive descent or pratt parser.</p><h4>Simple Predicate</h4><p>It has only one line basically left hand side+operator+right hand side. The lexer regex’es are one single terms. These are combined to create larger expressions. Lets parse this expression address.state=&#39;TX&#39;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*MXMdTsS9gtjpEGO9dyqn9g.png" /><figcaption>Expression term</figcaption></figure><pre>start = Predicate<br>    <br>Predicate = left:identifier op:op right:value {return {op: op, left, value: right};}</pre><pre>// lexer regex<br>op = &#39;=&#39;</pre><pre>value = _ id:[a-zA-Z0-9&#39;-]+ _ {<br>  return id.join(&#39;&#39;);<br>}<br>identifier = _ id:[a-zA-Z\.]+ _ {<br>  return { name: id.join(&#39;&#39;), type: &#39;identifier&#39; };<br>}</pre><pre>integer &quot;integer&quot;<br>  = _ [0-9]+ { return parseInt(text(), 10); }</pre><pre>_ &quot;whitespace&quot;<br>  = [ \t\n\r]*</pre><h4>Simple Predicate Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*-Xk5q0gVbj1JuKRFyzlF_A.png" /><figcaption>Output for address.state=&#39;TX&#39;</figcaption></figure><p>Extrapolating this technique can deal with binary operator expressions like this name=&#39;XX&#39; and address.state=&#39;TX&#39;. But how can we chain these expressions. Lets target name=&#39;XX&#39; and address.state=&#39;TX&#39; and address.apartment=356 next. We need to still make our expression backward compatible. Like if only name=&#39;XX&#39; is there without any and, it should still work. The little /Predicate does the trick. It tells AndExpr if it does not find the head or tail then fallback to match only Predicate.</p><pre>start = AndExpr<br> <br>AndExpr = head:Predicate tail:(&#39;and&#39; Predicate)+ {<br>   let accum = [head];<br>   tail.reduce((accumulated, element) =&gt; {<br>             accumulated.push(element[1]);<br>                return accumulated;<br>            }, accum);<br>   return {op: &#39;and&#39;, predicates: accum};<br>  }<br>        /Predicate</pre><pre>Predicate = left:identifier op:op right:value {return {op: op, left, value: right};}</pre><p>Output</p><pre>{<br>   &quot;op&quot;: &quot;and&quot;,<br>   &quot;predicates&quot;: [<br>      {<br>         &quot;op&quot;: &quot;=&quot;,<br>         &quot;left&quot;: {<br>            &quot;name&quot;: &quot;name&quot;,<br>            &quot;type&quot;: &quot;identifier&quot;<br>         },<br>         &quot;value&quot;: &quot;&#39;XX&#39;&quot;<br>      },<br>      {<br>         &quot;op&quot;: &quot;=&quot;,<br>         &quot;left&quot;: {<br>            &quot;name&quot;: &quot;address.state&quot;,<br>            &quot;type&quot;: &quot;identifier&quot;<br>         },<br>         &quot;value&quot;: &quot;&#39;TX&#39;&quot;<br>      },<br>      {<br>         &quot;op&quot;: &quot;=&quot;,<br>         &quot;left&quot;: {<br>            &quot;name&quot;: &quot;address.apartment&quot;,<br>            &quot;type&quot;: &quot;identifier&quot;<br>         },<br>         &quot;value&quot;: &quot;356&quot;<br>      }<br>   ]<br>}</pre><p>Dealing with parenthesis should not be much of a problem. But sometimes recursion will take a while to wrap your head around this.</p><pre>start = OrExpr<br> <br>OrExpr = head:AndExpr tail:(_ &#39;or&#39; _ AndExpr)+ {<br>   let accum = [head];<br>   tail.reduce((accumulated, element) =&gt; {<br>             accumulated.push(element[3]);<br>                return accumulated;<br>            }, accum);<br>   return {op: &#39;or&#39;, predicates: accum};<br>  }<br>        /AndExpr<br>        <br>AndExpr = head:ParenExpr tail:(_ &#39;and&#39; _ ParenExpr)+ {<br>   let accum = [head];<br>   tail.reduce((accumulated, element) =&gt; {<br>             accumulated.push(element[3]);<br>                return accumulated;<br>            }, accum);<br>   return {op: &#39;and&#39;, predicates: accum};<br>  }<br>        /ParenExpr</pre><pre>ParenExpr = &quot;(&quot; exp:AndExpr &quot;)&quot; { return exp; } / Predicate</pre><p>At this point we are able to handle this kind of expressions name=’XX’ and (address.state=’TX’ and address.apartment=356) and y=10</p><p>Lets get the call expressions working. There is quite a bit going on here to disambiguate between and(...) vs fn(...). Note the keyword and. To get around this we have to use ReservedWords concept. Since andis a reserved word, it will not match the CallEx. Notice how ArgsExpr also contains the OrExpr. Then finally the call function may be part of left hand side of an expression.</p><pre>start = OrExpr<br> <br>...<br>        <br>AndExpr = head:CallExpr tail:(_ &#39;and&#39; _ CallExpr)+ {<br>   let accum = [head];<br>   tail.reduce((accumulated, element) =&gt; {<br>             accumulated.push(element[3]);<br>                return accumulated;<br>            }, accum);<br>   return {op: &#39;and&#39;, predicates: accum};<br>  }<br>        /CallExpr</pre><pre>CallExpr = callex:CallEx _ op:op _ val:value { // functionRet() &gt; 0<br>    return {op, callex, value: val};<br>   }<br>         /CallEx</pre><pre>ArgsExpr = head:value _ &#39;,&#39; _ tail:OrExpr {<br>             tail.path = head;<br>    return tail;<br>     }<br>           /value<br>           <br>CallEx = !ReservedWord ident:[a-zA-Z]+ &#39;(&#39; _ args: ArgsExpr _ &#39;)&#39; { // functionThatReturnsBoolean()<br>   return {type: &#39;CalExpr&#39;, name: ident.join(&#39;&#39;), args: args};<br>           }<br>       / ParenExpr<br>       <br>ParenExpr = &quot;(&quot; exp:AndExpr &quot;)&quot; { return exp; } / Predicate</pre><pre>...</pre><p>This is already capable of parsing name=’XX’ and count(‘blog’, address.state=’TX’ and address.apartment=356) &gt; 0 and y=10.</p><h4>Full Implementation showing all the use cases</h4><p>I did modify a bit, like the value expression now understands quoted string and the terminating quote should be same as starting quote, still it can be improved to understand escape sequence. Also spaces are included as part of value since we have quoted string.</p><p>Below you can see all the expressions in action.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmedium-pegjs%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmedium-pegjs%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e20040656c2c4ae952122f2850d9b86/href">https://medium.com/media/6e20040656c2c4ae952122f2850d9b86/href</a></iframe><h4>Conclusion</h4><p>Now we have got a working lexer parser using pegjs grammar which produces AST. Writing this parser coding by hand would have taken a lot more thought process, but we could get a faster performance. Feel free to write a generator to execute these rules against the actual json context we imagined in the beginning. I will share the link in this post if you post in comments.</p><p><a href="https://medium.com/@samarjit.samanta/build-shopping-cart-promotion-engine-with-boolean-expressions-fe8ed31bb4f9">Second part</a> is all about evaluate the abstract syntax tree that we created in this part of the tutorial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac17c0d3fa0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Chip to linux — MyIMX233]]></title>
            <link>https://samarjit-samanta.medium.com/from-chip-to-linux-myimx233-adbe97849ff7?source=rss-a6779649b7fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/adbe97849ff7</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[pcb]]></category>
            <category><![CDATA[homebuilt-linux-pcb]]></category>
            <category><![CDATA[single-board-computer]]></category>
            <dc:creator><![CDATA[samarjit.samanta]]></dc:creator>
            <pubDate>Sat, 23 Mar 2019 22:52:26 GMT</pubDate>
            <atom:updated>2019-03-23T23:07:22.473Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qckYh6EFeXLU3vd6Ct1ySg.png" /></figure><h3>From Chip to linux — MyIMX233</h3><h4>Building a linux capable circuit board at home from designing to soldering to installing Arch Linux — Its not hard! Its costs less than 2000 Rs. (~$28). Sounds fun!</h4><p>Why it is not hard?<br>I am a professional software developer. But this skill was not used.<br>I have done bachelors in electronics. But they never taught any of these in school.<br>Skills you will need — good eyes, steady hand in soldering, some youtube videos, some links to contents, and patience patience patience. If you have arduino/raspberry skills it will help a little.</p><h3>Overview of how it works</h3><p>We need a microprocessor. Microprocessors have tiny RAM and tiny persistent memory. So we need to wire both bigger RAM and bigger persistent memory to hold OS image data. which in our case will be SD card big enough to hold linux. 2GB SD card is enough. Microprocessor comes with small pre-built programs which is present in its ROM and comes factory programmed. These small programs loads first thing and runs on power-up. These can be configured to look for next bigger of programs to load and run either from SD card or from NAND flash memory. They look for specific memory address in SD card or NAND flash and starts loading and executing from there. These first program that gets loaded from SD card or NAND flash memory are the bootlets or bootloaders (u-boot). These are slightly bigger programs and does some basic health checks and then loads OS image. OS binary images are also hardware aware. Meaning during building the OS image a board support package (BSP) was specified. I believe these become the hardware abstraction layer (HAL). On top of it sits the linux kernel. You can build your own OS image using linux BSP+linux kernel and building them all together using <a href="http://www.yoctoproject.org/about">YOCTO</a>. This <a href="https://www.jann.cc/2012/08/08/building_freescale_s_community_yocto_bsp_for_the_olinuxino.html">blog </a>explain more about it.</p><p>We connect the PCB to laptop using a micro usb which provides power. We talk to microprocessor during booting process using RS232 interface. So using RS232 COM interface we can see all the console logs and even you can send commands to PCB using RS232.</p><h4>Design Concerns</h4><ul><li>Microprocessor to RAM connection requires high speed PCB design and it is most critical. I believe 400MHz connectivity or is it 400mbps. I kind of forgot now.</li><li>Microprocessor to SD card connectivity is also high speed. Approx 96MHz.</li><li>Microprocessor to USB data connection is also high speed.</li><li>microprocessor to RS232 lower speed but you can still follow same quality.</li><li>power supply — microprocessors are a bit picky about power supply and interference/harmonics/oscillations in power supply cause lot of instability. You will need lots of bypass caps to suppress harmonics and stabilize power supply.</li></ul><h3>Tools I used:</h3><ul><li>Small fine tip soldering iron 12v. <a href="https://www.amazon.in/Buyyart-Original-QUICK-Soldering-Mobile/dp/B07CJZSGGC">MAX PAMMA 550</a> (500Rs)— It was cheapest and not very good. But I soldered 0.5mm thin pads with it.</li><li>Multimeter — <a href="https://www.amazon.in/HTC-Instrument-DM-97-Capacitance-Temperature/dp/B013YPMLO0/ref=sr_1_1?s=industrial&amp;ie=UTF8&amp;qid=1553368408&amp;sr=1-1&amp;keywords=multimeter+DM97">DM97</a> again nothing special but real cheap ones send out a lot of current in the leads. So better to go for a decent ones.</li><li>Antistatic Tweezers — not absolutely necessary</li><li>Thin soldering wire, flux, wick etc. Since my soldering iron was weak thin soldering iron worked. Good thing it came with a roll.</li><li>TTL to USB converter — <a href="https://www.amazon.in/Robodo-Electronics-MO41-Converter-Raspberry/dp/B0787KBLWX/">PL2303</a> This is also a bit painful with their drivers. Better to use an FTDI.</li></ul><h3>Knowledge</h3><p>Now this part is important, and good news is knowledge can be acquired. I am also new to it, but I will cover it sufficiently. PCB design is very important.</p><h4>High speed circuit design upto 400 MHz interface</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOGxXQwMUH2pfo8PSpzWZQ.png" /><figcaption>Length matching with curvy lines</figcaption></figure><p>The processor to RAM connections are high speed bus. Imagine if one signal travels longer and another one travels through shorter path they will both reach the destination at different time. Now the RAM will latch onto the input data at rising edge or falling edge of the clock pulse. If one of the signals travel slower then it may not reach during the instant when data is read by ram. This is the reason all these data lines should have same length. Now the challenge is everything cannot have same length because you have limited real estate. So subdivide into batches, and length tune each batch within a certain tolerance. Our RAM address bus is one batch, data lower byte D0-D7 is another batch, data higher byte D8-D14 is another batch. You can find other batch of connections like control signals can be one batch. If you have more RAM there will be more batches. Sometimes you can find this info in the datasheet of the microprocessor. To have a reliable clock pulse, it is a differential line. Differential pairs should have equal spacing between them from start to end. In general clock trace length should be average length of all data lines. Since we are using two layer board, if there are traces on top and bottom layer make sure they cross each other perpendicular. But try not to have traces in both layers. Having ground plane and traces on the other side makes it most stable. Kicad comes with differential pair routing capability. Kicad also comes with length matching utility. Without these two features designing the PCB would have been impossible. There is another aspect called impedance matching which I did not use.</p><h4>Power supply stabilization filtering out harmonics</h4><p>In general place bypass capacitors as close as possible physically to the pins of microprocessor to filter unwanted frequencies. The lower caps are usually smaller in size and can be placed closest to the microprocessor pins. The larger ones can be pushed away. One advantage of this imx233 microprocessor is that, it contains the power management unit inside the micro. A microprocessor splits power into multiple voltage levels each used for different purposes and each are having maximum power rating beyoned which if we draw it’s voltage might go down. Placing simple resistors to reduce voltage might be easy but resistances tend to eat up a lot of energy and consume as heat. So mostly switching mode voltage regulators are used. Inside this micro voltage is reduced in steps. Knowing each step will help in debugging if voltages are not matching up to the specs on power up. Also note that not all the powers are immediately available until some boot sequence is executed. I have noted down the specific lengths have below.</p><h4>Soldering</h4><p>Soldering is not too hard. I specified 5mil trace and 5mil spacing in RAM bus and other traces emanating from microprocessor. Microprocessor pins itself are very thin so there was not much choice. I got my PCBs manufactured in <a href="https://www.pcbpower.com/">PCBPOWER</a>. Their quality was very good. One major advantage was that, they were able to put soldermask between 5mil pads of the microprocessor. That really helps to avoid pin short circuiting between pads. One more advantage was to have the pads silvered HAL. This also helps in soldering. I would just add flux, the already silvered pads have enough solder to solder microprocessor pads to the pcb.</p><h4>Circuit diagram</h4><p><a href="https://github.com/samarjit/MyIMX233/blob/master/plot_sch/MyIMX233_3.pdf">https://github.com/samarjit/MyIMX233/blob/master/plot_sch/MyIMX233_3.pdf</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*Jya7APa0MCObI5iDd3NJsg.png" /></figure><h4>Components Guide Tip</h4><p>I ordered most stuff from <a href="http://www.shelfkey.com/">http://www.shelfkey.com/</a>. They have various sources and prices are reasonable. If you pick up from their store then you will not even incur the local postal charges of 200 Rs.</p><p>MicroSD connector — This one came costly with the kicad footprint which I already had. In local market there is a cheaper one available but you will need to download the footprint from somewhere. My latest circuit has it.</p><p>Microusb — For this the cheaper ones are somehow bad, either they are very difficult to secure to the board, or the pins are notoriously difficult to solder. You would want to solder it very well so that it does not break or lift traces, because everyday you will tug at it while trying to plug in/out your microusb cable. Other option is to use a type A/type B usb with through hole ones. Sturdiest connection! You wouldn’t want your board to be unusable just because of poor usb trace broken.</p><h3>My Github README</h3><p>This part is a readme from my github account verbatim.</p><p>I am starting to build a single board computer with freescale microprocessor iMX233 128 LQFP and 64MB DDR2 SDRAM in 66TSOP. This single board computer will be bare bones with lots of GPIO exposed. There is no special goal for this project. I am just curious to see if it works. In future I might add an LCD. The PCB is two layered only and can be manufactured cheap.</p><p><strong>Github:</strong> <a href="https://github.com/samarjit/MyIMX233">https://github.com/samarjit/MyIMX233</a></p><h3>TODOs (done)</h3><ul><li>Increase pad lengths of LQFP footprint. (done. Hope to mitigate the soldermask between pads issue |&lt;-0.06mm space-&gt;&lt;-0.08mm web-&gt;&lt;-0.06mm space-&gt;| = 0.2mm)</li><li>Perhaps add a jumper on the 2.5v LineReg and separate out VDD_MEM to be able to test the 2.5v is not 0 due to loading. (skipped)</li><li>88 USB_ID SSP1_DETECT ? Should I use this to CD of SD card connector or micro USB ID pin? In my circuit it is pulled low via LED. Tux,calculator does the same too.</li><li>Add option to boot resistors LCD_RS and LCD_00..LCD_05 (done)</li><li>14 LCD_RS ? High for register boot mode. Or low with 47k resistor for OTP boot mode. Olimex is confusing OTP is set MMBR and LCD_RS is high. (done)</li><li>Schottkey Diode D1 VDD4P2 direction. Its strange in ref diagram vs 5v wall. VDD4P2 -|&gt;||- VDDBATT. (done Optional. Not populated in running board)</li><li>Series resistor 1E for preventing oscillations (done 3 series resistor added, usb, batt, 4p2) /in old circuit Test by removing Diode, and LED_RS to gnd via resistor.</li><li>RESET circuit? Make sure not to get into USB recovery mode. add zener 1.0v so that it never reached 3.3v or just remove reset circuit altogether.</li><li>Configure to get rid of batteries as per rev-c circuit. Add 1k resistors in DCDC_BATT and BATT and some caps to GND.</li><li>Need to convert the SD card connector to a cheaper version available on ebay or alibaba. (done part-ATTEND 112J-TDAR-R01) I got the files from <a href="https://forum.kicad.info/t/microsd-component-footprint-help/3095/5">https://forum.kicad.info/t/microsd-component-footprint-help/3095/5</a> and placed in parts/ folder. It would be awesome if I can find some 3D model of it. If someone finds it please create an issue. (Yes found)</li><li>Make DDR RAM pin pads longer (new)</li><li>Make alternate USB plug preferably through hole or longer pads in micro USB. (new)</li><li>Make micro-SD pads larger and longer and add a few decoupling capacitors.(new)</li><li>Make more rooms for the inductor as most inductors are really big 8mm long plus place for hand soldering.(new)</li></ul><h3>TODOs (ignored)</h3><ul><li>POWER off circuit?</li><li>Is Micro SD pullups on all pins necessary? SSP1_DETECT used? (done added them in the bottom side. Data3/CS pulled low)</li><li>Added 120R between CLK nCLK.</li></ul><h3>Length Tuning</h3><ul><li>D0..D7 LDQS LDM — 39.7mm tuning (real 40.2mm)</li><li>CLK nCLK — real 32.2/32.6mm</li><li>D8..D15 UDQS UDM — 25.5mm tuning (real 26.0mm)</li><li>Address: 32.35mm ~ 25mm</li><li>CKE- 20.2mm</li><li>SD: 24.8mm tuning (real 25.3mm)</li></ul><h3>Installation steps</h3><p>Cloning this repository should work. It does use opendous conn_fci from <a href="https://github.com/cpavlina/kicad-pcblib.git">https://github.com/cpavlina/kicad-pcblib.git</a>, <a href="https://github.com/cpavlina/kicad-schlib.git">https://github.com/cpavlina/kicad-schlib.git</a> Copy kicad-pcblib\conn-fci.pretty to KiCad\share\kicad\modules\conn-fci.pretty Add kicad-schlib-master\library\conn-fci.lib to SchematicEditor -&gt; ComponentLibraries Add opendous to component libraries too.</p><h3>Drivers for this project.</h3><ul><li>Until recently I didn’t know of a decent opensource software for PCB designing or circuit designing which can be used to design complicated circuits involving microprocessor. I recently discovered KiCAD which is opensource pcb designing software and people have done microprocessor design with it eg. OLinuXino. I am trying to learn PCB designing using KiCAD now.</li><li>Second driver was Clementine Core project which I saw in circuitmaker website. This schematic looked so simple and pcb was on 2 layer design, which changed my thought process altogether that linux running board designs may be something I can try.</li><li>Third driver was LibreCalc which almost proved that KiCAD can be used to design IMX233 based board. I hope to learn from their mistakes, but a newbee like me can uncover a whole lot of new mystries.</li></ul><p>So I have put together a mashup of schematic design of IMX233 and 64MB RAM from freescale reference design and other sources.<br> <strong>Freescale microprocessor:</strong><br> <strong>DDR RAM — I think all these below RAM chips are compatible.</strong></p><ul><li>AS4C32M16MD1–5TCN</li><li>HY5DU121622D(L)T(P)-J</li><li>MT46V32M16P-5B:J (This is the only one I can source, so I am using this)</li></ul><p>This project is a work in progress and there is no gurantee that I will ever be able to complete it :). But if you want to try building same stuff as I am building. Go ahead and fork it. Download KiCad. I am using nightly version of it, because it does not require you to export the netlist and import it again in pcb editor. Make the workflow really easy. I can see one bug in KiCAD, which is after modifying the footprint by adding a step file. It looses the saved settings.</p><p>Once you have installed KiCAD, open <strong>MyIMX233.pro</strong> file.</p><p><a href="https://github.com/samarjit/MyIMX233/blob/master/MyIMX233.sch">MyIMX233.sch</a> — Schematic file.<br> <a href="https://github.com/samarjit/MyIMX233/blob/master/MyIMX233.kicad_pcb">MyIMX233.kicad_pcb</a> — PCB<br> <a href="https://github.com/samarjit/MyIMX233/blob/master/ReferenceSch">ReferenceSch</a> — contains reference materials. I uploaded all of them for providing content incase someone wants to understand the design.</p><h3>Progress:</h3><h3>Oct 8 It worked! You can start building one today for yourself :)</h3><p>Few soldering quirks are there. USB pads are quite small to solder. Also pad to hold USB in place is also very small and bad for soldering. Even the SD card pads are also small for soldering. These were new footprints so in next version I will make longer pads for these. RAM pads can be made slightly longer for reliable soldering. Soldered board and powered up without SD card. Some error were coming 0x80207002. Boot loader looking for I2C and it is not initialized. Turned out to be soldering of one pin was not proper for LQFP128. Fixed this pin issue then SD card missing related errors were coming. Added SD card with bogus data 0x8020A007 — ERROR_DDI_SD_CONFIG_BLOCK_NOT_FOUND. Added SD card formatted properly but still 0x8020A007. Little bit further digging showed that SD card MBR boot is not enabled by default. We need to burn an OPT bit HW_OCOTP_ROM0::SD_MBR_BOOT to enable booting from SD card. This process is irreversible. Default boot mode is BCB. I read up again librecalc’s failure blog. It gave two perl programs to burn the SD card with u-boot in BCB mode. The 2nd perl program didn’t run as it assumed smaller SD cards only. I edited the perl program to make it find proper boot signatures. Now we can see something HTLC in UART console. That’s too less info to debug further. At this point I posted in freescale community. <a href="https://community.nxp.com/message/949934">https://community.nxp.com/message/949934</a>. I decided to blow the MBR OTP flag using BitBurner. Then added MBR based uSD card and same u-boot. Now again it shows HTLC. Good news is that MBR booting works. But it fails very soon. Need bootlets which gives more detailed log instead of u-boot. Turned out voltages are fluctuating all 3v3, 4v2, 1v8, 1v. They were fluctuating in a cycle. I burned official Olinuxino image in SD card. That seems to have bootlets so it gave more info. After right after memory FRAC 0x92926192 it reboots. I heated up all the pins of DDR and iMX233 with soldering iron. It goes 1 more line ahead in log init_ddr_mt46v32m16_133Mhz and sometimes power 0x00820710. I added a big capacitor in place of battery which goes the log to further and says uSD card general error ending with r14&lt;0&gt;HTLLLL... I tried adding a few caps on 3v3. But nothing helped. Then I tried the other jumper of battery mode. Then it started loading kernel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*fPM35rA-YC_quLzV.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7bh5XOHrT3qGQkcp.jpg" /></figure><h3>Aug 2017</h3><p>Started modifying the schematic to make battery and USB wall power optional using jumpers. Also realized boot selection can be done using resistors. Sent for fabrication of PCB to pcbpower.</p><h3>July 2017 end first soldered board</h3><p>Good news is most of the components fitted. Also I got some confidence about my KiCAD skills. Some shortcomings were observed, like the pads for soldering were two short for the fine pitched LQFP128 0.4mm pitch and solder mask dams were not created between pads which made it incredibly hard to solder. I will have to customize the LQFP128 footprint to make it suitable for hand soldering. Some 0402 caps were placed very close, I realized the courtyard verification of components is not turned on by default. I had limited success like UART was working USB was working, BitBurner was working and showing all the OPT(One Time Programmable) bits. Some gibberish was coming on UART console. I used solder paste for soldering, so I thought some shorting might be happening. Then I tried to do reflow soldering to make the solder joints liquify once and then quickly cool it using a frying pan. It actually fried my board! I also mistakenly soldered uSD card with power on! Carelessness!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*Xapi2iO2FLF97Ich.jpg" /></figure><ul><li>I also ordered components. I didn’t realize this would be a pain. element14 is not that accessible for an individual. I ordered mostly from Shelfkey and some from KitsNSpares. I am still tensed if footprints I chose will match the actual components. Second I am very much tensed about soldering 0402 components.</li><li>Final version of PCB sent for fab in pcbpower.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PQMlMl_TtdtYT9dC.png" /></figure><ul><li>Added few options to use DCDC. I was not comfortable of grounding DCDC_BATT and BATT pins, so I added a few jumpers. Also added provisions to add battery.</li><li>Learnt basic Freecad to build the Step files of DDR SDRAM 66TSOP. Here is the project I created — <a href="https://github.com/samarjit/MT46V32M16P-5B-Freecad-Step">MT46V32M16P-5B-Freecad-Step</a>.</li><li>Initial version. DDR RAM child 3D missing and SD card’s 3D missing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SBYkk3d4_QJiJdrq.png" /></figure><ul><li>Wiggly trace lines, learnt Length Matching in Kicad.</li><li>Figured out placement of components. I am going with Clementine Core’s placement which seems very good.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XMeVN2AWd0gh0mUs.png" /></figure><ul><li>Initial version with the very basics layed out.</li></ul><p><em>Originally published at </em><a href="https://mylinuxsbc.blogspot.com/2017/10/myimx233.html"><em>mylinuxsbc.blogspot.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adbe97849ff7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Naive React]]></title>
            <link>https://samarjit-samanta.medium.com/naive-react-3d86ab64be84?source=rss-a6779649b7fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d86ab64be84</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[simple-react]]></category>
            <category><![CDATA[jsx]]></category>
            <dc:creator><![CDATA[samarjit.samanta]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 03:55:56 GMT</pubDate>
            <atom:updated>2020-11-05T04:30:22.291Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lets build ui framework — Naive React</h3><blockquote>Update: From React 17+ JSX transformation will no longer create React.createElement() instead it will be _jsx()!</blockquote><p>If JSX becomes a standard of EcmaScript ES-XXXX, we will have an amazing tool at our disposal. Even if we do not want full blown react in our application, lets see how far we can go about using its render functions.</p><p>Good news is TypeScript natively supports jsx now. It is also possible to compile jsx with babel without React js. The output javascript contains React.createElement(). In this project, I am trying to implement this createElement() to render dom tree. Initial render is quite simple. But it getscomplicated to handle rerender where children nodes need to be tracked and replaced. This was achieved in stage 2.</p><p>To run the project.</p><ol><li>npm install</li><li>npm run build -- This will compile all jsx and concatenate using browserify in the dist folder.</li><li>Open the index.html from dist folder in a browser. Alternatively run http-server to serve static files from dist directory</li></ol><ul><li>Note: This is a work in progress</li></ul><h3>Stage 1</h3><p>We have a simple render logic that traverses the nodes through render functions and generates dom. It is simple template rendering.</p><h4>There is no way to rerender onlysubtrees.</h4><p>If I go with virtual dom path there is no need to rerender subtrees as it will be always full render and virtual dom diff will take care. And then dom patch will be done as in traditional react.</p><h4>There is no way to know which subtree needs to be rerendered.</h4><p>One way is to make the state,props as observables and we can figure out if it requires rerender. Probably this is how angular1 was built. The rerender also cannot patch the dom since there is no marker to tell which node is being referred by the current component, so that the subtree can be replaced. Also I am starting to ponder what happens if the child subtree contains a form, all user’s selection will be lost. So singleton will be required, but singleton instance must be created per unique node. Once created those instances are created, those needs to be reused otherwise state data will be lost.</p><p>We may have to go with synthetic events for 2 reasons.</p><ol><li>To be able to cleanup without memory leaking.</li><li>To know if rerender is required if there is an event.</li></ol><h3>Some stage1 code</h3><p>I defined a button component, and a bootstrapping class App.tsx. Both are pretty much similar to what you would do in actual reactjs application. I will explain about the import statement in a minute. But rest of the code is exactly like plain reactjs.</p><pre>import React from &#39;./DummyReact&#39;;</pre><pre>export default class MyButton {<br>  state: any;<br>  constructor() {<br>    this.state = {count: 0};<br>    this.clickHandler = this.clickHandler.bind(this);<br>  }<br>  clickHandler() {<br>    console.log(&#39;Button clicked&#39;);<br>    this.state.count += 1; <br>  };<br>  render() {<br>    return (&lt;div&gt;<br>        {this.state.count}<br>        &lt;button onClick={this.clickHandler}&gt;button text&lt;/button&gt;<br>    &lt;/div&gt;);<br>  }<br>}</pre><p>And the bootstrapping part goes like this. This is also plain reactjs.</p><pre>import React from &#39;./DummyReact&#39;;<br>import MyButton from &#39;./MyButton&#39;;</pre><pre>class App {<br>  render(): any {<br>    return (&lt;div&gt;Hello &lt;MyButton/&gt;&lt;/div&gt;);<br>  }<br>}</pre><pre>React.renderRoot(&lt;App/&gt;, document.getElementById(&#39;root&#39;));</pre><p>Now what does it take to render these above snippets. We know that jsx gets compiled into plain javascript. Lets look at what it gets compiled into.</p><p>MyButton.tsx get compiled into below snippet.</p><pre>Object.defineProperty(exports, &quot;__esModule&quot;, { value: true });<br>var NaiveReact_1 = require(&quot;./DummyReact&quot;);<br>var MyButton = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>  function MyButton() {<br>    this.state = { count: 0 };<br>    this.clickHandler = this.clickHandler.bind(this);<br>  }<br>  MyButton.prototype.clickHandler = function () {<br>    console.log(&#39;Button clicked!&#39;);<br>    this.state.count += 1;<br>    NaiveReact_1.default.forceRender(this);<br>  };<br>  ;<br>  MyButton.prototype.render = function () {<br>    return (NaiveReact_1.default.createElement(&quot;div&quot;, null,<br>    this.state.count,<br>    NaiveReact_1.default.createElement(&quot;button&quot;, { onClick: this.clickHandler }, &quot;button text&quot;)));<br>  };<br>  return MyButton;<br>}());<br>exports.default = MyButton;</pre><p>The app.tsx looks like this below snippet.</p><pre>Object.defineProperty(exports, &quot;__esModule&quot;, { value: true });<br>var NaiveReact_1 = require(&quot;./DummyReact&quot;);<br>var MyButton_1 = require(&quot;./MyButton&quot;);<br>var App = /** <a href="http://twitter.com/class">@class</a> */ (function () {<br>  function App() {<br>  }<br>  App.prototype.render = function () {<br>    return (NaiveReact_1.default.createElement(&quot;div&quot;, null,<br>    &quot;Hello &quot;,<br>    NaiveReact_1.default.createElement(MyButton_1.default, null),<br>    NaiveReact_1.default.createElement(MyButton_1.default, null)));<br>  };<br>  return App;<br>}());<br>NaiveReact_1.default.renderRoot(NaiveReact_1.default.createElement(App, null), document.getElementById(&#39;root&#39;));</pre><p>By seeing the above compiled code, you will notice that JSX automatically assumes that it has to convert those tags into React.createElement() static functions. For this reason we have to stick with this React keyword. But we will provide our own implementation that will traverse this render functions tree calling each other until the dom is rendered. That is exactly what is done in this below 46 lines code on DummyReact.ts.</p><p>DummyReact.ts</p><pre>export default class DummyReact{</pre><pre>static singletonRegistry = {};<br>  static getInstance(tagName: any) { <br>      return new tagName();<br>  }<br>  static createElement(tagName: any, attrs:{[x: string]: any}, ...children) {<br>    let elm;<br>    if(typeof(tagName) === &#39;function&#39;){<br>      elm = DummyReact.getInstance(tagName).render();<br>    } else {<br>      elm = document.createElement(tagName);<br>    }<br>    if(attrs) {<br>     for( var attr in attrs) {<br>        <br>      if(/on\w+/.test(attr)) {<br>        let eventName = attr.replace(/^on/,&#39;&#39;);<br>        eventName = eventName.charAt(0).toLocaleLowerCase() + eventName.substr(1);<br>        elm.addEventListener(eventName, attrs[attr]);<br>      } else {<br>        elm.setAttribute(attr, attrs[attr]);<br>      }<br>     };<br>    }</pre><pre>    if(children) {<br>      children.forEach((child) =&gt; {<br>        if(typeof child === &#39;string&#39; || typeof child === &#39;number&#39;) {<br>          elm.innerHTML = elm.innerHTML + child;<br>        } else {<br>          // assume it is a function; perhaps a function createElement(..)<br>          elm.appendChild(child);<br>        }<br>      });<br>    }<br>    return elm;<br>  }</pre><pre>  static renderRoot(obj, rootElement) {<br>    for(var element of rootElement.children) {<br>      rootElement.removeChild(element);<br>    };<br>    rootElement.appendChild( obj );<br>  }<br>};</pre><p>You can see a working version right here.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fdummy-react%3Fembed%3D1%26file%3DDummyReact.ts&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fdummy-react%3Ffile%3DDummyReact.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2785cf7ed6cb70a65729d370cda42c70/href">https://medium.com/media/2785cf7ed6cb70a65729d370cda42c70/href</a></iframe><h3>Stage 2</h3><p>I am focusing on two things for now.</p><ol><li>I want to achieve without virtual-dom</li><li>Partial re-render of subtree. This will become our force render.</li><li>Be able to have Multiple instance of the same Component (Ex. MyButton being shown twice with two different counter values. Where counts are being stored within the Component)</li><li>Handle events from correct instance if multiple instances of a Custom Element is present. (Ex. Clicking MyButton in our case with trigger event of its correct instance)</li></ol><p>The solution was to have marker reference to each component instance in html node. This concept is similar to isolated scope in angularjs. Whenever any event is triggered the correct instance of the function gets called. We are having dom events listeners. Currently there is no synthetic event concept in our implementation. Also there is no global listening to events to autorender. So an explicit forceRender() is required to be called. From the instance which is called forceRender() the correct instance is identified and the relevant dom node is identified. Then the subtree is re-rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*2CK3UoTsC7LfvgNTIFq5_Q.png" /></figure><p>Overall the implementation of Naive-React has only 3 important function.</p><pre>export default class NaiveReact{</pre><pre>   static appendRef(inst, elm, instNumber) {...}</pre><pre>   static createElement(tagName: any, attrs:{[x: string]: any}, ...children) { ... }</pre><pre>   static forceRender(comp) { ... }</pre><pre>}</pre><p>The entire implementation is less than 98 lines of code.</p><p><a href="https://stackblitz.com/edit/naive-react?file=NaiveReact.ts">https://stackblitz.com/edit/naive-react?file=NaiveReact.ts</a><br><a href="https://github.com/samarjit/naive-react/blob/master/src/NaiveReact.ts">https://github.com/samarjit/naive-react/blob/master/src/NaiveReact.ts</a>.</p><p>Live working implementation is shown below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fnaive-react%3Fembed%3D1%26file%3Dindex.tsx&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fnaive-react%3Ffile%3Dindex.tsx&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/50a1adb948f2902bb03c2c9142a72c8f/href">https://medium.com/media/50a1adb948f2902bb03c2c9142a72c8f/href</a></iframe><h3>Conclusion</h3><p>With just 98 lines of code we can achieve a jsx rendering + events + render subtrees without any external dependencies. JSX is supported out of box in TypeScript which opens up this opportunities. I hope JSX is supported in EcmaScript in future. Today you can do so using babel. For a simple application where react will be overkill this is a viable template implementation.</p><p>Future improvements can be done to implement synthetic events and which will pave the path for implementing auto-render. Feel free to fork and have fun!</p><p>Links — What’s next lets build redux too — <a href="https://samarjit-samanta.medium.com/lets-build-naive-redux-159e3caa856b">https://samarjit-samanta.medium.com/lets-build-naive-redux-159e3caa856b</a></p><p>Next — probably I will build a router</p><p><strong>Food for throught </strong>— React keeps a virtual dom tree, and runs all components to create another dom tree, then find the diff, which results in a patch. Then apply this to browser. Now imagine if browser makers had to optimize. Start with HTML-A you make very slight modification to that html which creates HTML-B, and then apply the complete HTML-B to browser. Browsers then have to find the diff, create a patch and apply patch all written in highly optimized C/C++ code. I believe this business of diffing and patching should be left to browsers instead of using user-land virtual-dom js code to mess around! Let me know what you feel about it in comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d86ab64be84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React dynamic plugins loading]]></title>
            <link>https://samarjit-samanta.medium.com/react-dynamic-plugins-loading-e45905aa00a7?source=rss-a6779649b7fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45905aa00a7</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-dynamic-plugins]]></category>
            <dc:creator><![CDATA[samarjit.samanta]]></dc:creator>
            <pubDate>Thu, 17 Jan 2019 07:21:50 GMT</pubDate>
            <atom:updated>2019-01-17T07:21:50.980Z</atom:updated>
            <content:encoded><![CDATA[<p>What if you want to write some React component that can be a chart that can be plugged into a remote react application. The remote application does not need to pull your source code and rebuild again in order to use your code.</p><p>What ever I described above can be largely achieved with plain javascript by simply fetching a script and evaluating it in browser.</p><p>How is it different from react lazy loading?</p><p>Ans. React/angular kind of libraries do a lot of magic by statically linking. If you look up some dynamic loading and code splitting tutorial, you will find that entire code is statically parsed and mostly webpack does the code splitting based on routes or whereever dynamic imports are used ()=&gt; import(‘./YourPlugin’) is used.</p><p>You can use ReactDOM.render(‘&lt;YourPlugin/&gt;’, some dom elm) inside your main application. But this becomes two separate applications with no code sharing. In this case the bundle sizes of your plugins will contain entire react code so it will be big.</p><p>I am going to show an approach that will build the plugin code into minimal lib without any library or any redundant code. You can even use <a href="https://babeljs.io/repl">https://babeljs.io/repl</a> to transpile your plugin code without any react dependency.</p><p>Lets first see how to load and render the plugin.</p><pre>loadPlugins() {<br> fetch(&quot;./dist/&quot;+this.state.pluginName+&quot;.plugin.js&quot;)<br> .then((resp) =&gt; resp.text())<br> .then((resp)=&gt;{<br> this.state.components.push(this.state.pluginName);<br> this.pluginRegistry[this.state.pluginName] =  eval(resp).default;<br> this.forceUpdate();<br> });<br> this.forceUpdate();<br>}</pre><pre>render() {<br> return (<br> &lt;div&gt;<br>  &lt;h2&gt;Dynamic Components Loading&lt;/h2&gt;<br>  &lt;input type=&quot;text&quot;  onChange={ (e) =&gt; this.state.pluginName = e.target.value} placeholder=&quot;Plugin Name D1,D2,...D4 etc&quot;/&gt;<br>  &lt;button onClick={this.loadPlugins.bind(this)}&gt;Load&lt;/button&gt;<br>  &lt;div&gt;<br>  {this.state.components.map((componentId) =&gt; {<br>  let Component = this.pluginRegistry[componentId];<br>  return &lt;Component&gt;{componentId}&lt;/Component&gt;;<br>  })}<br>  &lt;/div&gt;<br> &lt;/div&gt;);<br>}</pre><p>The above snippet loads the plugin’s compiled js code using window.fetch() api and then eval() that code. We may be able to inject dynamic script tags or use some loader like requirejs here.</p><p>The plugin code is simple and straightforward</p><pre>import React from &#39;react&#39;;</pre><pre>export default class D2 extends React.Component {</pre><pre>constructor(){<br>    super();<br>    console.log(&#39;D2 loading&#39;)<br>  }</pre><pre>render () {<br>    console.log(&#39;D2 rendering&#39;)<br>    return &lt;div&gt;{this.props.children}&lt;/div&gt;<br>  }</pre><pre>};</pre><p>To make the plugin code not package react, react-dom along with it. We have to compile it as a library using webpack. Note that libraryTarget is ‘window’ which means React will be expected to be available in window object.</p><pre>var path = require(&#39;path&#39;);<br>var APP_DIR = path.resolve(__dirname, &#39;src&#39;);</pre><pre>module.exports = {<br>  mode: &#39;development&#39;,<br>  entry: {<br>    D1: &#39;./src/D1.jsx&#39;,<br>    D2: &#39;./src/D2.jsx&#39;,<br>  },<br>  output: {<br>    path: path.resolve(__dirname, &#39;dist&#39;),<br>    filename: &#39;[name].plugin.js&#39;,<br>    library: &#39;D1plugin&#39;,<br>    libraryTarget:&#39;window&#39;<br>  },<br>  externals: {<br>    react: {<br>      commonjs: &#39;react&#39;,<br>      commonjs2: &#39;react&#39;,<br>      amd: &#39;react&#39;,<br>      window: &#39;React&#39;<br>    }<br>  },<br>  module : {<br>    rules : [<br>        {<br>            test : /\.jsx?/,<br>            include : APP_DIR,<br>            loader : &#39;babel-loader&#39;<br>        }<br>    ]<br>  }<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*kH9Z7yg9b3OqUoW2rAjxtg.png" /><figcaption>Snip of compiled plugin code</figcaption></figure><p>The main lib react and react-dom are loaded as script tags.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;script src=&#39;<a href="https://unpkg.com/react@15.3.2/dist/react.js&#39;">https://unpkg.com/react@15.3.2/dist/react.js&#39;</a>&gt;&lt;/script&gt;<br>    &lt;script src=&#39;<a href="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js&#39;">https://unpkg.com/react-dom@15.3.2/dist/react-dom.js&#39;</a>&gt;&lt;/script&gt;   <br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;script async src=&quot;dist/main.bundle.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;<br>    &lt;div id=&quot;output&quot;&gt;&lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>The complete is code is here.</p><p>To run the code.</p><p>Git clone <a href="https://github.com/samarjit/react-dynamic-plugin">https://github.com/samarjit/react-dynamic-plugin</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CVFMNMRgIqAfgWa6tmeznw.png" /><figcaption>Compile plugins</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*Z5_0_aPI97SNtxb3AQ94jA.png" /><figcaption>Compile main jsx file</figcaption></figure><p>Run http-server in the react-dynamic-plugin folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*9g_PPqpm0EMGzHtjS25GMg.png" /></figure><p>Open the index.html in browser, and run main.load() in console to load the application. Then Enter ‘D1’ in the text field and click ‘Load’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*a_SA3ZMi5_G2gjsB3C2ToQ.png" /></figure><p>The complete source code is available in this project.</p><p><a href="https://github.com/samarjit/react-dynamic-plugin">samarjit/react-dynamic-plugin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45905aa00a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lets build naive redux]]></title>
            <link>https://samarjit-samanta.medium.com/lets-build-naive-redux-159e3caa856b?source=rss-a6779649b7fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/159e3caa856b</guid>
            <category><![CDATA[simpler-redux]]></category>
            <category><![CDATA[redux-internals]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-devtools]]></category>
            <dc:creator><![CDATA[samarjit.samanta]]></dc:creator>
            <pubDate>Mon, 26 Mar 2018 06:19:02 GMT</pubDate>
            <atom:updated>2020-11-05T04:18:26.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoYPs98h596XufXa0awLCA.gif" /></figure><h3>Lets build redux from scratch — naive redux</h3><h4>TL:DR; We will build redux in about 60 lines of code and make it work with redux devtools. Take me straight to code: <a href="https://stackblitz.com/edit/react-ts-redux">https://stackblitz.com/edit/react-ts-redux</a></h4><p>Before we begin let us take a step back and think what is redux?</p><p>It’s a store of data, you can update the store with some events and you can subscribe to stored data change events. Ofcourse you should not think of it as a pub-sub mechanism backed by a event data store. There is a subtle difference. The events which gets published do not get passed down to listeners.</p><blockquote><em>😖 </em>While writing this, I am pondering what will be the consequences if we really received those events back, may be we wont need reactive programming, food for thought!</blockquote><p>Lets get back to redux, it does update the stored data, and notify all subscribers that we have got new data in store. Up to this point I have explained what is within scope of redux. And after this, in a typical react application would have a special type of subscriber called `connect()`, which is a Higher Order Component (HOC) that read the store data and inject relevant parts of it into props of a react component. This `connect()` is part of react-redux project which is out of scope for our naive redux.</p><h3>Let’s visualize</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*1JxavlPpsuz2jVXnv21GnQ.png" /><figcaption>Redux skeleton</figcaption></figure><p>Now lets get acquainted with some terminologies used in redux.</p><p>Event data is `action`. Which typically contains type which is event name and payload. Eg. {type: ‘INCREMENT’, payload: ‘1’}.<br>Triggering event is called `dispatch()`<br>`Reducer` does the job of assimilating payload data into Data Store.<br>`Subscribe()` thankfully do not have strange nomenclature.</p><h3>Blueprint</h3><p>Let’s create a skeleton of necessary functions.</p><pre>class ReduxStore {<br>   storeState: any = undefined;<br>   reducers: Reducer[] = [];<br>   subscriptions: any[] = [];</pre><pre>/* Initialize the store */<br>   createStore() {}<br>  /* provide a method for emitting events. <br>   And also process events and finally call subscribers*/<br>   dispatch() {}<br>  /* loops though reducers array and update storeState*/<br>   runReducers() {}<br>  /* register subscribers */<br>   subscribe() {}<br>  /* return current state */<br>   getState()<br>}</pre><p>We can create a basic typescript project as follows.</p><pre>create-react-app ts-redux --scripts-version=react-scripts-ts</pre><p>First some boilerplate Types definitions since I am going to use TypeScript.</p><pre>/** Naive Redux */<br>export interface Action&lt;T = any&gt; {<br>type: T;<br>}</pre><pre>export interface AnyAction extends Action {<br>// Allows any extra properties to be defined in an action.      [extraProps: string]: any;<br>}</pre><pre>export type Reducer&lt;S = any, A extends Action = AnyAction&gt; = (state: S | undefined, action: A) =&gt; S;</pre><p>Then, the implementation of the blueprint. This is pretty much it.</p><h4>CreateStore</h4><pre>createStore(reducer: Reducer, predefinedState?: any) {<br>     this.reducers.push(reducer);<br>     return this;<br>   }</pre><p>What this function does is initialize the main store. It registers all the data manipulating reducers. You can write other methods to add more reducers. Like redux does with replace reducers. We also have to work with the predefinedStates. You can assign to storeState for now. If you want to capture the default argument value from the reducer. You can run the reducer once with undefined state and undefined action.</p><h4>Dispatch</h4><pre>dispatch(action: AnyAction) {<br>     this.runReducers(action);<br>     for(const publish of this.subscriptions) {<br>       publish();<br>     }<br>   }<br>   <br>runReducers(action: AnyAction) {<br>     for(const reducer of this.reducers) {<br>       const state = reducer(this.storeState, action);<br>       this.storeState = {...this.storeState, ...state};<br>     }<br>   }</pre><p>This function does all the event handling once user calls dispatch. We have to run through all the reducers passing the current storeState. Assume that action is {type: ‘INC’, payload: 1}. So all the reducers that act on ‘INC’ action type will manipulate the state. Ideally it should do in an immutable way. So that we can compare the old and new state to determine whether the storeState actually changed or not. And then publish storeState changed only if there is some real change in store state after running the the reducers. But for simplicity sake we anyway call all the subscribers.</p><p>The complete listing will look like this.</p><pre>export class ReduxStore {<br>  storeState: any = undefined;<br>  reducers: Reducer[] = [];<br>  subscriptions: any[] = [];<br>  constructor() {<br>    this.createStore = this.createStore.bind(this);<br>    this.subscribe = this.subscribe.bind(this);<br>  }<br>  /* Initialize the store */<br>   createStore(reducer: Reducer, predefinedState?: any) {<br>     this.reducers.push(reducer);<br>     return this;<br>   }<br>  /* provide a method for emitting events. <br>   And also process events and finally call subscribers*/<br>   dispatch(action: AnyAction) {<br>     this.runReducers(action);<br>     for(const subs of this.subscriptions) {<br>       subs();<br>     }<br>   }<br>  /* loops though reducers array and update storeState*/<br>   runReducers(action: AnyAction) {<br>     for(const reducer of this.reducers) {<br>       const state = reducer(this.storeState, action);<br>       this.storeState = {...this.storeState, ...state};<br>     }<br>   }<br>  /* register subscribers */<br>   subscribe(fn: ()=&gt;void) {<br>     this.subscriptions.push(fn);<br>   }<br>  getState(){<br>    return this.storeState;<br>  } <br>} <br>export const reduxStore = new ReduxStore();</pre><p>Then use it like regular redux.</p><h4>Create a reducer and store and subscribe to store:</h4><pre>function appReducer(state: {count: number} = { count: 1}, <br>                    action: AnyAction){</pre><pre>  switch(action.type) {<br>    case &#39;INC&#39;: <br>       return {...state, count: state.count + action.payload};<br>    case &#39;DEC&#39;: <br>       return {...state, count: state.count - action.payload};<br>    default: return state;<br>  }<br>}</pre><pre>this.store = reduxStore.createStore(appReducer);</pre><pre>this.store.subscribe( () =&gt; {<br>     console.log(&#39;Store:&#39; + this.store.getState());<br>});</pre><p>Dispatch actions to reduxStore. This is like publishing events.</p><pre>this.store.dispatch({type: &#39;INC&#39;, payload: 1})</pre><p>Output:</p><pre>Store: 1<br>Store: 2</pre><p>That’s all about redux. That wasn’t too difficult.</p><h4>Oh wait. What if I can get chrome redux dev tools to work with my naive redux.</h4><p>Sure, just modify your createStore() with the below code. Original redux has a concept of middlewares. This middleware concept is used to inject redux devtools into our application.</p><p>The first part is handling two overloaded createStore() function where predefinedState can be optional parameter.</p><p>`enhancer()` function is similar to applyMiddleware() provided by a redux. Redux devtools can also use enhancer and run some instrumentation logic on reducers. Basically it takes our reducer and wraps it into a wrappedReducer. It then calls our createStore. So what we store in our reducers[] array is wrappedReducers. Now imagine in our dispatch() function we call wrappedReducer instead of real reducers. These wrapped reducers calls back our original reducers and then calls different action types for updating redux devtools. This is contrived explanation of what happens in redux devtools. Isn’t is amazing that with this little code even redux devtools start to work and even the replay functionality of devtools work.</p><pre>createStore(reducer: Reducer, predefinedState: any, enhancer?: (fn: any) =&gt; any) {<br>        if(typeof(predefinedState) === &#39;function&#39; ) {<br>            enhancer = predefinedState;<br>            predefinedState = undefined;<br>        }<br>        if (enhancer) {<br>            const fnRet = enhancer(this.createStore);<br>            return fnRet(reducer, predefinedState);<br>        }<br>        this.reducers.push(reducer);<br>        this.dispatch({type: &#39;@@redux/INIT&#39;});<br>        return this;<br>}</pre><p>That is all required for simplified redux implementation.</p><p>Posible Enhancement: We can improve one thing which is currently not present in redux. That is pass on events to the subscriber. Often times subscriber gets called multiple times and in this case subscriber can easily react to specific events only.</p><pre>dispatch(action: AnyAction) {<br>     this.runReducers(action);<br>     for(const subs of this.subscriptions) {<br>       subs(action.type);  //Only this line requires changes<br>     }<br>   }</pre><h3>Live running code</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-redux%3Fembed%3D1%26file%3DReduxStore.tsx&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-redux%3Fembed%3D1%26file%3DReduxStore.tsx&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/edf5e0863c2c8dbd57bfb42d10a375fa/href">https://medium.com/media/edf5e0863c2c8dbd57bfb42d10a375fa/href</a></iframe><h3>Conclusion</h3><p>I hope someone gets a better understanding about redux from this writeup.</p><p>Links — Checkout if you want to build a framework like react <a href="https://samarjit-samanta.medium.com/naive-react-3d86ab64be84">https://samarjit-samanta.medium.com/naive-react-3d86ab64be84</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=159e3caa856b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>