<?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 Piyush Chauhan on Medium]]></title>
        <description><![CDATA[Stories by Piyush Chauhan on Medium]]></description>
        <link>https://medium.com/@piyushchauhan?source=rss-3cdd1bb9ae1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VQyHYq6Zmocs3eOMTm31Sg.jpeg</url>
            <title>Stories by Piyush Chauhan on Medium</title>
            <link>https://medium.com/@piyushchauhan?source=rss-3cdd1bb9ae1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:57:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@piyushchauhan/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[A type-safe decision engine in ReScript]]></title>
            <link>https://medium.com/beyond-localhost/a-type-safe-decision-engine-in-rescript-9f8565ca4adc?source=rss-3cdd1bb9ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f8565ca4adc</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[rescript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[webdev]]></category>
            <dc:creator><![CDATA[Piyush Chauhan]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 07:46:23 GMT</pubDate>
            <atom:updated>2026-11-23T17:04:16.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9B1cLtTRhuArl34zyWS2NA.png" /><figcaption>decision engine</figcaption></figure><h4>How a ReScript + Next.js demo runs experiments and rules through one validated registry, with deterministic bucketing and provenance on every decision</h4><p><em>Experiments, rules, and preview overrides through one validated registry, with provenance on every value.</em></p><p><strong>TL;DR:</strong> every variant question becomes one typed decision computed on the server, and every value remembers which layer wrote it. Two experiments cannot write the same field without failing loudly. The engine lives in the Elsewhere demo, a hotel site built with ReScript and Next.js.</p><h3>Why stringly-typed flags keep breaking</h3><p>A flag pipeline starts cheap. Someone puts hero_layout = split in a config table, reads it inside a component, and branches on the string. Nothing connects the read to the write: no compiler knows that splti is a typo, and no test knows which component owns the field.</p><p>Then the experiments multiply. Two of them write the same field, one silently wins, and the bug report says the hero layout flips between requests. Six months later nobody can answer why a particular visitor saw compact, because the value is in a payload and the reason is nowhere. One registry plus one resolve step fixes both problems, and that is the rest of this post.</p><h3>The demo: Elsewhere, a hotel site with experiments baked in</h3><p>I built the demo to test one architecture end to end. It is a hotel and destinations site that renders on the server, reads a SQLite catalog, and ships a development-only inspector. Everything runs from <a href="https://github.com/piyushchauhan2011/rescript-react-nextjs">the Elsewhere repository</a>.</p><p>The code is split three ways, and the dependency direction is the point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1LakkdLOX3O_4yioMSAmVg.png" /><figcaption>decision engine layers</figcaption></figure><p>The engine owns seven decision paths. Nothing else is adjustable, by design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmu1t9cGzv0un2luWtpoRw.png" /></figure><p>Those seven fields are the only surface any experiment or rule may touch, which is what keeps ownership checkable.</p><h3>The request path, end to end</h3><p>A request crosses four layers before any HTML exists. The proxy handles identity, the page route validates and calls the engine, the engine returns a snapshot, and the ReScript React shell renders from that snapshot without re-deriving anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jbfgRR0AlZilxPM-jch3dw.png" /></figure><h3>Decisions are types, not strings</h3><p>Every decision value is a variant. heroLayout is #immersive or #split, destinationCardLayout is #image or #compact, and a renderer that handles one case but not the other fails compilation. That property is why the engine is written in ReScript rather than TypeScript.</p><p>Strings still exist, but only at the wire boundary. @as(&quot;hero.layout&quot;) keeps the JSON key dotted while the value stays a variant, and @tag(&quot;source&quot;) labels every provenance case with the layer that produced it.</p><pre>@genType type page = [#home | #destinations]<br>@genType type variant = [#control | #treatment]<br>@genType type country = [#IN | #US]<br>@genType type heroLayout = [#immersive | #split]<br>@genType type searchLayout = [#overlay | #inline]<br>@genType type cardLayout = [#image | #compact]<br>@genType type columns = [#three | #two]<br>@genType type guideDetail = [#brief | #expanded]</pre><pre>@genType @unboxed<br>type path =<br>  | @as(&quot;hero.layout&quot;) HeroLayout<br>  | @as(&quot;search.layout&quot;) SearchLayout<br>  | @as(&quot;destinationCard.layout&quot;) DestinationCardLayout<br>  | @as(&quot;destinations.columns&quot;) DestinationsColumns<br>  | @as(&quot;offers.visible&quot;) OffersVisible<br>  | @as(&quot;planningGuide.visible&quot;) PlanningGuideVisible<br>  | @as(&quot;planningGuide.detail&quot;) PlanningGuideDetail</pre><pre>@genType<br>type decisionValues = {<br>  @as(&quot;hero.layout&quot;) mutable heroLayout: heroLayout,<br>  @as(&quot;search.layout&quot;) mutable searchLayout: searchLayout,<br>  @as(&quot;destinationCard.layout&quot;) mutable destinationCardLayout: cardLayout,<br>  @as(&quot;destinations.columns&quot;) mutable destinationsColumns: columns,<br>  @as(&quot;offers.visible&quot;) mutable offersVisible: bool,<br>  @as(&quot;planningGuide.visible&quot;) mutable planningGuideVisible: bool,<br>  @as(&quot;planningGuide.detail&quot;) mutable planningGuideDetail: guideDetail,<br>}<br>// Sparse fields are read through the validated string-keyed boundary codec.<br>@genType<br>type decisionPatch = {<br>  @live @as(&quot;hero.layout&quot;) heroLayout?: heroLayout,<br>  @live @as(&quot;search.layout&quot;) searchLayout?: searchLayout,<br>  @live @as(&quot;destinationCard.layout&quot;) destinationCardLayout?: cardLayout,<br>  @live @as(&quot;destinations.columns&quot;) destinationsColumns?: columns,<br>  @live @as(&quot;offers.visible&quot;) offersVisible?: bool,<br>  @live @as(&quot;planningGuide.visible&quot;) planningGuideVisible?: bool,<br>  @live @as(&quot;planningGuide.detail&quot;) planningGuideDetail?: guideDetail,<br>}<br>@genType @tag(&quot;source&quot;)<br>type provenance =<br>  | @as(&quot;default&quot;) Default({})<br>  | @as(&quot;rule&quot;) Rule({id: string})<br>  | @as(&quot;experiment&quot;) Experiment({id: string, variant: variant})</pre><p>The codec helpers below that block (cast, dictionary, objectValue, fail, defaults, validPatchValue, and decodePatch) validate the wire boundary, rejecting unknown paths and out-of-range values before any write happens.</p><h3>One registry owns every experiment and rule</h3><p>Experiments and rules are declared as data, and createDecisionRegistry validates the whole declaration at module load. Duplicate IDs, overlapping allocations, and two owners claiming the same path all throw at startup, so a broken registry never serves a request.</p><pre>@genType<br>let experiments: array&lt;experiment&gt; = [<br>  {<br>    id: &quot;arrival-flow&quot;,<br>    surface: &quot;arrival-flow&quot;,<br>    enabled: true,<br>    allocation: (0, 10000),<br>    owns: [HeroLayout, SearchLayout, DestinationCardLayout],<br>    variants: {<br>      control: {},<br>      treatment: {heroLayout: #split, searchLayout: #inline, destinationCardLayout: #compact},<br>    },<br>  },<br>  {<br>    id: &quot;destination-density&quot;,<br>    surface: &quot;destination-density&quot;,<br>    enabled: true,<br>    allocation: (0, 10000),<br>    owns: [DestinationsColumns],<br>    variants: {control: {}, treatment: {destinationsColumns: #two}},<br>  },<br>  {<br>    id: &quot;planning-guide-detail&quot;,<br>    surface: &quot;planning-guide-detail&quot;,<br>    enabled: true,<br>    allocation: (0, 10000),<br>    owns: [PlanningGuideDetail],<br>    variants: {control: {}, treatment: {planningGuideDetail: #expanded}},<br>  },<br>]</pre><p>Ownership is the strictest of those checks, because it is the one that catches a logic mistake rather than a typo:</p><pre>let conflict = switch previous {<br>      | Some(previous) =&gt; surface == None || previous.surface != surface<br>      | None =&gt; false<br>      }<br>      if own(local, name) || conflict {<br>        let previousOwner = switch previous {<br>        | Some(p) =&gt; p.owner<br>        | None =&gt; owner<br>        }<br>        fail(&quot;Ownership conflict on &quot; ++ name ++ &quot;: &quot; ++ previousOwner ++ &quot; and &quot; ++ owner)</pre><p>That gives a registry with five members:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CH3W4GZejQyEAFNWFOHyzA.png" /></figure><p>Allocation is (0, 10000) on each surface, which is the full slot range: one experiment owns the whole surface and every visitor lands on one of its two variants.</p><h3>Deterministic assignment without server state</h3><p>Assignment is a pure function of the visitor ID plus a namespace string. FNV-1a hashes the concatenation, and the result is reduced twice: modulo 100 picks the 50/50 variant, modulo 10000 picks the slot inside a surface. There is no assignment table, no database write, and no session store.</p><p>That makes assignment replayable. The same cookie and the same experiment ID produce the same variant on a cold server, after a restart, or behind a different edge node, which is the whole reason the engine can run without shared state.</p><pre>/** FNV-1a hashes JavaScript UTF-16 code units, including surrogate pairs. */<br>@genType let fnv1a32 = (input: string): float =&gt; {<br>  let hash = ref(-2128831035)<br>  for index in 0 to length(input) - 1 {<br>    hash.contents = imul(Int.bitwiseXor(hash.contents, charCodeAt(input, index)), 16777619)<br>  }<br>  unsigned(hash.contents)<br>}<br>@genType<br>let bucketForExperiment = (visitorId: string, experimentId: string): int =&gt;<br>  Int.fromFloat(fnv1a32(visitorId ++ &quot;:&quot; ++ experimentId) % 100.)<br>@genType<br>let bucketForSurface = (visitorId: string, surface: string): int =&gt;<br>  Int.fromFloat(fnv1a32(visitorId ++ &quot;:surface:&quot; ++ surface) % 10000.)<br>@genType<br>let assignVariant = (visitorId: string, experimentId: string): DecisionTypes.variant =&gt;<br>  if bucketForExperiment(visitorId, experimentId) &lt; 50 {<br>    #control<br>  } else {<br>    #treatment<br>  }</pre><p>The four externals and the unsigned helper I left out of that snippet bind Math.imul, charCodeAt, length, and the &gt;&gt;&gt; 0 unsigned coercion.</p><p>Both reductions are visible in the geometry of one experiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OEu3z8DquEE-AuBhrcC9A.png" /><figcaption>decision engine allocation</figcaption></figure><p>Slots live in a sorted table per surface, so picking one is a binary search:</p><pre>let findSlot = (table: array&lt;Experiments.experiment&gt;, bucket) =&gt; {<br>  let low = ref(0)<br>  let high = ref(Belt.Array.length(table))<br>  while low.contents &lt; high.contents {<br>    let middle = (low.contents + high.contents) / 2<br>    let (start, _) = Belt.Array.getUnsafe(table, middle).allocation<br>    if start &lt;= bucket {<br>      low.contents = middle + 1<br>    } else {<br>      high.contents = middle<br>    }<br>  }<br>  if low.contents == 0 {<br>    None<br>  } else {<br>    let candidate = Belt.Array.getUnsafe(table, low.contents - 1)<br>    let (_, end) = candidate.allocation<br>    if bucket &lt; end {<br>      Some(candidate)<br>    } else {<br>      None<br>    }<br>  }<br>}</pre><p>The whole path from cookie to variant is one hash, one modulo, and one comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvQ6JMmndFpPw8A4neqVsQ.png" /></figure><h3>Rules: eligibility and effects</h3><p>Experiments and rules both end in a patch, but they get there differently. An experiment is picked by slot and then filtered by eligibleWhen, so a visitor can be in a slot and still hold out. A rule has no allocation at all: its when clause is the entire gate, and it applies whenever that clause is true.</p><pre>@genType @tag(&quot;type&quot;)<br>type rec rule =<br>  | @as(&quot;all&quot;) All({rules: array&lt;rule&gt;})<br>  | @as(&quot;any&quot;) Any({rules: array&lt;rule&gt;})<br>  | @as(&quot;not&quot;) Not({rule: rule})<br>  | @as(&quot;eq&quot;) Eq({@live field: string, value: country})<br>  | @as(&quot;flag&quot;) Flag({name: string})</pre><p>Predicates are data too, and the demo ships two of them:</p><pre>@genType<br>let ruleEffects: array&lt;ruleEffect&gt; = [<br>  {<br>    id: &quot;india-seasonal-offers&quot;,<br>    owns: [OffersVisible],<br>    when_: All({<br>      rules: [Flag({name: &quot;seasonal-offers&quot;}), Eq({field: &quot;visitor.country&quot;, value: #IN})],<br>    }),<br>    patch: {offersVisible: true},<br>  },<br>  {<br>    id: &quot;planning-guide-flag&quot;,<br>    owns: [PlanningGuideVisible],<br>    when_: Flag({name: &quot;planning-guide&quot;}),<br>    patch: {planningGuideVisible: true},<br>  },<br>]</pre><p>decodeRule validates the JSON shape of a predicate and rejects unknown fields, flags, and rule nodes, so evaluateValidatedRule can walk the tree without re-checking anything.</p><h3>Resolution and provenance</h3><p>Resolution applies patches in a fixed order: the selected experiments first, then the rules. A second write to the same path is a failure, not an overwrite, and every write records its source. That pairing is what makes the inspector honest, because a value and its reason are produced by the same line of code.</p><pre>let apply = (patch: decisionPatch, owner, source) =&gt; {<br>    // Registry codecs have validated these wire keys and values already.<br>    let entries: array&lt;(string, unknown)&gt; = Dict.toArray(cast(patch))<br>    entries-&gt;Belt.Array.forEach(((name, value)) =&gt; {<br>      switch getOwn(writtenBy, name) {<br>      | Some(previous) =&gt;<br>        fail(&quot;Decision write conflict on &quot; ++ name ++ &quot;: &quot; ++ previous ++ &quot; and &quot; ++ owner)<br>      | None =&gt; ()<br>      }<br>      Dict.set(writtenBy, name, owner)<br>      switch decodePath(cast(name)) {<br>      | HeroLayout =&gt;<br>        values.heroLayout = cast(value)<br>        provenance.heroLayout = source<br>      | SearchLayout =&gt;<br>        values.searchLayout = cast(value)<br>        provenance.searchLayout = source<br>      | DestinationCardLayout =&gt;<br>        values.destinationCardLayout = cast(value)<br>        provenance.destinationCardLayout = source<br>      | DestinationsColumns =&gt;<br>        values.destinationsColumns = cast(value)<br>        provenance.destinationsColumns = source<br>      | OffersVisible =&gt;<br>        values.offersVisible = cast(value)<br>        provenance.offersVisible = source<br>      | PlanningGuideVisible =&gt;<br>        values.planningGuideVisible = cast(value)<br>        provenance.planningGuideVisible = source<br>      | PlanningGuideDetail =&gt;<br>        values.planningGuideDetail = cast(value)<br>        provenance.planningGuideDetail = source<br>      }<br>    })<br>  }</pre><p>A snapshot for one visitor (country IN, offers=on, arrival-flow treatment) carries a badge per value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hK0504NDG-y4CPhrIkA2Tw.png" /><figcaption>decision engine snapshot</figcaption></figure><p>The order of operations, from query string to provenance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udxDV6ehWsreakGa12F8kw.png" /></figure><h3>Preview overrides and the decision inspector</h3><p>In development, query params force a variant: ?exp.arrival-flow=treatment. The allowlist decides what survives the trip. An unknown key is dropped, and a recognized key whose value is malformed stays in the snapshot as a diagnostic instead of disappearing.</p><pre>let recognized = key =&gt;<br>  key == &quot;country&quot; ||<br>  key == &quot;offers&quot; ||<br>  key == &quot;guide&quot; ||<br>  (String.startsWith(key, &quot;exp.&quot;) &amp;&amp;<br>  own(Experiments.decisionRegistry.experimentById, String.slice(key, ~start=4)))</pre><pre>@genType<br>let validatePageSearch = (input: unknown, production: bool): pageSearch =&gt; {<br>  let result = dictionary()<br>  switch JSON.Decode.object(cast(input)) {<br>  | None =&gt; ()<br>  | Some(source) =&gt;<br>    Dict.toArray(source)-&gt;Belt.Array.forEach(((key, value)) =&gt; {<br>      if (<br>        (key == &quot;destination&quot; || (!production &amp;&amp; recognized(key))) &amp;&amp; Type.typeof(value) == #string<br>      ) {<br>        Dict.set(result, key, (cast(value): string))<br>      }<br>    })<br>  }<br>  result<br>}</pre><p>The decision inspector is a development-only panel that prints every resolved value next to its provenance, lists ignored overrides with their raw values, and lets you flip country, flags, and individual experiments to re-render the page from a new snapshot.</p><h3>Signed cookies and rollout flags</h3><p>Identity is a cookie. In production that cookie is a UUID plus an HMAC-SHA-256 signature: the edge proxy verifies it or issues a new one, and the page verifies it again before the engine sees it. A missing, tampered, or unsigned cookie is treated as no identity at all.</p><pre>function signature(id: string, secret: string): string {<br>  return createHmac(&quot;sha256&quot;, secret).update(id).digest(&quot;hex&quot;);<br>}<br>export function visitorFromCookie(<br>  cookie: string | undefined,<br>  secret: string | undefined,<br>): string | undefined {<br>  if (!secret) {<br>    return cookie &amp;&amp; uuid.test(cookie) ? cookie : undefined;<br>  }<br>  if (!cookie) {<br>    return undefined;<br>  }<br>  const match = /^([0-9a-f-]{36})\.([0-9a-f]{64})$/.exec(cookie);<br>  if (!match || !uuid.test(match[1])) {<br>    return undefined;<br>  }<br>  return timingSafeEqual(<br>    Buffer.from(match[2], &quot;hex&quot;),<br>    Buffer.from(signature(match[1], secret), &quot;hex&quot;),<br>  )<br>    ? match[1]<br>    : undefined;<br>}<br>export function visitorCookie(id: string, secret: string | undefined): string {<br>  return secret ? id + &quot;.&quot; + signature(id, secret) : id;<br>}</pre><p>I left out the uuid regex constant above those functions, which checks the UUID shape before any signature comparison happens.</p><p>Rollout configuration is validated the same way, eagerly, at startup. Flag values accept only on, empty, or absent, and anything else throws before the server listens:</p><pre>function flag(name: string): boolean {<br>  const value = process.env[name];<br>  if (value !== undefined &amp;&amp; value !== &quot;&quot; &amp;&amp; value !== &quot;on&quot;) {<br>    throw new Error(`Invalid ${name}: expected on or empty`);<br>  }<br>  return value === &quot;on&quot;;<br>}</pre><p>The disabled-experiment list and the production cookie secret get the same treatment, both inside readRollout:</p><pre>export function readRollout(): rollout &amp; { cookieSecret: string | undefined } {<br>  const known = new Set(experiments.map((experiment) =&gt; experiment.id));<br>  const disabledIds = [<br>    ...new Set(<br>      (process.env.DECISION_DISABLED_EXPERIMENTS ?? &quot;&quot;)<br>        .split(&quot;,&quot;)<br>        .map((v) =&gt; v.trim())<br>        .filter(Boolean),<br>    ),<br>  ];<br>  for (const id of disabledIds) {<br>    if (!known.has(id)) {<br>      throw new Error(`Invalid DECISION_DISABLED_EXPERIMENTS: unknown experiment ${id}`);<br>    }<br>  }<br>  let cookieSecret: string | undefined;<br>  if (process.env.NODE_ENV === &quot;production&quot;) {<br>    cookieSecret = process.env.DECISION_COOKIE_SECRET;<br>    if (!cookieSecret || Buffer.byteLength(cookieSecret, &quot;utf8&quot;) &lt; 32) {<br>      throw new Error(&quot;Invalid DECISION_COOKIE_SECRET: at least 32 UTF-8 bytes required&quot;);<br>    }<br>  }</pre><p>seasonalOffers and planningGuide are read with the same flag() call, so both accept only absent, empty, or on, and off fails startup.</p><h3>Crossing the ReScript ↔ TypeScript boundary</h3><p>genType emits a .gen.tsx and a .res.mjs per module, which is how the RegistryCore and RegistryUi namespaces become importable TypeScript. @live, @as, and @tag carry the wire contract across, so the TS side sees the same strings the JSON has.</p><p>The React shell needs one context and one hook, and that is the entire UI-side integration:</p><pre>type values = RegistryCore.DecisionTypes.decisionValues<br>let context: React.Context.t&lt;option&lt;values&gt;&gt; = React.createContext(None)</pre><pre>module Provider = {<br>  let make = React.Context.provider(context)<br>}</pre><pre>@react.component<br>let make = (~values: values, ~children) =&gt; &lt;Provider value={Some(values)}&gt; {children} &lt;/Provider&gt;</pre><pre>let useDecision = (selector: values =&gt; &#39;a): &#39;a =&gt; {<br>  switch React.useContext(context) {<br>  | Some(values) =&gt; selector(values)<br>  | None =&gt; JsError.throwWithMessage(&quot;useDecision requires a DecisionProvider&quot;)<br>  }<br>}</pre><p>A page component then reads a single field through that hook, and the field name is checked by the ReScript compiler:</p><pre>let heroLayout = DecisionProvider.useDecision(values =&gt; values.heroLayout)</pre><p>One more adaptation lives in apps/web/src/server/page-data.ts, where resolved, assignments, and ignored are spread into plain objects before they cross into React Flight, because null-prototype dictionaries are not accepted there.</p><h3>What this cost us</h3><p>Registering an experiment is ceremony. Every new one needs an id, a surface, an allocation, an owns list, and both variants declared before anything renders. The registry catches the mistakes at startup, but I still wrote that record by hand each time.</p><p>ReScript is a second compiler and a second syntax. The OCaml heritage shows up in ref, Belt.Array, and pipe-first argument order, and the exhaustiveness that makes the engine safe also means every new path case touches every consumer.</p><p>The wire still speaks strings. hero.layout appears as a string in the JSON, in the serialized snapshot, and in the generated TypeScript types. The variants only exist after validation, which is a real cost in a codebase that is mostly TypeScript.</p><p>Identity is one sticky cookie. Anyone who clears cookies or switches devices is a new visitor to the engine, and there is no cross-device merge.</p><p>Nothing tracks exposure or conversions. The inspector panel states that in one line, and it is accurate: the engine assigns deterministically and reports provenance, and analytics are out of scope for the demo.</p><h3>Run it yourself</h3><p>Node &gt;= 22.12 and pnpm 12.4.2 are the only prerequisites.</p><pre>pnpm install<br>pnpm exec playwright install chromium<br>export DB_FILE_NAME=/absolute/path/to/catalog.db<br>pnpm db:setup<br>pnpm dev</pre><p>Open http://127.0.0.1:3000, then try /?exp.arrival-flow=treatment&amp;country=IN&amp;offers=on to see a forced variant, a forced country, and the India offers rule land in the same snapshot. All of it is in <a href="https://github.com/piyushchauhan2011/rescript-react-nextjs">the Elsewhere repository</a>.</p><h3>FAQ</h3><h3>Why ReScript instead of TypeScript?</h3><p>Exhaustive matching turns an omitted variant into a compile error, and this engine leans on that harder than on any other language feature: a new path case cannot be added without updating every consumer. The typed core is roughly 900 lines of .res across eight modules, with the whole domain expressed as variants.</p><h3>How do I add a new experiment?</h3><p>Add one record to the experiments array in packages/core/src/Experiments.res with an id, a surface, an allocation, an owns list, and both variants. createDecisionRegistry validates it at startup: duplicate IDs, overlapping allocations, and paths already owned by another experiment or rule all throw before a request runs.</p><h3>How do I kill an experiment in production?</h3><p>Set DECISION_DISABLED_EXPERIMENTS to a comma-separated list of registered IDs. Unknown IDs reject startup, and the disabled set is applied to allocation as well as resolution, so a disabled experiment stops writing even if a preview URL forces it.</p><h3>Does it track conversions or metrics?</h3><p>No. The engine assigns a variant deterministically and records which layer wrote each value, and that is all it does. Exposure logging, conversion events, and analysis are out of scope for the demo, which the inspector says in one line.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f8565ca4adc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beyond-localhost/a-type-safe-decision-engine-in-rescript-9f8565ca4adc">A type-safe decision engine in ReScript</a> was originally published in <a href="https://medium.com/beyond-localhost">Beyond Localhost</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a .NET + React Islands Site With a Playwright Snapshot Worker]]></title>
            <link>https://medium.com/@piyushchauhan/how-i-built-a-net-react-islands-site-with-a-playwright-snapshot-worker-9d26a3a5979f?source=rss-3cdd1bb9ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d26a3a5979f</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Piyush Chauhan]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 15:53:02 GMT</pubDate>
            <atom:updated>2026-09-26T15:58:47.189Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Razor owns the pages. React owns a few interactions. A separate browser publishes the finished HTML before anyone visits.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3cZ1d9C8AFBjG3XTs8sCaw.png" /><figcaption>.NET with React Islands</figcaption></figure><h3>The problem: interactive pages without browser rendering per visitor</h3><p>Imagine opening /hotels/casa-aurelia. You should get the hotel&#39;s description, prices, photos, and metadata in the HTML response. Then, if you click a photo, a gallery dialog should open. A client-only SPA that initially sends a nearly empty shell makes discovery of that content depend on executing JavaScript; rendering Chromium on every visitor request would solve a different problem at a high operational cost. I wanted crawlable first-response HTML <strong>and</strong> hydration, without either compromise.</p><p>This project is a hotel-and-editorial site built with ASP.NET Core 10 Razor Pages, React islands, PostgreSQL, and a Node/Playwright worker. The public site has catalog pages, a journal, search, and a stay <strong>inquiry</strong> flow — not a reservation or payment system. Its editors have a separate protected React admin. The awkward part is that the public gallery and other islands begin as empty markers in Razor: rendering only Razor would ship the page content but not the gallery’s initial HTML.</p><p>My solution was to move browser execution to <strong>publication time</strong>. Razor generates the source document; a background Chromium process mounts its islands, validates the result, and saves the completed HTML in PostgreSQL. The public gateway serves that saved document. The visitor’s browser hydrates the already populated islands for interaction. This is browser-rendered React at publication time, <strong>not React server-side rendering in .NET</strong>, and Chromium is not on the visitor request path.</p><h3>Who owns what?</h3><p>The architecture becomes easier to reason about when each layer has a narrow job:</p><p><strong>Owner:</strong> ASP.NET Core Razor Pages<br><strong>Responsibility:</strong> Public routes, catalog and article content, HTML shell, SEO title, description, canonical links, structured data, and no-JS results<br><strong>What it does not own:</strong> React’s interactive state</p><p><strong>Owner:</strong> React islands<br><strong>Responsibility:</strong> Search/date controls, gallery, mobile navigation, and inquiry form interaction<br><strong>What it does not own:</strong> Public-page routing or the catalog’s canonical HTML</p><p><strong>Owner:</strong> React Router admin<br><strong>Responsibility:</strong> Protected editor UI behind the server’s document guard and APIs<br><strong>What it does not own:</strong> Public visitor routes</p><p><strong>Owner:</strong> PostgreSQL<br><strong>Responsibility:</strong> Catalog, snapshot jobs, and published HTML<br><strong>What it does not own:</strong> Browser rendering</p><p><strong>Owner:</strong> Playwright worker<br><strong>Responsibility:</strong> Off-request source-page capture, validation, and conditional publication<br><strong>What it does not own:</strong> Serving a visitor request</p><p>The distinction between content and controls matters. Razor writes the hotel heading, text, cards, and inquiry link. It also renders search results and GET-based sort/pagination so those remain useful without JavaScript. React adds the gallery dialog and richer search controls; those controls do need JavaScript. The admin is deliberately different: it is a protected React Router SPA, not an island pretending to be a public page.</p><p>This arrangement does not claim that every part of the site works without JavaScript. It makes the <strong>public content and search-results path</strong> independently useful while treating interactive controls as an enhancement with an explicit dependency.</p><h3>One request, two paths</h3><p>A canonical public GET or HEAD — such as /hotels/casa-aurelia, a journal post, or bare /search—passes through the snapshot gateway. It looks up a published HTML document by path. The document already includes Razor content <strong>and</strong> the gallery markup produced by Chromium. Only after delivery does the visitor&#39;s React runtime attach behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dtcm6e0JptY4n4KYCXhWog.png" /></figure><h3>How an island becomes published HTML</h3><p>Razor emits an island marker and JSON props. Here is the gallery marker excerpt from the hotel page:</p><pre>&lt;div data-island=&quot;Gallery&quot; data-hydrate=&quot;visible&quot;<br>     data-props=&quot;@(PublicPageModel.IslandProps(new<br>     {<br>         name = hotel.Name,<br>         items = stay.Gallery.Select(x =&gt; new<br>         {<br>             x.Id, x.Src, x.Alt, x.Caption, x.Category, x.RoomId<br>         })<br>     }))&quot;&gt;&lt;/div&gt;</pre><p>_Layout.cshtml likewise supplies the shared MobileNav marker and the runtime script, and owns the document&#39;s metadata. The marker above is empty in the Razor source. data-island selects a dynamically imported component; data-props passes its serialized input; data-hydrate=&quot;visible&quot; tells the <strong>visitor</strong> runtime that it can defer mounting until near the viewport.</p><p>The worker visits /_snapshot-source?path=/hotels/casa-aurelia with a private token. That route only delegates to Razor for an allowed canonical path that has a job or an existing snapshot. On the protected source page, the island runtime mounts <strong>all</strong> markers, even normally deferred ones. When every mount&#39;s effect has run, it sets window.__SNAPSHOT_READY__. Playwright waits for that signal and for successful browser execution before serializing the document. It rejects invalid documents rather than saving a partial render: among its checks are the canonical path, exactly one h1, populated islands, the expected runtime script, absence of private-form inputs and the token, and browser errors. It also strips Chromium-added Vite modulepreload hints and inserts separators between adjacent island text nodes so the saved HTML can hydrate correctly.</p><p>On a visitor’s request, this HTML already contains a gallery grid <strong>inside the same marker</strong>. The runtime checks whether the marker has child markup. Its essential choice is:</p><pre>// Excerpt from the public island runtime; Ready wraps the imported component.<br>if (marker.children.length &gt; 0) hydrateRoot(marker, createElement(Ready))<br>else createRoot(marker).render(createElement(Ready))</pre><p>hydrateRoot attaches to captured markup; createRoot fills an empty marker in live Razor development or another uncaptured context. Visitors defer visible islands with IntersectionObserver (with a near-viewport margin), whereas the source-page capture mounts them eagerly. There is no duplicate static gallery fallback sitting beside a second React gallery. Without JavaScript, the published gallery grid and Razor text are still present, but its dialog and other island controls will not work.</p><p>This is testable as behavior, not just a design sketch. The repository’s tests/e2e/hydration.spec.ts reads the published hotel HTML and finds one .gallery-grid inside the gallery island with no duplicate fallback. It then loads that hotel page, opens a gallery image, advances to the next photo, and closes the dialog. The static representation survives delivery and the same representation gains interaction.</p><h3>Publishing without serving stale work</h3><p>The worker needs a precise answer to a race: what if an editor changes the hotel again while Chromium is rendering the first change? Saving that first render afterward would roll the public page backward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*88zxmXKmXmuuRmE8-fu1Pw.png" /></figure><p>Admin publication and affected-route invalidation share a database transaction. Editing a hotel can affect its own route, destination listing/detail, bare search, home page, offer pages, and published articles that embed catalog records. Renames include old paths. A route that is no longer published loses its snapshot and job immediately rather than retaining discoverable old HTML. Valid published routes get a new desired job version.</p><p>The worker leases due jobs using PostgreSQL FOR UPDATE SKIP LOCKED, renders the protected Razor source in its own Chromium context, and checks the job&#39;s <strong>current</strong> desired version under a row lock before inserting/updating the HTML and deleting the job in one transaction. If the version changed, it discards the obsolete capture. Errors never publish a partial document: the job is released and retried with exponential backoff. The old complete snapshot stays available while a published route is regenerated.</p><p>A first-time canonical path has no old document to serve. If it is queued, the gateway responds 503 with Retry-After: 5 until publication succeeds. Unknown or unpublished detail routes return 404 (the fixed canonical index routes can return 503 while their first capture is pending). Once a route is unpublished or renamed, its persisted HTML is removed immediately; already cached copies may still live for the declared cache window, so publication and caching policy must be understood together.</p><h3>What must never be snapshotted</h3><p>The easiest way to leak private data would be to treat the snapshot store as a generic response cache. It is not. Its key is a canonical public <strong>path</strong>, not arbitrary combinations of query string, cookies, authentication, or POST body. Filtered search remains a live private response. The inquiry flow carries personal input, is CSRF-protected, and must remain private. Admin sessions and protected API responses cannot become public snapshots either.</p><p>The source endpoint is also a security boundary. It requires a sufficiently long SNAPSHOT_INTERNAL_TOKEN, compares the supplied header, rejects unrecognized canonical routes, sends private, no-store and noindex, and should be blocked from the public ingress as well. A robots directive alone would not secure it. The worker restricts fetched resources to its configured API origin and validates the captured result before publication; neither check replaces proper network isolation and authentication.</p><p>The worker rejects a source document containing password or antiforgery inputs, a token string, unexpected executable scripts, missing canonical metadata, unrendered islands, or browser errors. These checks are a publishing guard, not a blanket proof that arbitrary application data is safe to cache. The safe baseline remains an explicit allowlist of canonical public routes and a separate live/private path for anything user-specific.</p><h3>The SEO advantage over a client-only SPA</h3><p>A client-only SPA can be indexed by search engines that render JavaScript, but its initial HTML may contain little more than an app root. Content discovery then depends on fetching and running scripts successfully; rendering can be delayed or missed by crawlers that do not execute them. A React SPA with SSR or prerendering does <strong>not</strong> have that limitation by definition. The comparison here is with a <strong>client-rendered shell</strong>, not with all SPAs.</p><p>For a published hotel URL, a crawler’s first HTML response already contains the hotel heading, description, links, gallery markup, and metadata. It does not have to execute React to discover the principal content. Razor provides the page-specific title and description, a canonical URL, and Hotel JSON-LD; the worker preserves these in the published document. The gateway generates robots.txt and an XML sitemap of catalog-published canonical routes. When a route is unpublished, it is removed from that sitemap and its stored HTML is deleted. Bare /search is canonical; filtered search URLs specify noindex,follow to avoid indexing many query variants. Inquiry and admin documents are marked noindex and are not public snapshots.</p><p>This is the outcome I like about prerender-then-hydrate designs: <strong>content is present before client JavaScript, while controls become interactive after hydration</strong>. It shares that goal with several other rendering strategies, but the publication boundary here is different.</p><p>The concrete SEO benefit is a more reliable path for crawlers to discover and assess canonical content, links, and metadata. It is not a guaranteed ranking. A sitemap is a discovery hint, structured data does not guarantee a rich result, and an indexable response does not mean a search engine will index or rank it. A newly queued URL returns 503 until its first capture; finish publication before directing production traffic or crawlers to it. After an origin change, wait for republishing and check the actual canonical URLs in the returned HTML: PUBLIC_ORIGIN is embedded at capture time. Old cached pages can also persist briefly after an edit or removal.</p><p>Lighthouse audits the loaded page, so it is not a direct test of what a no-JavaScript crawler sees. Here, the first response already exposes content and metadata, while off-request publication avoids Chromium work on the visitor path; both are useful starting conditions. But a high Lighthouse <strong>performance</strong> score is not automatic: React chunks, CSS, images, fonts, server/cache behavior, hydration work, and audit settings still affect LCP, CLS, and interactivity. Deferred visible islands and removal of captured modulepreload hints can reduce unnecessary upfront work. Audit the <strong>published snapshot</strong>, not Vite HMR: the repository documents make lighthouse-https for a local HTTPS run and pnpm lighthouse for its desktop preset. Compare repeated runs under the same conditions and inspect the generated HTML, canonical, robots directives, sitemap, and metric breakdown rather than quoting a single score.</p><h3>How SSR, SSG, ISR, and PPR compare</h3><p>These names describe <strong>when and where HTML is produced</strong>, not whether React can hydrate it. Each can ship crawlable HTML when configured to render the actual public content. The useful question for this site was where to pay the rendering cost and how to update edited catalog pages.</p><p><strong>Strategy:</strong> SSR (server-side rendering)<br><strong>When HTML is produced:</strong> On each request, potentially cached afterward<br><strong>Advantage:</strong> Fresh request-specific data; a natural fit for personalized search or inquiry pages<br><strong>Cost or mismatch for this site:</strong> Uncached rendering and data access add request-path work; cache keys and private data need care</p><p><strong>Strategy:</strong> SSG (static site generation)<br><strong>When HTML is produced:</strong> At build time<br><strong>Advantage:</strong> Simple, fast delivery of already complete public HTML<br><strong>Cost or mismatch for this site:</strong> Catalog edits or new pages need a rebuild and redeploy unless another regeneration mechanism is added</p><p><strong>Strategy:</strong> ISR (incremental static regeneration)<br><strong>When HTML is produced:</strong> Initially prerendered or generated on demand, then regenerated after revalidation<br><strong>Advantage:</strong> Reuses HTML between visits and can refresh without rebuilding the whole site<br><strong>Cost or mismatch for this site:</strong> Refresh policy and stale windows must be managed; in the common request-triggered model, regeneration waits for traffic</p><p><strong>Strategy:</strong> PPR (Partial Prerendering)<br><strong>When HTML is produced:</strong> Static shell prepared ahead of time; dynamic regions render and stream at request time<br><strong>Advantage:</strong> Static content can arrive early while request-specific regions stay dynamic<br><strong>Cost or mismatch for this site:</strong> More per-request rendering and cache-boundary coordination than these wholly public canonical documents need</p><p><strong>Strategy:</strong> This site’s snapshot publication<br><strong>When HTML is produced:</strong> Razor source plus browser-mounted islands captured for queued paths after catalog edits or release changes, then stored in PostgreSQL<br><strong>Advantage:</strong> Full public HTML and hydrated controls, with no Chromium on visitor requests; versioned jobs can target affected routes<br><strong>Cost or mismatch for this site:</strong> Publication delay, first-capture 503, and a database/browser worker to operate; private routes still need live rendering</p><p>The closest analogy is ISR’s <strong>last-good HTML while regenerating</strong>, not an identical implementation. This worker queues affected paths when editors publish, captures eagerly in the background, and discards a capture if its desired version changed. It does not wait for a visitor or a timer to trigger regeneration. PPR is also not what happens here: the canonical snapshot is a complete shared document, not a static shell with request-time streamed islands. The project’s filtered search and inquiry pages use live Razor responses instead. <a href="https://nextjs.org/docs/app/guides/incremental-static-regeneration">Next.js describes ISR’s request-triggered revalidation</a> and <a href="https://nextjs.org/docs/app/getting-started/caching">its static-shell/streamed-region model</a>; those are comparisons, not dependencies of this .NET implementation.</p><h3>Tradeoffs and running it</h3><p>The split removes Chromium from visitor latency, but adds a publication pipeline. An edit can take time to appear; a new page waits for its first successful capture. If the worker, Chromium, or PostgreSQL is unavailable, publication stalls even while an old complete snapshot may continue to be served. No performance score or SEO result follows automatically from this architecture: measure the deployed site and audit the generated document.</p><p>Locally I use two different modes from the repository root:</p><pre>pnpm dev             # Live Razor pages and Vite HMR; no snapshot worker required<br>pnpm dev:snapshots   # Build Vite manifest; run .NET plus continuous worker</pre><p>The production-like mode needs PostgreSQL, a valid internal token, and Playwright Chromium; the quick-start guide covers initial setup and seeding. When it first starts, a new canonical route may answer 503 until captured. Failed jobs back off rather than writing half a page, so a persistent 503 is a reason to inspect worker logs and the snapshot job table—not to bypass the gateway.</p><p>Deploy the API and worker from the <strong>same release</strong>: the worker’s asset fingerprint includes the Vite manifest, relevant source files, and PUBLIC_ORIGIN. A changed fingerprint requeues stored pages; changing PUBLIC_ORIGIN matters because canonical links are embedded in HTML. Keep old hashed assets available while old snapshots still reference them, and restart a running API after rebuilding its manifest in snapshot mode. Otherwise an intact stored page can point at a chunk the server no longer serves. These are operational costs of publishing HTML with client-side hydration rather than computing every page on demand.</p><h3>The design rule I kept</h3><p>Give the public document a single owner and give interactivity a clear boundary. Here, Razor defines the public page and its metadata; a background browser completes its islands once for publication; React hydrates that exact markup for visitors. The protected admin and user-specific flows never cross into the public snapshot store.</p><p>That buys immediately useful content without putting Chromium on each request. It also makes the limitations visible: editorial publication delay, a PostgreSQL-and-browser worker to operate, JavaScript required for controls, and strict route/cache/security boundaries. For this site, those are easier to reason about than making the entire public experience depend on a client-rendered shell or hiding a browser render in the request path.</p><blockquote><em>Github: </em><a href="https://github.com/piyushchauhan2011/dotnet-islands"><em>https://github.com/piyushchauhan2011/dotnet-islands</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d26a3a5979f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type-checked and maintainable CSS using aphrodite with Next.js —(1)]]></title>
            <link>https://medium.com/@piyushchauhan/type-checked-and-maintainable-css-using-aphrodite-with-next-js-1-7b10230ef721?source=rss-3cdd1bb9ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b10230ef721</guid>
            <category><![CDATA[react-with-styles]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[aphrodite]]></category>
            <dc:creator><![CDATA[Piyush Chauhan]]></dc:creator>
            <pubDate>Thu, 17 Oct 2019 07:19:20 GMT</pubDate>
            <atom:updated>2019-10-17T07:19:20.119Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered if you could have type-checked your CSS classes or have them linted using eslint before committing or pushing your work to source control?</p><p>In this part 1 of the article, we are going to explore a fresh look at approaching the problem of writing maintainable and type-checked CSS using packages like <a href="https://github.com/Khan/aphrodite">aphrodit</a>e! Since this is one of the approaches from the recent “css-in-js” way of writing stylesheets, so if you are familiar with other approaches in “css-in-js” like styled-components or emotion , then moving forward will give less value to you, but I would advise having a look if you want to understand them using typescript .</p><p>Recently, I came across the <a href="https://github.com/Khan/aphrodite">aphrodite</a> package from Khan Academy which allows you to write styles in .jsx and .tsx and has good support for type checking CSS with typescript. The object created from helper class method StyleSheet.create() can be utilized to access the element classes which are already type-checked and have autocompletion.</p><h4>Setting up <a href="https://nextjs.org/">Next.js</a> Application</h4><p>We will be relying on <a href="https://nextjs.org/">Next.js</a> and <a href="https://reactjs.org/">React</a>, so if you are not familiar with them I would advise checking the official documentation by clicking links respectively.</p><p>Next.js already has an example project on aphrodite which we will be utilizing to bootstrap the current project.</p><pre>yarn create next-app --example with-aphrodite with-aphrodite-app<br>cd with-aphrodite-app<br>yarn add typescript @types/aphrodite @types/node @types/react @types/react-dom -D</pre><p>If you don’t like above approach you can bootstrap from scratch using below,</p><pre>mkdir with-aphrodite-app<br>cd with-aphrodite-app &amp;&amp; yarn init -y<br>yarn add next react react-dom aphrodite<br>yarn add typescript @types/aphrodite @types/node @types/react @types/react-dom -D</pre><pre>mkdir pages<br>touch pages/_document.js</pre><p>and populate the content of _document.js file with the following,</p><pre>// Following is necessary for SSR to work properly</pre><pre>import Document, { Head, Main, NextScript } from &quot;next/document&quot;;<br>import { StyleSheetServer } from &quot;aphrodite&quot;;</pre><pre>export default <em>class</em> MyDocument extends <em>Document</em> {<br>  <br>  static async getInitialProps({ <em>renderPage</em> }) {<br>    <em>const</em> { html, css } = StyleSheetServer.renderStatic(() <em>=&gt;</em> renderPage());<br>    <em>const</em> ids = css.renderedClassNames;<br>    return { ...html, css, ids };</pre><pre>  }</pre><pre>  <em>constructor</em>(<em>props</em>) {<br>    super(props);<br>    <em>const</em> { __NEXT_DATA__, ids } = props;<br>    if (ids) {<br>      __NEXT_DATA__.ids = this.props.ids;<br>    }<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;html&gt;<br>        &lt;Head&gt;<br>          &lt;style data-aphrodite dangerouslySetInnerHTML={{ __html: this.props.css.content }} /&gt;<br>        &lt;/Head&gt;<br>        &lt;body&gt;<br>          &lt;Main /&gt; <br>          &lt;<em>NextScript</em> /&gt;<br>        &lt;/body&gt;<br>      &lt;/html&gt;<br>    );<br>  }<br>}</pre><p>and make sure package.json has the following,</p><pre><em>&quot;scripts&quot;</em>: {<br>  <em>&quot;dev&quot;</em>: &quot;next&quot;,<br>  <em>&quot;build&quot;</em>: &quot;next build&quot;,<br>  <em>&quot;start&quot;</em>: &quot;next start&quot;<br>},</pre><p>To start with we will modify our pages index.js file and convert it to index.tsx . This is possible because next.js has out-of-box typescript support. Go ahead and paste the following <em>(the example is taken straight from aphrodite docs)</em> as our starting point:</p><pre>import React, { Component } from &#39;react&#39;;<br>import { StyleSheet, css } from &#39;aphrodite&#39;;<br><br>export default class App extends Component {<br>    render() {<br>        return &lt;div&gt;<br>            &lt;span className={css(styles.red)}&gt;<br>                This is red.<br>            &lt;/span&gt;<br>            &lt;span className={css(styles.hover)}&gt;<br>                This turns red on hover.<br>            &lt;/span&gt;<br>            &lt;span className={css(styles.small)}&gt;<br>                This turns red when the browser is less than 600px width.<br>            &lt;/span&gt;<br>            &lt;span className={css(styles.red, styles.blue)}&gt;<br>                This is blue.<br>            &lt;/span&gt;<br>            &lt;span className={css(styles.blue, styles.small)}&gt;<br>                This is blue and turns red when the browser is less than<br>                600px width.<br>            &lt;/span&gt;<br>        &lt;/div&gt;;<br>    }<br>}<br><br>const styles = StyleSheet.create({<br>    red: {<br>        backgroundColor: &#39;red&#39;<br>    },<br><br>    blue: {<br>        backgroundColor: &#39;blue&#39;<br>    },<br><br>    hover: {<br>        &#39;:hover&#39;: {<br>            backgroundColor: &#39;red&#39;<br>        }<br>    },<br><br>    small: {<br>        &#39;@media (max-width: 600px)&#39;: {<br>            backgroundColor: &#39;red&#39;,<br>        }<br>    }<br>});</pre><p>With the above in place, you should be able to leverage the auto-completion support as shown in the figure!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADu2KCcBGFE5w1WGzV2W6g.png" /><figcaption>StyleSheet aphrodite autocompletion</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KvWZYLBF0ltiT-zeJBofRg.png" /><figcaption>Autocompletion support with aphrodite</figcaption></figure><p>Go ahead and try visiting our application on localhost:3000 by running yarn dev from terminal. You should be able to see the following, which doesn’t look pretty but we have some CSS that is now properly type-checked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkYjsCAgUVcwIELIIP7wKw.png" /></figure><p>We can try leveraging our javascript skills and move out commonly used colors in a constant variable object</p><pre><em>const</em> THEME = {<br>  color: {<br>    primary: &#39;red&#39;,<br>    secondary: &#39;blue&#39;,<br>  },<br>};</pre><p>This will allow us to be consistent with our theme colors everywhere. Try replacing backgroundColor: &#39;red&#39; with backgroundColor: THEME.color.primary and similarly blue with THEME.color.secondary</p><p>You can also try extracting out backgroundColor: THEME.color.primary,</p><pre>const primaryStyle = {<br>  backgroundColor: THEME.color.primary,<br>};</pre><pre>// ...utilize destructuring</pre><pre>red: {<br>  ...primaryStyle<br>},<br>hover: {<br>  &#39;:hover&#39;: {<br>    ...primaryStyle<br>  }<br>},</pre><p>We can also replicate mixins from SCSS using plain javascript functions.</p><pre>function applyShadow(type:&#39;normal&#39;|&#39;hover&#39;) {<br>  switch (type) {<br>    case &#39;normal&#39;:<br>      return {<br>        boxShadow: &#39;0 2px 20px 0 rgba(0, 0, 0, 0.1)&#39;,<br>      };<br>    case &#39;hover&#39;:<br>      return {<br>        boxShadow: `<br>          0 2px 2px 0 rgba(0, 0, 0, 0.1), 0 2px 4px 0 rgba(0, 0, 0, 0.1),<br>          0 4px 8px 0 rgba(0, 0, 0, 0.1), 0 8px 16px 0 rgba(0, 0, 0, 0.1),<br>          0 16px 32px 0 rgba(0, 0, 0, 0.1)<br>        `,<br>      }<br>    default:<br>      return {<br>        boxShadow: &#39;0 2px 4px 0 rgba(0, 0, 0, 0.2)&#39;,<br>      }<br>  };<br>}</pre><pre>// ...use it like<br>red: {<br>  ...applyShadow(&#39;normal&#39;),<br>}</pre><p>You can also try replacing box-shadow colors and spacing values to different constants which can be fixed as per the theme guidelines. This allows us to not switch between SCSS and JS syntax and gives us the flexibility to leverage our existing JS skills. Other concepts like @extend .class and modules can also be replicated in the js world. We also get linting for free with eslint setup. Try setting up eslint and eslint-plugin-react with typescript or better include husky to lint styles before pushing to version control. We also get tree-shaking and conflict-free naming for free!</p><h4>Disadvantages</h4><ol><li>Including the library will have an overhead of increasing js file size by 7.23kb, a small price to pay for the type-checked syntax.</li><li>For a simple project, using the current library can be overkill and type-checked CSS could be overhead for lot of co-workers in the company.</li><li>Missing theming capabilities, but can be replicated by using Context&#39;s Provider and Consumer or hooks, more on this in coming articles…</li></ol><p>There are a lot of things to fix while creating a design system or in a big project like colors, shadows, spacing, typography etc… While writing plain CSS and SCSS, we either miss a lot of these or have to switch context between SCSS syntax and JS syntax. As per my experience, utilizing above approach can benefit team in the long-running project.</p><p>In the next part of this series, we will cover theming capabilities using the <a href="https://github.com/airbnb/react-with-styles">react-with-styles</a> library from Airbnb which has support for aphrodite.… It uses a higher-order function to wrap components with styles. The HOC returns a style object which can be utilized to access the element classes which are already type-checked and have autocompletion. It has good support for next.js and has a theming ability which can be utilized to define the design system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b10230ef721" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging C and C++ with VSCode]]></title>
            <link>https://medium.com/@piyushchauhan/debugging-c-and-c-with-vscode-77dae50eaf7f?source=rss-3cdd1bb9ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/77dae50eaf7f</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Piyush Chauhan]]></dc:creator>
            <pubDate>Wed, 31 Aug 2016 14:00:20 GMT</pubDate>
            <atom:updated>2016-08-31T14:00:20.020Z</atom:updated>
            <content:encoded><![CDATA[<p>Let us setup our favourite editor — Visual studio code to have debugging support for c and c++ projects or files. If you don’t have vscode editor, I suggest downloading it from <a href="http://code.visualstudio.com/">here</a> and have a play with it. It’s a good community driven and Microsoft effort to have a nice ecosystem around JavaScript and TypeScript apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*5egeoknfCLA962aij-ohgg.png" /><figcaption>Visual studio Code — Credits: Microsoft http://code.visualstudio.com</figcaption></figure><p>Now to have debugging enabled for C/C++ language, please download the C/C++ extension from Microsoft from the extensions tab as shown above. Just click ‘Install’ and it will setup automatically.</p><p>I’m on osx and love `clang` support with `lldb` which makes it easy to debug string, collections nicely. You can type a basic c++ program and use lldb to debug it like below.</p><pre>#include &lt;iostream&gt;</pre><pre>using namespace std;</pre><pre>int main() {<br>    string message = &quot;Hello World&quot;;<br>    cout &lt;&lt; message &lt;&lt; endl;<br>    return 0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*6rYQeyOzcI5MBUryLoAr-A.png" /><figcaption>clang++ and lldb debugging</figcaption></figure><p>Ok but we want nicety of debugging with visual editor and do the same step into and analysing tasks visually. So, go ahead and enter the above program by making a new folder and copy-paste it in a file namely `main.cpp`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*9adUWgy1Fu50oZQoSN3qSA.png" /><figcaption>cpptrial/main.cpp</figcaption></figure><p>Let’s go to debugging tab now and click the gear icon with red dot and select C++ (gdb/lldb) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*HNEbDDhRPMnmF0JZm6skkg.png" /><figcaption>Environment for debugging</figcaption></figure><p>It will create launch.json file and allow to customise the options for the project. We will change “program” and “externalConsole” fields under “configurations”. Set these two to below values. Do it for both “C++ Launch” and “C++ Attach”. You can select the “name” when you will try to debug the program. “C++ Attach” is useful in cases when the program is running elsewhere from command line or using other IDE. We will be sticking with “C++ Launch” in this article.</p><pre>&quot;program&quot;: &quot;${workspaceRoot}/a.out&quot;,<br>&quot;externalConsole&quot;: false</pre><p>Now press `Cmd + shift + B` on osx or `Ctrl + shift + B` on windows/linux to “Configure Task Runner”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*27UnMuEYH5NWeOXex-5Hyg.png" /><figcaption>Task Runner Config</figcaption></figure><p>Select “Others” after clicking to “Configure Task Runner”. It will create `tasks.json` file. Replace the file with the contents below.</p><pre>{<br>    // See <a href="https://go.microsoft.com/fwlink/?LinkId=733558">https://go.microsoft.com/fwlink/?LinkId=733558</a><br>    // for the documentation about the tasks.json format<br>    &quot;version&quot;: &quot;0.1.0&quot;,<br>    &quot;command&quot;: &quot;clang++&quot;,<br>    &quot;isShellCommand&quot;: true,<br>    &quot;args&quot;: [&quot;main.cpp&quot;, &quot;-std=c++11&quot;, &quot;-g&quot;],<br>    &quot;showOutput&quot;: &quot;always&quot;<br>}</pre><p>Now you can press `Cmd + shift + B` on osx or `Ctrl + shift + B` on windows/linux to build the program `a.out` with debugging symbols. Go ahead set a breakpoint on line 7 and click on the `run` button in debug tab to start the debugger. You will see something like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*Gql25yVOnlg7XKhJDzn9Nw.png" /><figcaption>Final c/c++ debugging with vscode</figcaption></figure><p>Not the best support but it works, you can do same operations like step in, out, over, continue, hit breakpoints, inspect etc. There is still on-going improvements in this area as the lldb output of print has better inspection than above. I also tried creating `stack` and analysing it with lldb and vscode, and lldb still have pretty print in there. Outputs shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NtRkdBr0V03sqVMV0iDvTA.png" /><figcaption>stack debugging comparison vscode</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*UkCzZQwsfY_jk3vBQwUk5A.png" /><figcaption>stack debugging comparison lldb</figcaption></figure><p>I hope the above will improve in future but i’m still enjoying the support for debugging, the editor is really fast and a nice syntax highlight support, backed by Microsoft and community effort. Cool!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77dae50eaf7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic graph algorithms in Kotlin]]></title>
            <link>https://medium.com/@piyushchauhan/basic-graph-algorithms-in-kotlin-8b84beda8907?source=rss-3cdd1bb9ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b84beda8907</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[depth-first-search]]></category>
            <category><![CDATA[breadth-first-search]]></category>
            <dc:creator><![CDATA[Piyush Chauhan]]></dc:creator>
            <pubDate>Tue, 21 Jun 2016 23:34:47 GMT</pubDate>
            <atom:updated>2016-06-21T23:34:47.388Z</atom:updated>
            <content:encoded><![CDATA[<p>I decided to write more programs in Kotlin language. Since, I’ve a computer science background, my favourite part of programming is implementing algorithms and understand how language can simplify their implementation. We will cover two popular and basic algorithms for graph search which are Depth first search and Breadth first search. Specifically we will have a graph with components in it i.e. not all nodes are connected and they form connected components. Below is the graph for it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*mBUDJ3hBBHhl_P7HbhIgDA.jpeg" /></figure><p>The input output format is as follows which is taken from a stack-overflow question,</p><p><a href="http://stackoverflow.com/questions/25671618/c-depth-first-search-dfs-implementation">C++ Depth First Search (DFS) Implementation</a></p><pre>Input:        Output:<br>9 7           Component 1: 0 1 2 3 4<br>0 1           Component 2: 5<br>1 2           Component 3: 6 7 8<br>1 3           There are 3 connected components<br>2 3<br>3 4<br>6 7<br>6 8</pre><p>So let’s walk through Depth first search initially. We will the recursive implementation of DFS from wikipedia from,</p><p><a href="https://en.wikipedia.org/wiki/Depth-first_search">Depth-first search - Wikipedia</a></p><pre>1  <strong>procedure</strong> DFS(<em>G</em>,<em>v</em>):<br>2      label <em>v</em> as discovered<br>3      <strong>for all</strong> edges from <em>v</em> to <em>w</em> <strong>in</strong> <em>G</em>.adjacentEdges(<em>v</em>) <strong>do</strong><br>4          <strong>if</strong> vertex <em>w</em> is not labeled as discovered <strong>then</strong><br>5              recursively call DFS(<em>G</em>,<em>w</em>)</pre><p>Here is what I implemented for DFS and finding connected components in Kotlin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3015a39d1e69ac878a6865fd9c864bd/href">https://medium.com/media/d3015a39d1e69ac878a6865fd9c864bd/href</a></iframe><p>The important things worth mentioning here is the use of `forEach`with `it` variable and ranges from Kotlin helped me quite a lot. Use of `Pair` and variable like `tv.first` is also helpful.</p><pre>enum class Color {<br>    BLACK, WHITE<br>}</pre><pre>var <em>vert</em>: MutableList&lt;Color&gt; = <em>mutableListOf</em>()<br>var <em>adj</em>: MutableList&lt;MutableList&lt;Pair&lt;Int, Int&gt;&gt;&gt; = <em>mutableListOf</em>()</pre><p>vert is a list of `Color` enum which is used track the visit status of each node. WHITE denotes if it’s unvisited while BLACK means it’s visited. adj maintains are graph in the form of adjacency list which `list of list of Pairs`. Pair contains two numbers of which first denotes the node and second denotes the weight associated with that edge which is in this case is `1`.</p><p>Most of the part is spent in reading the input and doing variable declaration. Apart from that, the core DFS is very small.</p><pre><strong>fun</strong> dfs(u: <strong>Int</strong>) {<br>    <em>vert</em>[u] = Color.BLACK<br>    <strong><em>print</em></strong>(&quot; $u&quot;)<br>    (0..<em>adj</em>[u].size-1).<strong><em>forEach</em></strong><em> </em><strong>{<br>        val</strong> tv = <em>adj</em>[u][<strong>it</strong>]<br>        if(<em>vert</em>[tv.<strong>first</strong>] == Color.WHITE) <em>dfs</em>(tv.<strong>first</strong>)<br>    <strong>}<br></strong>}</pre><p>Now let’s quickly go through BFS implementation. We will use the following wiki article as reference,</p><p><a href="https://en.wikipedia.org/wiki/Breadth-first_search">Breadth-first search - Wikipedia</a></p><p><strong>Pseudocode</strong>:</p><pre><strong>Breadth-First-Search</strong>(Graph, root):</pre><pre><strong>for</strong> <strong>each</strong> node n <strong>in</strong> Graph:<br>    n.distance = <strong>INFINITY</strong><br>    n.parent = <strong>NIL</strong></pre><pre>create empty queue Q</pre><pre>root.distance = 0<br>    Q.enqueue(root)</pre><pre><strong>while</strong> Q is <strong>not</strong> <strong>empty</strong>:</pre><pre>current = Q.dequeue()</pre><pre><strong>for</strong> <strong>each</strong> node n that is adjacent to current:<br>        <strong>if</strong> n.distance == <strong>INFINITY</strong>:<br>          n.distance = current.distance + 1<br>          n.parent = current<br>          Q.enqueue(n)</pre><p>Here is implementation in Kotlin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f74b775dc9516ae11485e36eb8e25fd/href">https://medium.com/media/5f74b775dc9516ae11485e36eb8e25fd/href</a></iframe><p>Make sure you use the following variables and enum class.</p><pre>enum class Color {<br>    BLACK, WHITE<br>}<br>var <em>adj</em>: MutableList&lt;MutableList&lt;Pair&lt;Int, Int&gt;&gt;&gt; = <em>mutableListOf</em>()</pre><p>We make use of a `data class Node` to keep track of color for visiting, distance and parent of the node while doing BFS.</p><p>You can follow or clone my repository on github for other adventures in Kotlin during my practice,</p><p><a href="https://github.com/piyushchauhan2011/kotlin-practice/tree/master/src/main/kotlin">piyushchauhan2011/kotlin-practice</a></p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b84beda8907" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resources in Kotlin]]></title>
            <link>https://medium.com/@piyushchauhan/resources-in-kotlin-e1a07eeb5886?source=rss-3cdd1bb9ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1a07eeb5886</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[first-post]]></category>
            <category><![CDATA[resources]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Piyush Chauhan]]></dc:creator>
            <pubDate>Sat, 18 Jun 2016 15:27:51 GMT</pubDate>
            <atom:updated>2016-06-18T16:03:57.878Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YK5PLgDKciZ0J66Ilvb9wQ.png" /></figure><p>This is my first post after exploring little about Kotlin and reading the tutorials from kotlinlang.org. There isn’t much, I have included except the resources I found useful while learning kotlin language, could be useful for people exploring and learning about it.</p><p>Below is an example program demonstrating the create and read operation for Bank Account. In this, we have been given a file Bank-Account.txt with fields account number, account holder name, account type, interest rate and current balance. The task is to read in the file and create a workflow of adding, updating, deleting and reading the list of bank accounts available currently in sorted order.</p><p>I have gone ahead and coded create and read operations with sorting. People reading the post can make the update and delete operations with checking for exceptions and errors related to various types and wrong inputs.</p><pre>data class BankAccount(<br>   val number: Int,<br>   val name: String,<br>   val type: String,<br>   val interestRate: Double,<br>   val balance: Int<br>)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70c1cc2a547c07a0f6aa1ccfdcce479b/href">https://medium.com/media/70c1cc2a547c07a0f6aa1ccfdcce479b/href</a></iframe><p>I tried doing closures in kotlin, one sample you could try is below:</p><pre>data class Person(val name: String, val age: Int)</pre><pre>fun getMaxOrSum(): (type: String) -&gt; Any? {<br>    // people variable will remain in closure<br>    val people = <br>        listOf(<br>            Person(“Piyush”, 25),<br>            Person(“Kartikey”, 23),<br>            Person(“Mithun”, 25)<br>        )</pre><pre>    return fun (type: String): Any? {<br>        when (type) {<br>            “maxBy” -&gt; return people.maxBy { it.age }<br>            “sumBy” -&gt; return people.sumBy { it.age }<br>            else -&gt; return 1<br>        }<br>    }<br>}</pre><pre>val maxOrSumBy = getMaxOrSum() // return a function</pre><pre>// Now you could call like this<br>maxOrSumBy(“maxBy”)<br>// =&gt; Person(name=Piyush, age=25)<br>maxOrSumBy(“sumBy”)<br>// =&gt; 73<br>maxOrSumBy(“other”)<br>// =&gt; 1</pre><p>I found the following resources useful while playing with kotlin. funkTionale is great resource for exploring about partial functionals, currying etc. The author has also included `testng` framework and related tests while demonstrating various functionality.</p><h3>Piyush Chauhan on Twitter</h3><p>Functional programming in Kotlin with funKTionale https://speakerdeck.com/marioariasc/functional-programming-in-kotlin-with-funktionale ... @kotlin</p><p><a href="https://github.com/MarioAriasC/funKTionale/blob/master/src/test/kotlin/org/funktionale/currying/CurryingTest.kt">MarioAriasC/funKTionale</a></p><p>Kotlin loves FP read from medium is also worth spending time on. A lot of concepts have been covered about the language and functional practices here.</p><p><a href="https://medium.com/@octskyward/kotlin-fp-3bf63a17d64a">Kotlin ❤ FP</a></p><p>Kotlin-Koans is a practice exercises from kotlinlang.org. The following repository contains the solved examples which might be useful for inspiration. I might go ahead and try `testng` and practice testing various implemented functions.</p><p><a href="https://github.com/vicboma1/Kotlin-Koans">vicboma1/Kotlin-Koans</a></p><p>The upcoming posts will cover Spring integration with Kotlin using gradle and JPA integration with Kotlin using gradle plus some examples.</p><p>Happy Coding! Let me know about your views at twitter account here: <a href="https://medium.com/u/3e5249ce6953">Piyush Chauhan</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1a07eeb5886" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>