<?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 Mustafa Elsayed on Medium]]></title>
        <description><![CDATA[Stories by Mustafa Elsayed on Medium]]></description>
        <link>https://medium.com/@mustafaskyer?source=rss-6ec8da7ec721------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TkSaR7m-mheLF1M66PVS6g.jpeg</url>
            <title>Stories by Mustafa Elsayed on Medium</title>
            <link>https://medium.com/@mustafaskyer?source=rss-6ec8da7ec721------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 08:12:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mustafaskyer/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[WebMCP: The Full Guide in One Article]]></title>
            <link>https://medium.com/@mustafaskyer/webmcp-the-full-guide-in-one-article-dd73457f9814?source=rss-6ec8da7ec721------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd73457f9814</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[web-mcp]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[mcps]]></category>
            <dc:creator><![CDATA[Mustafa Elsayed]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 22:45:13 GMT</pubDate>
            <atom:updated>2026-11-06T22:45:13.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yoxLeLu3x4i3KtL4" /><figcaption>Photo by <a href="https://unsplash.com/@madara_p?utm_source=medium&amp;utm_medium=referral">Madara</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Get started with WebMCP, explore its capabilities, and see why every frontend application will eventually adopt it.</p><p>New experimental web features land almost every week, and nobody has the time to try them all. WebMCP is one that deserves your attention, because I believe every web application will end up adopting it.</p><h4>Why do I think everyone will adopt it?</h4><p>Agents are eating the world, but driving a UI is the old way: they crawl the page and take screenshots to work out what to do, with plenty of guessing and hallucination. WebMCP replaces that:</p><ul><li><strong>Reliable</strong>: agents call your tools and make the right choice, instead of guessing which button to click.</li><li><strong>Fast</strong>: tools run inside the browser, with no extra network hop to call them.</li><li><strong>Controllable</strong>: you define the preferred way for agents to act on your site.</li></ul><h4>Who is adopting it?</h4><p>WebMCP is still experimental, but its capabilities are worth trying early, and plenty of companies already are. <strong>Google</strong> and <strong>Microsoft</strong> co-edit the spec and run origin trials in Chrome and Edge. <strong>OpenAI</strong> ships it in the ChatGPT desktop app under the name “site tools”. <strong>Shopify</strong> has turned it on for its Liquid storefronts, and <strong>Cloudflare</strong> offers it at the edge and in Browser Run. Google also says Expedia, <strong>Booking</strong>.com, <strong>Etsy</strong>, <strong>Instacart</strong>, <strong>Target</strong>, <strong>Redfin</strong>, Credit Karma, and TurboTax are experimenting with it.</p><h4>The Problem</h4><p>Today’s agents struggle to understand UIs built for humans. To take a single action in your web application, an agent has to read the whole page, work out what every element does, and then decide what to use. There is a lot of guessing at that stage.</p><p>WebMCP solves this by telling agents exactly which tools exist, how to call them, and what to expect back. No guessing, no crawling the whole UI to figure out what to do, and far fewer wrong actions. All of this goes through a single API: document.modelContext</p><h4>What is WebMCP, and how is it different from MCP?</h4><p>WebMCP runs in the browser, inside your web pages, and exposes tools only. MCP runs on servers and can expose more: tools, prompts, resources, and so on.</p><p>WebMCP gives you two ways to define tools: an imperative API in JavaScript, and a declarative API that turns HTML forms into tools through attributes. We’ll start with JavaScript and cover forms further down.</p><p><strong>Two more distinctions</strong>:</p><ol><li>WebMCP uses the user’s existing browser session, so there is no separate authentication or authorization flow to build.</li><li>WebMCP works with your application logic rather than your markup, so a UI revamp or redesign shouldn’t affect your agents. Your tools stay as they are!</li></ol><h4>Getting Started with WebMCP</h4><p><strong>Enabling WebMCP</strong></p><p>WebMCP is still experimental. To enable it in Chrome, visit chrome://flags/#enable-webmcp-testing and turn the flag on, as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GuVdTZ4cBjQiVAm5-D0v7w.png" /><figcaption>Enabling WebMCP for testing in Chrome</figcaption></figure><p><strong>Write your first tool</strong></p><p>On any web page, open the console and type document.modelContext to explore the full API.</p><pre>await document.modelContext.registerTool({ name, description, inputSchema, execute })</pre><ul><li><strong>name </strong>(string): the tool’s name, like get_orders or add_to_cart. A tool can do anything, like managing state or changing the theme. keep the name within 30 characters, as Chrome recommends.</li><li><strong>description </strong>(string): describes what the tool does and when to use it. Agents rely on it to pick the right tool, so be specific, use positive language, and keep it within 500 characters.</li><li><strong>inputSchema</strong> (JSON Schema): a JSON Schema object that describes the tool’s parameters. Give each parameter a specific type, a name within 30 characters, and a description within 150 characters. The browser does not validate arguments against the schema, so validate them inside execute.</li><li><strong>execute</strong> (function, sync or async): where your logic lives. Return clear, actionable errors so the agent can recover, and keep each output within 1.5K characters.</li></ul><p>Full example</p><pre>await document.modelContext.registerTool({<br>  name: &quot;add_to_cart&quot;,<br>  description: &quot;Add a product item to the cart&quot;,<br>  inputSchema: {<br>    type: &quot;object&quot;,<br>    properties: {<br>      productId: { type: &quot;string&quot;, description: &quot;Unique ID of the product&quot; },<br>      name: { type: &quot;string&quot;, description: &quot;Display name of the product&quot; },<br>      image: { type: &quot;string&quot;, description: &quot;URL of the product image&quot; },<br>      quantity: { type: &quot;integer&quot;, minimum: 1, description: &quot;Units to add&quot; }<br>    },<br>    required: [&quot;productId&quot;, &quot;name&quot;, &quot;quantity&quot;]<br>  },<br>  execute: async ({ productId, name, image, quantity }) =&gt; {<br>    const items = store.getItems()<br>    const newItem = { productId, name, image, quantity, datetime: new Date() }<br>    items.push(newItem)<br>    return { success: true, itemsCount: items.length }<br>  }<br>})</pre><p>You’ve added your first tool. Any agent with access to this page can now find it, interact with it, and execute it, as long as the page stays open.</p><p>To see the registered tool from the console, type await document.modelContext.getTools()</p><pre>const tools = await document.modelContext.getTools()<br><br>/** Tools response<br> * Returns a list of tools, each with the following shape:<br>[<br>  {<br>    annotations: { ... },<br>    description,<br>    name,<br>    inputSchema,<br>    origin,<br>    title,<br>    window: Window { window: Window, self: Window, ... }<br>  }<br>]<br>**/</pre><p><strong>Tool Exposure</strong></p><p>By default, a tool is only accessible to documents on the same origin. To make it available to other origins, you have to list them explicitly with the exposedTo option. Only secure (HTTPS) origins are accepted.</p><pre>await document.modelContext.registerTool(<br> {  name, description, ...etc},<br> { exposedTo: [&#39;https://example.com&#39;] } // expose to other trusted origins<br>);</pre><p><strong>Getting Document Tools</strong></p><p>A plain call to <strong>getTools </strong>returns only same-origin tools by default: the ones registered by the calling document or by other same-origin documents in its frame tree. To get tools from other origins, you have to ask for them explicitly by passing fromOrigins</p><pre>const tools = await document.modelContext.getTools({<br>  fromOrigins: [&quot;https://example.com&quot;],<br>});</pre><p>This returns the current document’s tools plus any tools that example.com has exposed to it.</p><p><strong>Tool Execution</strong></p><p>To execute a tool manually, which is handy for testing or for an in-page agent, find it in the list returned by getTools and pass it, along with its inputs, to executeTool</p><pre>const tools = await document.modelContext.getTools()<br>const addToCart = tools.find((tool) =&gt; tool.name === &quot;add_to_cart&quot;)<br><br>const result = await document.modelContext.executeTool(addToCart, {<br>  productId: &quot;123&quot;,<br>  name: &quot;Product One&quot;,<br>  image: &quot;https://...&quot;,<br>  quantity: 1<br>})</pre><h4>Tool Cancellation</h4><p>If an async tool is running and you’d like to cancel it, use an AbortController. You pass its signal when you execute the tool, and the tool receives that signal as the second argument of its execute function.</p><pre>const fetchTool = await document.modelContext.registerTool({<br>  execute: async ({ url, priority }, { signal }) =&gt; {<br>    // Abort the fetch request when tool execution is aborted.<br>    const response = await fetch(url, { priority, signal });<br>    return &#39;Success&#39;;<br>  },<br>})<br><br>const controller = new AbortController();<br>document.modelContext.executeTool(<br>  fetchTool,<br>  toolInputs,<br>  { signal: controller.signal }<br>);<br><br>// Cancel the execution whenever you need to.<br>controller.abort();</pre><h4>Annotations</h4><p>Annotations are metadata that help agents and the browser understand how safe a tool is: whether to ask for confirmation before an important action, for example, or whether the returned output can be trusted. They are hints, not enforcement, so your tool still has to protect itself.</p><ul><li>readOnlyHint (boolean): indicates that the tool is safe to call because it only reads data and changes nothing.</li><li>untrustedContentHint (boolean): indicates that the returned output is untrusted, such as user-generated content or external data, so agents should handle it with extra care, for example by sanitizing or delimiting it.</li><li>consequentialHint (boolean): indicates that the tool performs real, irreversible actions like transferring money or deleting data, so agents and browsers can ask for confirmation before executing.</li><li>debugging (boolean): indicates that the tool is meant for debugging and developer tooling, not for end users.</li></ul><p>To add annotations to a tool, pass an annotations object when you register it.</p><pre>await document.modelContext.registerTool({<br>  // name, description, inputSchema, ...etc<br>  annotations: {<br>    readOnlyHint: false, // defaults to false, added here for clarity<br>    consequentialHint: true,<br>    untrustedContentHint: false,<br>    debugging: false,<br>  },<br>  execute: async ({ flightId, passengers }) =&gt; {<br>    return `Booked ${passengers} on flight ${flightId}`<br>  },<br>})</pre><h4>WebMCP Extensions</h4><p>To try your tools without a full agent, the Chrome team provides two extensions:</p><ul><li><a href="https://chromewebstore.google.com/detail/model-context-tool-inspec/gbpdfapgefenggkahomfgkhfehlcenpd"><strong>Model Context Tool Inspector</strong></a>: test your tools with natural language prompts.</li><li><a href="https://github.com/GoogleChromeLabs/webmcp-extension/"><strong>Example Agentic Chrome Extension</strong></a>: an example agent that inspects, monitors, and executes WebMCP tools.</li></ul><h4>Framework Support</h4><p>React, Vue, and Angular have experimental support for WebMCP. Each one ties a tool to your app’s lifecycle, so it registers and unregisters for you.</p><p><a href="https://www.npmjs.com/package/use-webmcp-tool"><strong>React</strong></a>: use the useWebMCP hook from the use-webmcp-tool package. The tool registers when the component mounts and unregisters when it unmounts.</p><pre>import { useWebMCP } from &quot;use-webmcp-tool&quot;<br><br>function CartTools({ addToCart }) {<br>  useWebMCP({<br>    name: &quot;add_to_cart&quot;,<br>    description: &quot;Add a product item to the cart&quot;,<br>    inputSchema: { /* same schema as before */ },<br>    execute: async ({ productId, quantity }) =&gt; {<br>      addToCart(productId, quantity)<br>      return &quot;Added to cart&quot;<br>    },<br>  })<br><br>  return null<br>}</pre><p><a href="https://vueuse.org/core/usewebmcp"><strong>Vue</strong></a>: use the useWebMCP composable from @vueuse/core. The tool lives as long as the current Vue scope.</p><pre>import { useWebMCP } from &quot;@vueuse/core&quot;<br><br>useWebMCP({<br>  name: &quot;add_to_cart&quot;,<br>  description: &quot;Add a product item to the cart&quot;,<br>  inputSchema: { /* same schema as before */ },<br>  execute: async ({ productId, quantity }) =&gt; {<br>    cart.add(productId, quantity)<br>    return &quot;Added to cart&quot;<br>  },<br>})</pre><p><a href="https://angular.dev/ai/webmcp"><strong>Angular</strong></a>: use provideExperimentalWebMcpTools from @angular/core. Tools register when the app starts, and Angular can also turn Signal Forms into tools.</p><pre>import { inject, provideExperimentalWebMcpTools } from &quot;@angular/core&quot;<br><br>bootstrapApplication(AppRoot, {<br>  providers: [<br>    provideExperimentalWebMcpTools([<br>      {<br>        name: &quot;add_to_cart&quot;,<br>        description: &quot;Add a product item to the cart&quot;,<br>        inputSchema: { /* same schema as before */ },<br>        execute: ({ productId, quantity }) =&gt; {<br>          inject(Cart).add(productId, quantity)<br>          return { content: [{ type: &quot;text&quot;, text: &quot;Added to cart&quot; }] }<br>        },<br>      },<br>    ]),<br>  ],<br>})</pre><h4>Conclusion</h4><p>WebMCP is still experimental, but the idea is simple: instead of letting agents guess their way through your UI, you hand them a small set of tools built on logic you already have. You’ve seen how to register a tool, expose it across origins, execute and cancel it, add annotations, turn forms into tools, and wire it all into React, Vue, and Angular. That’s everything you need to try it on your own app today.</p><p>Thank you for reading all the way to the end! If you’re interested in more content like this, follow me for the next articles. And if you’d like to go deeper, the official docs below are the best place to start.</p><h4>References</h4><ul><li><a href="https://developer.chrome.com/docs/ai/webmcp">WebMCP overview</a> (Chrome for Developers)</li><li><a href="https://developer.chrome.com/docs/ai/webmcp/imperative-api">Imperative API</a> (Chrome for Developers)</li><li><a href="https://developer.chrome.com/docs/ai/webmcp/declarative-api">Declarative API</a> (Chrome for Developers)</li><li><a href="https://developer.chrome.com/docs/ai/webmcp/best-practices">WebMCP best practices</a> (Chrome for Developers)</li><li><a href="https://developer.chrome.com/docs/ai/webmcp/secure-tools">WebMCP tool security guidance</a> (Chrome for Developers)</li><li><a href="https://developer.chrome.com/docs/ai/webmcp/build-tools">Build your user’s agentic workflows with WebMCP tools</a> (Chrome for Developers)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd73457f9814" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clock In, Clock Out: Turning OpenSpec and Linear into a Reliable AI Agent Execution Loop]]></title>
            <link>https://medium.com/@mustafaskyer/clock-in-clock-out-turning-openspec-and-linear-into-a-reliable-ai-agent-execution-loop-e79f041c0202?source=rss-6ec8da7ec721------2</link>
            <guid isPermaLink="false">https://medium.com/p/e79f041c0202</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Mustafa Elsayed]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 19:41:46 GMT</pubDate>
            <atom:updated>2026-07-26T16:46:18.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*51CnZCd2OTR09WMH" /><figcaption>Photo by <a href="https://unsplash.com/@jcraice?utm_source=medium&amp;utm_medium=referral">Julia Craice</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Most teams begin using coding agents with a task list. That works for small jobs, but it breaks down when the work spans multiple sessions, branches, agents, or days.</p><p>The problem is rarely that the agent cannot write code, The problem is continuity.</p><p>A new session must know what has already changed, which decisions are settled, what remains blocked, and whether the repository is healthy. An old session must stop at the right boundary and leave enough durable context for the next one.</p><p>A practical way to solve this is to borrow a familiar workplace metaphor:</p><blockquote>Clock in before starting. Clock out before leaving.</blockquote><p>In an agent workflow, clock-in and clock-out are not status updates. They are execution gates.</p><p>OpenSpec defines the work. Linear tracks the work. Clock-in and clock-out make each agent session reliable enough to execute the work one phase or task at a time.</p><h3>The real unit of work is the session</h3><p>Long-running conversations are fragile. They accumulate stale assumptions, hidden decisions, noisy context, and partially remembered state.</p><p>A better model is to treat each agent session as disposable.</p><p>Every session should be able to start fresh, read the current project state, complete one scoped task or phase, verify the result, update the durable records, and archive itself.</p><p>Disposable does not mean careless or forgettable. It means the session itself should not be the source of truth: once its decisions, verification results, and next action are written to OpenSpec, Linear, or the progress log, the conversation can end without losing the work.</p><p>That creates a simple execution loop:</p><ol><li>Read the OpenSpec phases, tasks, acceptance criteria, and blockers.</li><li>Match the next unblocked task to its Linear issue.</li><li>Start a fresh session with predefined or dynamically selected model settings.</li><li>Clock in.</li><li>Execute one scoped task or phase.</li><li>Clock out.</li><li>Update OpenSpec, Linear, verification notes, and the next action.</li><li>Archive the session.</li><li>Start the next session from the updated state.</li></ol><p>The goal is not to preserve one perfect conversation forever.</p><p>The goal is to make every session replaceable.</p><h3>What OpenSpec owns</h3><p>OpenSpec should be the source of truth for the shape of the work.</p><p>It defines:</p><ul><li>Requirements</li><li>Design constraints</li><li>Phases</li><li>Tasks</li><li>Acceptance criteria</li><li>Dependencies</li><li>Known blockers</li></ul><p>This is where the agent learns what “done” means.</p><p>A task without acceptance criteria is just a suggestion. A phase without entry and exit conditions is just a heading. OpenSpec gives the agent a concrete contract to execute against.</p><h3>What Linear owns</h3><p>Linear should be the source of truth for execution coordination.</p><p>It tracks:</p><ul><li>Status</li><li>Priority</li><li>Ownership</li><li>Team visibility</li><li>Links to pull requests</li><li>Links to related issues</li></ul><p>Linear is where humans and agents coordinate the movement of work.</p><p>The important part is to avoid pretending every system owns everything. OpenSpec should not become a project management clone. Linear should not become the full specification store.</p><p>Each tool needs a distinct job.</p><p>For example:</p><ul><li>OpenSpec is authoritative for requirements and acceptance criteria.</li><li>Linear is authoritative for execution status and ownership.</li><li>GitHub or GitLab is authoritative for code review and merge state.</li><li>A handoff file or progress log is authoritative for the next agent action.</li></ul><p>Synchronization should exist only where it removes real manual work.</p><h3>What clocking in means</h3><p>Clocking in is the entry gate for a fresh session.</p><p>Before changing code, the agent should prove that it understands the current state.</p><p>A clock-in checklist can include:</p><ul><li>Read the relevant OpenSpec proposal, phase, task, and acceptance criteria.</li><li>Read the matching Linear issue and current status.</li><li>Inspect the current branch or work-tree.</li><li>Review recent changes.</li><li>Run baseline checks such as tests, linting, type checks, or build commands.</li><li>Confirm the task is unblocked.</li><li>Search the codebase for existing helpers, patterns, and related callers.</li><li>Select the model and reasoning effort appropriate for the task.</li><li>State the exact scope for this session.</li></ul><p>That last point matters.</p><p>The session should not begin with “I will continue the project.” It should begin with something concrete:</p><p>“I will complete task 2.3, verify it with the listed acceptance checks, update OpenSpec and Linear, then leave the next action.”</p><p>If the baseline is already failing, that must be recorded before new work begins. Otherwise, the next failure may be blamed on the wrong change.</p><h3>Choosing the model and reasoning effort</h3><p>Not every task needs the same agent configuration.</p><p>A small documentation update may only need a fast, low-reasoning session. A database migration, security-sensitive change, or cross-module refactor may need a stronger model and deeper reasoning.</p><p>Clock-in is the right place to decide this.</p><p>The selection can be predefined:</p><ul><li>Small task: fast model, low reasoning.</li><li>Medium implementation: balanced model, medium reasoning.</li><li>Risky or architectural task: stronger model, high reasoning.</li></ul><p>Or it can be dynamic:</p><p>The session reads the task complexity, dependency count, file surface, risk level, and acceptance criteria, then chooses the model and reasoning effort before implementation begins.</p><p>The key is that this decision happens before code changes, not halfway through the task.</p><h3>What clocking out means</h3><p>Clocking out is the exit gate.</p><p>Before ending, the agent should:</p><ul><li>Run the relevant tests, linting, type checks, builds, and acceptance checks.</li><li>Compare the completed work against the OpenSpec acceptance criteria.</li><li>Update the OpenSpec task checklist.</li><li>Update the matching Linear issue.</li><li>Record verification results.</li><li>Record important decisions.</li><li>Record blockers or follow-up work.</li><li>Remove temporary files, debug code, and abandoned experiments.</li><li>Leave the exact next action.</li><li>Archive the session.</li></ul><p>The most important rule is simple:</p><p>Never mark a task complete unless its acceptance criteria have passed.</p><p>“Done” is not the moment code is generated. It is a verified state that another session can reproduce.</p><h3>Archive the session, not the knowledge</h3><p>Archiving the session should not mean losing what happened.</p><p>The conversation can be closed, summarized, or discarded. The durable state must remain.</p><p>At minimum, preserve:</p><ul><li>What changed</li><li>Why it changed</li><li>Which checks passed</li><li>Which checks failed</li><li>Which decisions were made</li><li>What remains blocked</li><li>What the next session should do first</li></ul><p>That state can live in OpenSpec, Linear, repository progress files, or a combination of them. The exact storage matters less than the contract:</p><p>The next session must not need the previous conversation to continue safely.</p><h3>From checklist to execution system</h3><p>Once clock-in and clock-out are explicit, the workflow can become an execution system.</p><p>A coordinator can:</p><ul><li>Read OpenSpec.</li><li>Find the next unblocked task.</li><li>Open or update the matching Linear issue.</li><li>Start a fresh agent session with the right model settings.</li><li>Provide the task, acceptance criteria, and current state.</li><li>Let the agent execute one scoped unit.</li><li>Require clock-out evidence.</li><li>Archive the session.</li><li>Continue with the next task.</li></ul><p>This makes AI coding less dependent on memory and more dependent on evidence.</p><p>Each session has a clear beginning, a clear end, and a measurable result.</p><h3>Use worktrees for isolated execution</h3><p>Fresh sessions pair well with Git worktrees.</p><p>Each worktree can hold one branch, one task, and one isolated agent session. That allows parallel work without multiple agents modifying the same checkout.</p><p>But parallelism should be earned.</p><p>Two tasks are good candidates for parallel execution only when their dependencies are clear and their file-level overlap is low. Tightly coupled work should stay sequential.</p><p>Parallel agents are useful when they reduce elapsed time. They are harmful when they multiply merge conflicts and review effort.</p><h3>Use subagents only when the work decomposes</h3><p>Specialized subagents can help, but only when the work has clean boundaries.</p><p>Useful roles include:</p><ul><li>Planner: turns a goal into OpenSpec phases, tasks, and acceptance criteria.</li><li>Implementer: completes one scoped task.</li><li>Test engineer: reproduces failures and verifies behavior independently.</li><li>Security reviewer: checks trust boundaries and abuse cases.</li><li>Documentation writer: updates durable project guidance.</li><li>Evaluator: compares the final result with the original requirements.</li></ul><p>“Use more agents” is not a strategy.</p><p>A subagent should have defined inputs, permissions, tools, and expected output. If coordination costs more than the independent contribution, keep the workflow sequential.</p><p>The protocol is intentionally simple.</p><p>Start with an OpenSpec task checklist, a Linear issue, a clock-in checklist, and a clock-out checklist.</p><p>Add automation only after repeated manual work shows where it will help.</p><h3>Start small</h3><p>For your next agent-driven project, define two gates:</p><p>What must be true before an agent changes code? What must be true before an agent marks the task complete?</p><p>Then connect those gates to OpenSpec and Linear.</p><p>At clock-in, start a fresh session from the current task state.</p><p>At clock-out, verify the result, update the records, write the next action.</p><p>That is enough to turn isolated agent sessions into a dependable engineering loop.</p><h3>Useful resources</h3><ul><li><a href="https://github.com/Fission-AI/openspec">OpenSpec</a>: the spec-driven workflow layer for proposals, requirements, phases, tasks, acceptance criteria, and archive state.</li><li><a href="https://walkinglabs.github.io/learn-harness-engineering/en/lectures/lecture-05-why-long-running-tasks-lose-continuity/">Learn Harness Engineering: Keeping Context Alive Across Sessions</a>: a practical explanation of why long-running agent work loses continuity and why progress files, decision logs, and clean session boundaries matter.</li><li><a href="https://github.com/intent-driven-dev/openspec-schemas/blob/main/.codex/skills/openspec-linearized/SKILL.md">OpenSpec Linearized Skill</a>: an example Codex skill for turning OpenSpec work into a linearized execution loop.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e79f041c0202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Contract First Development | ORPC]]></title>
            <link>https://medium.com/@mustafaskyer/contract-first-development-orpc-7a64df3dc743?source=rss-6ec8da7ec721------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a64df3dc743</guid>
            <category><![CDATA[contract-first]]></category>
            <category><![CDATA[orpc]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[hono]]></category>
            <category><![CDATA[tanstack-query]]></category>
            <dc:creator><![CDATA[Mustafa Elsayed]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 05:25:51 GMT</pubDate>
            <atom:updated>2026-06-16T17:25:28.085Z</atom:updated>
            <content:encoded><![CDATA[<h3>Contract First Development | Orpc</h3><p><strong>Every API has a contract, even when nobody wrote it down.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9s26YS2-Tb2cx9Bi" /><figcaption>Photo by <a href="https://unsplash.com/@jakubpabis?utm_source=medium&amp;utm_medium=referral">Jakub Pabis</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In many projects, that contract is spread across backend route handlers, frontend interfaces, mobile DTOs, Postman collections, stale docs, and one Slack message nobody wants to lose.</p><p>The frontend sends a payload the backend no longer accepts. The mobile app expects a field that was renamed. The docs show one response, the server returns another, and the bug only appears when real users reach production. That is the problem contract-first APIs are meant to reduce.</p><p>oRPC lets you define the API contract once and reuse it across the server, clients, docs, and query layer. The contract describes routes, inputs, outputs, validation rules, and expected errors. The backend implements it. Clients consume it. Docs come from it.</p><p>This repo demonstrates that pattern with a small product catalog demonstration with the following stack:</p><ul><li>Bun</li><li>Turborepo</li><li>Hono</li><li>oRPC</li><li>Zod</li><li>static TypeScript data</li><li>OpenAPI</li><li>Scalar API docs</li><li>Next.js</li><li>Expo</li><li>TanStack Query</li><li>Sentry</li></ul><p>You can find the full example on <a href="https://github.com/mustafaskyer/orpc-contract-example">GitHub</a></p><p>One note before starting, The data layer is static TypeScript data on purpose. That keeps the article focused on the boundary that matters: the API contract. You can replace the data layer later with PostgreSQL, Drizzle, Prisma, SQLite, or an external service without changing how web and mobile call the API.</p><h3>What we are building</h3><p>The project is a monorepo with one shared API contract and three runtimes.</p><pre>orpcexample/<br>├── apps/<br>│   ├── server/<br>│   ├── web/<br>│   └── mobile/<br>├── packages/<br>│   ├── db/<br>│   ├── orpc/<br>│   ├── ui/<br>│   ├── eslint-config/<br>│   └── typescript-config/<br>├── turbo.json<br>└── package.json</pre><p>Each part has a narrow job</p><p>packages/db owns product data and query helpers.</p><p>packages/orpc owns the contract, Zod schemas, typed client, and TanStack Query helpers.</p><p>apps/server implements the contract with Hono and exposes RPC, REST, OpenAPI, and Scalar docs.</p><p>packages/web consumes the same contract from a Next.js app.</p><p>apps/mobile consumes the same contract from an Expo app.</p><p>The important part: web and mobile do not define their own API types. They import the same contract-aware client instead.</p><h3>Why contract-first APIs help</h3><p>The benefit is not just autocomplete, Autocomplete is useful, but the bigger win is that oRPC makes drift harder.</p><p><strong>When the API contract is shared:</strong></p><ul><li>route names are not guessed by clients</li><li>request payloads are validated at the boundary</li><li>response shapes are derived from the same schema</li><li>expected errors become part of the API design</li><li>REST/OpenAPI docs come from the implemented router</li><li>TanStack Query options come from the typed client</li><li>web and mobile stop maintaining duplicate DTOs</li></ul><p>That changes the daily workflow. Instead of asking “what does this endpoint return now?”, the team changes the contract and lets TypeScript show every place that must be updated.</p><h3>Domain schemas in the data layer</h3><p>Before defining the oRPC contract, we define the domain shapes in packages/db.</p><p>That may feel odd at first, but it keeps ownership clear.</p><p>packages/db owns categories and products, so it also owns their Zod schemas. packages/orpc should not redefine those shapes. It should consume them.</p><p>The data layer starts with Zod schemas. This is the only place where the product and category shapes are defined.</p><h3>The contract package</h3><p>The heart of the repo is packages/orpc . This package does not render UI. It does not own database access. It describes the boundary between server and consumers.</p><pre>// packages/db/src/categories/types.ts<br>import { z } from &quot;zod&quot;;<br><br>export const CategorySlugSchema = z.enum([<br>  &quot;keyboard&quot;,<br>  &quot;mouse&quot;,<br>  &quot;monitor&quot;,<br>  &quot;audio&quot;,<br>  &quot;accessory&quot;,<br>]);</pre><p>and types</p><pre>// packages/db/src/product/types.ts<br>import { z } from &quot;zod&quot;;<br><br>import { CategorySlugSchema } from &quot;../categories&quot;;<br><br>export const ProductSchema = z.object({<br>  id: z.string().startsWith(&quot;prod_&quot;),<br>  slug: z.string().min(1),<br>  name: z.string().min(1),<br>  category: CategorySlugSchema,<br>  description: z.string().min(1),<br>  priceCents: z.number().int().nonnegative(),<br>  currency: z.literal(&quot;USD&quot;),<br>  inStock: z.boolean(),<br>  tags: z.array(z.string().min(1)),<br>  pictures: z.array(<br>    z.object({<br>      url: z.string().url(),<br>      alt: z.string().min(1),<br>      label: z.string().min(1),<br>    }),<br>  ),<br>});</pre><h3>The Contract Package</h3><p>Now packages/orpc can focus on the API boundary.</p><p>It imports the domain schemas from @repo/db, adds API-specific input schemas, and describes the routes.</p><pre>// packages/orpc/src/contract.ts<br>import { oc } from &quot;@orpc/contract&quot;;<br>import { CategorySchema, CategorySlugSchema, ProductSchema } from &quot;@repo/db&quot;;<br>import { z } from &quot;zod&quot;;<br><br>const ListProductsInputSchema = z.object({<br>  category: CategorySlugSchema.optional(),<br>  inStock: z.boolean().optional(),<br>  search: z.string().trim().min(1).optional(),<br>  limit: z.number().int().min(1).max(50).optional(),<br>});<br><br>export const contract = {<br>  categories: {<br>    list: oc<br>      .route({<br>        method: &quot;GET&quot;,<br>        path: &quot;/categories&quot;,<br>        summary: &quot;List product categories.&quot;,<br>      })<br>      .output(z.array(CategorySchema)),<br>  },<br>  products: {<br>    list: oc<br>      .route({<br>        method: &quot;GET&quot;,<br>        path: &quot;/products&quot;,<br>        summary: &quot;List products.&quot;,<br>      })<br>      .input(ListProductsInputSchema)<br>      .output(z.array(ProductSchema)),<br>    byId: oc<br>      .route({<br>        method: &quot;GET&quot;,<br>        path: &quot;/products/{id}&quot;,<br>        summary: &quot;Get product by ID.&quot;,<br>      })<br>      .errors(ProductNotFoundError)<br>      .input(ProductIdInputSchema)<br>      .output(ProductSchema),<br>    bySlug: oc<br>      .route({<br>        method: &quot;GET&quot;,<br>        path: &quot;/products/by-slug/{slug}&quot;,<br>        summary: &quot;Get product by slug.&quot;,<br>      })<br>      .errors(ProductNotFoundError)<br>      .input(ProductSlugInputSchema)<br>      .output(ProductSchema),<br>    reserve: oc<br>      .route({<br>        method: &quot;POST&quot;,<br>        path: &quot;/products/{productId}/reservations&quot;,<br>        summary: &quot;Reserve product stock.&quot;,<br>        successStatus: 201,<br>      })<br>      .errors({<br>        ...ProductNotFoundError,<br>        ...ProductUnavailableError,<br>      })<br>      .input(ReserveProductInputSchema)<br>      .output(ReservationSchema),<br>  },<br>};</pre><p>This avoids defining the product shape twice.</p><p>The domain schema lives in packages/db. The API promise lives in packages/orpc.</p><p>With that split, the repo gets typed procedures, runtime validation, known error shapes, OpenAPI generation, and client utilities. The contract package does not need to own the data model.</p><h3>The data layer is replaceable</h3><p>The contract does not care where the data comes from.</p><p>The contract does not care where the data comes from. That is the point.</p><p>Today it is static product data. Later it can be a database, a CMS, a search service, or another API. Only the server implementation should care. The web app, mobile app, OpenAPI spec, and client code should change only when the API contract changes.</p><h3>Implementing the contract in Hono</h3><p>The server imports the contract and implements it.</p><pre>import { implement } from &quot;@orpc/server&quot;;<br>import { contract } from &quot;@repo/orpc&quot;;<br><br>const os = implement(contract);</pre><p>Each handler now has to satisfy the contract.</p><pre>const listProducts = base.products.list.handler(({ input }) =&gt; {<br>  return filterProducts(input);<br>});</pre><p>A product lookup can return a known contract error instead of inventing a one-off response shape.</p><pre>const byId = base.products.byId.handler(({ input, errors }) =&gt; {<br>  const product = findProductById(input.id);<br><br>  if (!product) {<br>    throw errors.NOT_FOUND({<br>      message: `Product ${input.id} not found.`,<br>    });<br>  }<br><br>  return product;<br>});</pre><p>The reservation mutation follows the same rule.</p><pre>const reserve = base.products.reserve.handler(({ input, errors }) =&gt; {<br>  const product = findProductById(input.productId);<br><br>  if (!product) {<br>    throw errors.NOT_FOUND({<br>      message: `Product ${input.productId} not found.`,<br>    });<br>  }<br><br>  if (!product.inStock) {<br>    throw errors.CONFLICT({<br>      message: `${product.name} is currently out of stock.`,<br>    });<br>  }<br><br>  return {<br>    id: `res_${Date.now()}`,<br>    product,<br>    quantity: input.quantity,<br>    status: &quot;reserved&quot;,<br>    reservedAt: new Date().toISOString(),<br>  };<br>});</pre><p>Finally, the router mirrors the contract shape.</p><pre>export const router = base.router({<br>  categories: {<br>    list: listCategories,<br>  },<br>  products: {<br>    list: listProducts,<br>    byId,<br>    bySlug,<br>    reserve,<br>  },<br>});</pre><p>At this point, the contract is doing real work.</p><p>If the contract says a handler returns a product, the implementation cannot casually return a different shape. If the input schema changes, the handler sees that change. If the client sends the wrong payload, the boundary rejects it.</p><h3>RPC, REST, OpenAPI, and docs from one router</h3><p>The server exposes multiple surfaces from the same router.</p><pre>const rpcHandler = new RPCHandler(router, {<br>  plugins: [new CORSPlugin()],<br>});<br><br>const openAPIHandler = new OpenAPIHandler(router, {<br>  plugins: [new CORSPlugin(), new experimental_ZodSmartCoercionPlugin()],<br>});</pre><p>The app serves:</p><pre>/rpc       -&gt; typed oRPC client calls<br>/api       -&gt; REST/OpenAPI-style calls<br>/spec.json -&gt; generated OpenAPI spec<br>/docs      -&gt; Scalar API reference<br>/health    -&gt; health check</pre><p>That matters because not every consumer wants the same interface.</p><p>The Next.js and Expo apps can use typed RPC. External consumers can use REST and OpenAPI. Humans can explore the API through Scalar.</p><p>They all come from the same contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KlgkWPM8JC8yV6OMzeHmtA.png" /><figcaption>Scalar API Documentaion</figcaption></figure><h3>OpenAPI and Scalar</h3><p>OpenAPI is generated directly from the implemented router.</p><pre>const openAPIGenerator = new OpenAPIGenerator({<br>  schemaConverters: [new ZodToJsonSchemaConverter()],<br>});<br><br>app.get(&quot;/spec.json&quot;, async (c) =&gt; {<br>  return c.json(await generateSpec(c.req.raw));<br>});</pre><p>Scalar loads that generated spec.</p><pre>&lt;script<br>  id=&quot;api-reference&quot;<br>  data-url=&quot;/spec.json&quot;<br>  data-theme=&quot;deepSpace&quot;<br>  src=&quot;https://cdn.jsdelivr.net/npm/@scalar/api-reference&quot;<br>&gt;&lt;/script&gt;</pre><p>Once the server is running, the docs are available at http://localhost:4001/docs .</p><p>No separate endpoint table. No manual request examples waiting to go stale. The docs are generated from the same API shape the server implements and the clients consume.</p><h3>Sharing the client</h3><p>The contract package also exports a typed client factory.</p><pre>import type { ContractRouterClient } from &quot;@orpc/contract&quot;;<br>import { createORPCClient } from &quot;@orpc/client&quot;;<br>import { RPCLink } from &quot;@orpc/client/fetch&quot;;<br>import { createTanstackQueryUtils } from &quot;@orpc/tanstack-query&quot;;<br><br>import type { AppContract } from &quot;./contract&quot;;<br><br>export type AppClient = ContractRouterClient&lt;AppContract&gt;;<br><br>export function createAppClient(rpcUrl: string): AppClient {<br>  const link = new RPCLink({ url: rpcUrl });<br><br>  return createORPCClient&lt;AppClient&gt;(link);<br>}<br><br>export function createAppQueryUtils(client: AppClient) {<br>  return createTanstackQueryUtils(client);<br>}</pre><p>Every client gets the same API surface.</p><p>The Next.js app and Expo app do not need separate SDKs. They import helpers from @repo/orpc and get the same procedure names, inputs, outputs, and errors.</p><h3>Using oRPC in Next.js</h3><p>The web app creates the client once.</p><pre>import { createAppClient, createAppQueryUtils } from &quot;@repo/orpc&quot;;<br><br>const client = createAppClient(<br>  process.env.NEXT_PUBLIC_RPC_URL ?? &quot;http://localhost:4001/rpc&quot;,<br>);<br><br>export const orpc = createAppQueryUtils(client);</pre><p>Then the page can query products with TanStack Query.</p><pre>const productsQuery = useQuery(<br>  orpc.products.list.queryOptions({<br>    input: {<br>      category,<br>      search,<br>      limit: 12,<br>    },<br>  }),<br>);</pre><p>The mutation is typed too.</p><pre>const reserveMutation = useMutation(<br>  orpc.products.reserve.mutationOptions({<br>    onSuccess: () =&gt; {<br>      queryClient.invalidateQueries({<br>        queryKey: orpc.products.key(),<br>      });<br>    },<br>  }),<br>);</pre><p>This removes a common frontend problem: duplicate API types.</p><p>There is no separate ProductResponse interface in the web app. There is no handwritten fetch wrapper slowly drifting away from the backend. Query options, mutation input, response data, and invalidation keys all come from the shared contract-aware client.</p><h4>Why TanStack Query fits here</h4><p>TanStack Query is already good at managing server state: loading states, caching, refetching, mutations, retries, and invalidation.</p><p>The messy part in many apps is the API layer around it.</p><p>Without a shared contract, teams often write query wrappers by hand. One file knows the URL. Another knows the request payload. Another defines the response type. Another defines the cache key. Over time, those pieces drift.</p><p>oRPC makes that layer contract-aware.</p><pre>orpc.products.list.queryOptions({ input });<br>orpc.products.reserve.mutationOptions();<br>orpc.products.key();</pre><p>The query key, input type, output type, and mutation shape come from the same API definition.</p><p>That means TanStack Query still does what it does best, but the API calls become harder to misuse.</p><p>For full-stack TypeScript apps, that combination is practical: oRPC defines the contract, and TanStack Query manages the client-side lifecycle around it.</p><h3>Using the same contract in Expo</h3><p>The mobile app uses the same idea.</p><pre>const client = createAppClient(&quot;http://localhost:4001/rpc&quot;);<br>const orpc = createAppQueryUtils(client);</pre><p>Then it queries products through the same contract.</p><pre>const productsQuery = useQuery(<br>  orpc.products.list.queryOptions({<br>    input: {<br>      category,<br>      search,<br>      limit: 12,<br>    },<br>  }),<br>);</pre><p>The UI can be different. The transport and contract stay the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxFUv2NBKVueOBr_YoWjKA.png" /><figcaption>web example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjAULQvOBCKIuWDBbR2nOQ.png" /><figcaption>Mobile Example</figcaption></figure><p>Backend, web, mobile, generated docs, and query helpers all depend on one API definition.</p><h3>Error handling and Sentry</h3><p>Good API contracts also describe what can go wrong.</p><p>They should also describe what can go wrong.</p><p>oRPC supports two styles of error handling.</p><p>The first is the normal approach: throw errors directly. You can throw a standard JavaScript error, but ORPCError is usually clearer because it carries an explicit error code and optional client-safe data.</p><pre>import { ORPCError } from &quot;@orpc/server&quot;;<br><br>const rateLimit = os.middleware(async ({ next }) =&gt; {<br>  throw new ORPCError(&quot;RATE_LIMITED&quot;, {<br>    message: &quot;You are being rate limited.&quot;,<br>    data: { retryAfter: 60 },<br>  });<br><br>  return next();<br>});</pre><p>If you throw a regular Error, oRPC can still handle it, but it becomes a generic internal server error. That is fine for unexpected failures. For expected API states, explicit errors are better.</p><p>One rule matters: do not put sensitive data in ORPCError.data. That data can be sent to the client.</p><p>The second style is type-safe error handling. The product catalog uses this for expected product errors. The contract defines known errors with .errors(…), then handlers throw through the generated errors helper.</p><pre>export const ProductNotFoundError = {<br>  NOT_FOUND: {<br>    message: &quot;Product not found.&quot;,<br>  },<br>} as const;<br><br>export const ProductUnavailableError = {<br>  CONFLICT: {<br>    message: &quot;Product is not available.&quot;,<br>  },<br>} as const;</pre><p>The contract attaches those errors to procedures.</p><pre>reserve: oc.route({<br>  method: &quot;POST&quot;,<br>  path: &quot;/products/{productId}/reservations&quot;,<br>  summary: &quot;Reserve product stock.&quot;,<br>  successStatus: 201,<br>})<br>  .errors({<br>    ...ProductNotFoundError,<br>    ...ProductUnavailableError,<br>  })<br>  .input(ReserveProductInputSchema)<br>  .output(ReservationSchema);</pre><p>Then the server throws typed errors from the handler.</p><pre>const reserve = base.products.reserve.handler(({ input, errors }) =&gt; {<br>  const product = findProductById(input.productId);<br><br>  if (!product) {<br>    throw errors.NOT_FOUND({<br>      message: `Product ${input.productId} not found.`,<br>    });<br>  }<br><br>  if (!product.inStock) {<br>    throw errors.CONFLICT({<br>      message: `${product.name} is currently out of stock.`,<br>    });<br>  }<br><br>  return {<br>    id: `res_${Date.now()}`,<br>    product,<br>    quantity: input.quantity,<br>    status: &quot;reserved&quot;,<br>    reservedAt: new Date().toISOString(),<br>  };<br>});</pre><p>This gives clients a better contract. They know the success shape and the expected failure cases.</p><p>You can also combine both approaches. If an ORPCError matches a defined error code, status, and data shape, oRPC treats it like the type-safe error.</p><h3>Sentry and OpenTelemetry</h3><p>The server wires Sentry without putting logging code in every handler.</p><p>The repo already has @orpc/otel installed. Sentry uses ORPCInstrumentation to collect oRPC tracing information.</p><pre>Sentry.init({<br>  dsn: Bun.env.SENTRY_DSN,<br>  tracesSampleRate: Number(Bun.env.SENTRY_TRACES_SAMPLE_RATE ?? 1),<br>  openTelemetryInstrumentations: [new ORPCInstrumentation()],<br>});</pre><p>Tracing is useful, but Sentry does not currently collect every OpenTelemetry span event as an application error. Business logic errors should still be captured manually.</p><p>Middleware is a clean place for that.</p><pre>const sentryMiddleware = os.middleware(async ({ next }) =&gt; {<br>  try {<br>    return await next();<br>  } catch (error) {<br>    Sentry.captureException(error);<br>    throw error;<br>  }<br>});<br><br>const base = os.use(sentryMiddleware);</pre><p>Business logic stays in the handler. Error capture stays in middleware. Tracing stays in instrumentation.</p><p>The example repo keeps one primary Sentry capture path: procedure middleware. You can also add onError interceptors at the RPC or OpenAPI transport edge, but then you should deduplicate events so the same exception does not show up twice in Sentry.</p><p>For production systems, there are two extra details worth knowing:</p><ul><li>oRPC middleware gets its own OpenTelemetry span, so you can add attributes or events to the active span when needed.</li><li>Some errors can happen before your procedure handler runs, such as adapter-level failures or invalid WebSocket messages. Capture uncaught exceptions and unhandled rejections at the process level if your runtime needs that visibility.</li></ul><h3>Running the project</h3><p>Prerequisite: install Bun. This repo was created with bun@1.3.10.</p><pre>bun install<br>bun run dev<br>/**<br>* http://localhost:4001 -&gt; Server<br>* http://localhost:3000 -&gt; Web<br>* http://localhost:4001/docs -&gt; Docs<br>*/</pre><h3>Why this pattern works</h3><p>Contract-first development gives the team one API source of truth.</p><p>With this setup:</p><ul><li>The web &amp; mobile apps consumes the contract.</li><li>OpenAPI documentation is generated from the contract.</li><li>Scalar renders documentation from the generated spec.</li><li>TanStack Query options are derived from the typed client.</li><li>Known errors are part of the API design instead of being hidden in route handlers.</li></ul><p>That is the boundary this example is trying to protect.</p><p>It also scales without tying clients to the data layer. Today, the data layer is static TypeScript data. Later, it can be Drizzle, Prisma, PostgreSQL, SQLite, or an external service. The contract does not need to change unless the API contract changes.</p><p>That separation is the point.</p><h3>Final thought</h3><p>A type-safe API gives you more than editor hints. It gives your team a boundary everyone can trust.</p><p>That matters even more when teams move fast. AI can help build full-stack TypeScript features quickly, but speed without boundaries creates drift. A shared oRPC contract gives humans and AI tools the same source of truth.</p><p>The backend knows what to implement. The web and mobile apps know what to call. The docs know what to show. TypeScript knows what changed.</p><p>That is the real win: faster development without pushing stability to later.</p><p><strong>That is the practical win: faster development without pushing stability to later.</strong></p><p>Define the contract once. Then let every runtime prove it still follows that contract.</p><p>Clone the example repo, run it locally, and open the generated Scalar docs to see the same contract power the server, clients, OpenAPI spec, and UI:</p><p>#orpc #typescript #fullstack #ai #turbo #nextjs #honojs #react #expo</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a64df3dc743" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Langgraph JS | Build your first AI Workflow]]></title>
            <link>https://medium.com/@mustafaskyer/langgraph-js-build-your-first-ai-workflow-188fdc7fb1e4?source=rss-6ec8da7ec721------2</link>
            <guid isPermaLink="false">https://medium.com/p/188fdc7fb1e4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Mustafa Elsayed]]></dc:creator>
            <pubDate>Sat, 08 Feb 2025 18:30:44 GMT</pubDate>
            <atom:updated>2025-02-08T18:30:44.563Z</atom:updated>
            <content:encoded><![CDATA[<h4>Langgraph.js</h4><p>It is a library for building stateful, multi-actor applications with LLMs, used to create agent and multi-agent workflows, using the concept of nodes, and edges hence the graph. It<strong> </strong>offers cycles, controllability, and persistence, and also includes built-in persistence, enabling advanced human-in-the-loop and memory features!</p><p><a href="https://github.com/mustafaskyer/langgraph-workflows"><em>Please note that all the code can be found here in this repo!</em></a></p><p>Before we begin, Let’s explore the key concepts that form the foundation of langgraph.js such as Workflow, Graph, State, Nodes, and Edges.</p><h4>What’s A workflow?</h4><p>In my perspective, it’s just a pipeline containing N of jobs (Nodes), each node has a specific task to handle, and then moves to the next one and so on, additionally, it has a shared context (the graph state) between all nodes that any node can edit!</p><p><em>Also, There’s a more detailed definition of workflow from </em><a href="https://en.wikipedia.org/wiki/Workflow"><em>Wikipedia</em></a><em> please refer to it for more about that!</em></p><h3><strong>The Graph</strong></h3><p>At its core, LangGraph models agent workflows as graphs. The graph is shaped by three main keys, which are:</p><h4><strong>State</strong></h4><p>A shared data structure that represents the current snapshot of your application.</p><h4><strong>Nodes</strong></h4><p>Simple functions that receive the current state as an input, handle some operations over it, then return an updated state.</p><h4><strong>Edges</strong></h4><p>The connections between nodes, determine which Node to execute next based on the current State , and they can be conditional for example only execute this node in a specific case, otherwise ignore it!</p><h4>Building the graph</h4><p>To implement the graph, first of all, I recommend sketching it on some clean boards like <a href="https://www.tldraw.com"><strong>tldraw</strong></a> and getting an insight into whatever you want before starting coding, this should help you imagine your graph, and compare it with the output like what we’ll see below!</p><p><strong>Steps to Implement Your Graph</strong></p><p>To implement a graph whether it’s a simple, or large one, I always follow the below steps:</p><ol><li>Defining the State Object</li><li>Implement Nodes (Make it empty at first)</li><li>Build The graph, and connect the Edges</li><li>Compile the graph, and print it</li></ol><ul><li><strong>Defining the State</strong></li></ul><pre>import { Annotation, messagesStateReducer } from &#39;@langchain/langgraph&#39;<br><br>const StateAnnotation = Annotation.Root({<br>  messages: Annotation({<br>    reducer: messagesStateReducer, // how you update your state<br>    default: () =&gt; [],<br>  }),<br>  /** add any keys regards to your business requirements below */<br>})</pre><p><strong><em>Reducer:</em></strong><em> represents how to update your state (in our case messages)</em></p><p><em>and it takes two arguments, </em><strong><em>the first one is the current state</em></strong><em>,</em><strong><em> and the next is the updated one</em></strong></p><p><em>Example</em></p><pre>const StateAnnotation = Annotation.Root({<br>  sum: Annotation&lt;number&gt;({<br>    reducer: (current: number, next: number) =&gt; current + next,<br>    default: 0,<br>  }),<br>})</pre><ul><li><strong>Defining Empty Nodes</strong></li></ul><pre>export const nodeOne = async (state: typeof StateAnnotation.State) =&gt; {<br>  // return the current state for now<br>  return state<br>}<br><br>export const nodeTwo = async (state: typeof StateAnnotation.State) =&gt; {<br>  // return the current state for now<br>  return state<br>}<br><br>export const nodeThree = async (state: typeof StateAnnotation.State) =&gt; {<br>  // return the current state for now<br>  return state<br>}</pre><ul><li><strong>Build The workflow &amp; connect the edges</strong></li></ul><pre>import { StateGraph, START, END } from &#39;@langchain/langgraph&#39;<br><br>const workflow = new StateGraph(StateAnnotation)<br>  .addNode(&#39;one&#39;, nodeOne)<br>  .addNode(&#39;two&#39;, nodeTwo)<br>  .addNode(&#39;three&#39;, nodeThree)<br>  // Conecting Edges Here<br>  .addEdge(START, &#39;one&#39;)<br>  .addEdge(&#39;one&#39;, &#39;two&#39;)<br>  .addEdge(&#39;two&#39;, &#39;three&#39;)<br>  .addEdge(&quot;three&quot;, END)</pre><p><strong>Compile the workflow, and print your first graph</strong></p><p><em>please note that I am using Bun Here!</em></p><pre>// ********************** Compile the graph<br>const graph = workflow.compile()<br><br>// ********************** Drawing &amp; Output a png<br>async function main() {<br>  // print the graph<br>  const drawableGraph = await graph.getGraphAsync()<br>  const png = await drawableGraph.drawMermaidPng()<br>  Bun.write(process.cwd() + &#39;/src/simple/conditional-graph.png&#39;, png)<br>}<br><br>main()<br><br>// ********************** Invoking (With Stream)<br>// Invoke the graph<br>graph.invoke({})<br>// Invoke with stream<br>graph.stream({})</pre><p><strong>Output Png</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/1*619BjntWmRmx_14X5q6PLg.png" /><figcaption>output graph image</figcaption></figure><p>One of the most interesting things in Langgraph is the output you see above, from one picture you can figure out all the flow without debugging your code!</p><h4>Conditional Edges</h4><p>A special edge type lets you control the flow based on some conditions!</p><p>There are two ways to handle conditional edges</p><ol><li>using <strong>addConditionalEdges</strong></li></ol><pre><br>export const shouldContinue = async (state: typeof StateAnnotation.State) =&gt; {<br>  const random = Math.random() * 100<br>  if (random &gt; 50) {<br>    return END<br>  } else {<br>    return &#39;two&#39;<br>  }<br>}<br><br><br>const workflow = new StateGraph(StateAnnotation)<br>  .addNode(&#39;one&#39;, nodeOne)<br>  .addNode(&#39;two&#39;, nodeTwo)<br>  .addNode(&#39;three&#39;, nodeThree)<br>  // Conecting Edges<br>  .addEdge(START, &#39;one&#39;)<br>  .addEdge(&#39;one&#39;, &#39;two&#39;)<br>  .addEdge(&#39;two&#39;, &#39;three&#39;)<br>  .addEdge(&#39;three&#39;, END)<br>  .addConditionalEdges(&#39;one&#39;, shouldContinue, {<br>    true: &#39;two&#39;,<br>    false: END,<br>  })</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/1*Zd2ywIshjQ8LDdXKXW_SWw.png" /></figure><ol><li>using <strong>Command</strong></li></ol><p><em>(Command is using heavily with Human In the Loop Process)</em></p><p><strong>The main difference when using </strong><strong>Command is that you can update the state before routing!</strong></p><pre>export const nodeOne = async (state: typeof StateAnnotation.State) =&gt; {<br>  const someChecks = &#39;...&#39;<br>  if (someChecks) {<br>    return new Command({<br>      goto: END,<br>      // Update your state here!<br>      update: {<br>        // what to update<br>      },<br>    })<br>  }<br><br>  return new Command({<br>    goto: &#39;two&#39;,<br>  })<br><br>}</pre><h4>Langgraph Studio</h4><p>A desktop app for prototyping and debugging LangGraph applications locally, that allows you to <strong>debug, test, and run</strong> your workflow.</p><p><a href="https://studio.langchain.com/">download Langgraph Studio from here</a> and follow the steps below to start!</p><ol><li>Make sure you’ve installed <strong>docker</strong> and is running on your machine</li><li>Clone the <a href="https://github.com/mustafaskyer/langgraph-workflows"><strong>repo</strong></a></li><li>Drag your project, and from the bottom bar open project settings</li><li>Select NodeJS as the project version, and set the path of the graph to ./src/simple/graph.ts:graph don’t forget the :graphwhich is the named export from the graph.ts file</li><li>start the project, and run your flow from the submit button</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*REwc86HH0KcPlS1GERlqiA.png" /><figcaption>screenshot from langgraph studio</figcaption></figure><p>In the next article, I’ll demonstrate a real example workflow such as a TripPlanner using the same techniques that are explained here but with real agents and tools, stay tuned!</p><p><strong>Finally</strong>, Hopefully, you’ve learned something new, and if so please share it with anyone interested!</p><p><strong>Mustafa Elsayed</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=188fdc7fb1e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG with Langchain JS, OpenAI, and Pinecone]]></title>
            <link>https://medium.com/@mustafaskyer/rag-with-langchain-js-openai-and-pinecone-3755c65d5052?source=rss-6ec8da7ec721------2</link>
            <guid isPermaLink="false">https://medium.com/p/3755c65d5052</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[pinecone]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[langchainjs]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Mustafa Elsayed]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 14:54:25 GMT</pubDate>
            <atom:updated>2024-12-14T14:54:25.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8VJjdZyiaHoAI9Xu" /><figcaption>Software is eating the world, but AI is going to eat software. Jensen Huang</figcaption></figure><p>By the end of this article, you will gain a clear understanding of Retrieval-Augmented Generation (RAG), its benefits for enhancing AI applications, and a step-by-step guide to implementing it in JavaScript using LangChain.js and Pinecone Database.</p><h3>Introduction</h3><h4>What is RAG ?</h4><blockquote>RAG Is a technique for enhancing the accuracy and reliability of generative AI models with facts fetched from external sources. (source <a href="https://blogs.nvidia.com/blog/what-is-retrieval-augmented-generation/">Nvidia</a>)</blockquote><h4><strong>Why you might need to apply it in you AI app ?</strong></h4><ol><li><strong>Access to Up-to-Date Information</strong>:<br>RAG allows your AI to retrieve the latest or specific knowledge from external databases or documents, addressing the limitations of static training data.</li><li><strong>Improved Accuracy</strong>:<br>By combining a retrieval system with a generative model, RAG ensures responses are more grounded in factual information rather than relying solely on the model’s probabilistic reasoning.</li><li><strong>Domain-Specific Expertise</strong>:<br>If your application requires specialized knowledge (e.g., legal, medical, or financial), RAG can pull precise data from curated domain-specific sources.</li><li><strong>Cost-Effective Updates</strong><br>You can continuously improve the system by updating the retrieval database without needing extensive re-training cycles for the AI model.</li><li><strong>Context Limit </strong><br>Large Language Models (LLMs) have token limits that constrain how much information they can process at once. RAG helps manage this by dynamically fetching only the most relevant data, ensuring the AI stays within context limits while providing accurate and focused responses</li></ol><p>By leveraging <strong>RAG</strong>, you can combine the strengths of information retrieval and generative capabilities to build smarter, more reliable, and adaptable AI applications.</p><p>To enhance LLM results, reduce hallucination and provide much more clear and relevant information as a context to LLM.</p><h4>Steps To effectively implement the RAG technique in your AI app</h4><ol><li><strong>Index Your Data</strong><br>Prepare your data by gathering, processing, and organizing it into a structured format suitable for efficient retrieval.</li><li><strong>Store Data in Databases</strong><br>Utilize a database to store the processed data, ensuring it is readily available for retrieval when needed.</li><li><strong>Integrate with the LLM</strong><br>Append the retrieved data to the Large Language Model (LLM) context, enriching its input to produce more accurate and context-aware outputs.</li></ol><h4>Indexing your data</h4><p>for example in order providing LLM knowledge about your company data wether it’s public or private!</p><ol><li>you’ll need to collect all the data you need</li><li>then split these data into chunks</li><li>then embed it and store in a specific database type called <strong>Vector Databases</strong></li></ol><p><strong>Okay, now you might ask why I can’t provide these data to LLM directly without all these steps above ?</strong></p><p>the answer is due the following reasons</p><ol><li>LLM context size (chunking helps here by providing only chunks that are related to the user query)</li><li>avoid send large useless data to LLM, hence reduce hallucination (embeddings helps here, since it will retrieve the relevant content to the user query)</li><li>reduce cost. more input tokens means more money you will spend</li></ol><h4>Splitting your documents</h4><p>to divide a large large doc file into chunks. you’ll need to split it without loosing context meaning and minimize the context for each call!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*TvpERS0-dll6ysoaEKgFpQ.png" /><figcaption><a href="https://js.langchain.com/assets/images/text_splitters-7961ccc13e05e2fd7f7f58048e082f47.png">https://js.langchain.com/assets/images/text_splitters-7961ccc13e05e2fd7f7f58048e082f47.png</a></figcaption></figure><p>langchain provides a different tools to help you split your documents effortlessly such as (PDFs, CSvs, PPT, Txts, HTML, Webpages, …etc)</p><p><strong>Let’s cover some examples with coding</strong></p><p><em>example splitting Javascript code</em></p><pre>const JS_CODE = `<br>function helloWorld() {<br>  console.log(&quot;Hello, World!&quot;);<br>}<br><br>// Call the function<br>helloWorld();<br>`;<br>const jsSplitter = RecursiveCharacterTextSplitter.fromLanguage(&quot;js&quot;, {<br>  chunkSize: 60,<br>  chunkOverlap: 0,<br>});<br>const jsDocs = await jsSplitter.createDocuments([JS_CODE]);<br>jsDocs;</pre><p><em>Example Response</em></p><pre>[<br>  Document {<br>    pageContent: &#39;function helloWorld() {\n  console.log(&quot;Hello, World!&quot;);\n}&#39;,<br>    metadata: { loc: { lines: { from: 2, to: 4 } } }<br>  },<br>  Document {<br>    pageContent: &quot;// Call the function\nhelloWorld();&quot;,<br>    metadata: { loc: { lines: { from: 6, to: 7 } } }<br>  }<br>]</pre><p>To configure text splitting effectively, please consider the following parameters:</p><ul><li><strong>chunkSize</strong>: Defines the maximum size of each text chunk.</li><li><strong>chunkOverlap</strong>: Specifies the number of overlapping characters or tokens shared between consecutive chunks to preserve contextual integrity across splits.</li><li><strong>separator</strong>: Determines the delimiter used to segment the text into chunks.</li></ul><p><em>Example Html Splitter</em></p><pre>import { RecursiveCharacterTextSplitter } from &quot;@langchain/textsplitters&quot;;</pre><pre>const text = `&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;🦜️🔗 LangChain&lt;/title&gt;<br>    &lt;style&gt;<br>      body {<br>        font-family: Arial, sans-serif;<br>      }<br>      h1 {<br>        color: darkblue;<br>      }<br>    &lt;/style&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div&gt;<br>      &lt;h1&gt;🦜️🔗 LangChain&lt;/h1&gt;<br>      &lt;p&gt;⚡ Building applications with LLMs through composability ⚡&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div&gt;<br>      As an open source project in a rapidly developing field, we are extremely open to contributions.<br>    &lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;`;</pre><pre>const splitter = RecursiveCharacterTextSplitter.fromLanguage(&quot;html&quot;, {<br>  chunkSize: 175,<br>  chunkOverlap: 20,<br>});</pre><pre>const output = await splitter.createDocuments([text]);</pre><p><em>Example Response</em></p><pre>/*<br>  [<br>    Document {<br>      pageContent: &#39;&lt;!DOCTYPE html&gt;\n&lt;html&gt;&#39;,<br>      metadata: { loc: [Object] }<br>    },<br>    Document {<br>      pageContent: &#39;&lt;head&gt;\n    &lt;title&gt;🦜️🔗 LangChain&lt;/title&gt;&#39;,<br>      metadata: { loc: [Object] }<br>    },<br>    Document {<br>      pageContent: &#39;&lt;style&gt;\n&#39; +<br>        &#39;      body {\n&#39; +<br>        &#39;        font-family: Arial, sans-serif;\n&#39; +<br>        &#39;      }\n&#39; +<br>        &#39;      h1 {\n&#39; +<br>        &#39;        color: darkblue;\n&#39; +<br>        &#39;      }\n&#39; +<br>        &#39;    &lt;/style&gt;\n&#39; +<br>        &#39;  &lt;/head&gt;&#39;,<br>      metadata: { loc: [Object] }<br>    },<br>    Document {<br>      pageContent: &#39;&lt;body&gt;\n&#39; +<br>        &#39;    &lt;div&gt;\n&#39; +<br>        &#39;      &lt;h1&gt;🦜️🔗 LangChain&lt;/h1&gt;\n&#39; +<br>        &#39;      &lt;p&gt;⚡ Building applications with LLMs through composability ⚡&lt;/p&gt;\n&#39; +<br>        &#39;    &lt;/div&gt;&#39;,<br>      metadata: { loc: [Object] }<br>    },<br>    Document {<br>      pageContent: &#39;&lt;div&gt;\n&#39; +<br>        &#39;      As an open source project in a rapidly developing field, we are extremely open to contributions.\n&#39; +<br>        &#39;    &lt;/div&gt;\n&#39; +<br>        &#39;  &lt;/body&gt;\n&#39; +<br>        &#39;&lt;/html&gt;&#39;,<br>      metadata: { loc: [Object] }<br>    }<br>  ]<br>*/</pre><h3>Vector Databases</h3><p>A specific database type that you can store unstructured data, and search over it!</p><p><em>Note: that unstructured data almost represent </em><strong><em>80%</em></strong><em> of internet data such as pdfs, images, videos, audios, …etc</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*_Z_Vvkw7KSEVAa0mjhf7sQ.jpeg" /><figcaption><a href="https://weaviate.io/assets/images/image10-ebe747ac9f2e03dba758f1ed3ea7e82c.jpg">https://weaviate.io/assets/images/image10-ebe747ac9f2e03dba758f1ed3ea7e82c.jpg</a></figcaption></figure><p><em>The above image shows a multi dimensional vector db, which every word represent a specific dimension, and as you see similar words are nearest together than others</em></p><blockquote><strong>Embedding Projector</strong>: A live example to see how vector databases are is at <a href="https://projector.tensorflow.org/">this link</a> from google</blockquote><h3>Why Use Vector Databases?</h3><p>Traditional databases store data in tables or objects, and queries typically rely on exact matches, such as selecting records by IDs or specific keywords. However, vector databases operate differently, allowing for results based on similarity rather than exact matches.</p><h4>Example: Traditional Databases</h4><p>Consider a table of podcasts. If a user searches for the term <strong>“JavaScript”</strong> and your database doesn’t explicitly contain this keyword in any records, the query will return no results, leaving the user empty-handed.</p><h4>Example: Vector Databases</h4><p>Now, imagine the same search for <strong>“JavaScript”</strong> in a vector database. Even if the exact keyword <strong>“JavaScript”</strong> isn’t stored, the database can return related results like <strong>“Programming”</strong>, <strong>“Web Development”</strong>, or <strong>“React Js”</strong>.</p><p>This functionality is achieved through <strong>similarity search</strong>, where the database retrieves and ranks results based on their proximity to the query in vector space. The results are then sorted by a similarity score, providing more relevant and contextually rich outcomes.</p><blockquote>Note that vector databases are very fast in query, basically this is because it calculating the distance between all arrays. and then return the closest to the query (score)</blockquote><blockquote><strong>To summarize this, vector databases go beyond keywords searches. and provide the user what results he expected by meaning!</strong></blockquote><p>We will use <strong>pinecone</strong> as our a vector db in this article. but you can try others, please refer to <a href="https://js.langchain.com/docs/integrations/vectorstores/">this link</a> for more info</p><blockquote><strong>Pinecone</strong> is the leading knowledge platform for building accurate, secure, and scalable AI applications. they have a limit access to developers without payment required.and here’s the <a href="https://www.pinecone.io/">Link</a> to get access key!</blockquote><h3>Embeddings</h3><p>convert texts to numbers. to be able to save your data into a <strong>vector database</strong>, you’ll have to embed it first!</p><p><em>Embeddings example with langchain</em></p><pre>import { OpenAIEmbeddings } from &quot;@langchain/openai&quot;;<br><br>const embeddings = new OpenAIEmbeddings();<br><br>const res = await embeddings.embedQuery(&quot;Hello world&quot;); // query<br><br>const resDocs = await embeddings.embedDocuments([&quot;Hello world&quot;]); // docs</pre><p><em>Example Response</em></p><pre>/*<br>[<br>   -0.004845875,   0.004899438,  -0.016358767,  -0.024475135, -0.017341806,<br>    0.012571548,  -0.019156644,   0.009036391,  -0.010227379, -0.026945334,<br>    0.022861943,   0.010321903,  -0.023479493, -0.0066544134,  0.007977734,<br>   0.0026371893,   0.025206111,  -0.012048521,   0.012943339,  0.013094575,<br>   -0.010580265,  -0.003509951,   0.004070787,   0.008639394, -0.020631202,<br>  ... 1511 more items<br>]<br>*/</pre><p>Here’s a more polished and technical rewrite:</p><h3>LangChain</h3><p>LangChain is among the first open-source frameworks enabling developers to harness the power of large language models (LLMs) with an exceptional developer experience and extensive community support. It supports two programming languages: <strong>Python</strong> and <strong>JavaScript</strong>.</p><p>In addition to its core framework, LangChain offers complementary tools to enhance the development and deployment of AI-driven workflows:</p><ul><li><strong>LangSmith</strong>: A suite designed for debugging, testing, and monitoring AI workflows, ensuring reliability and performance.</li><li><strong>LangServe</strong>: A platform that facilitates the deployment of LangChain-powered APIs, simplifying production integration.</li></ul><h3>Example Code Implementing All the Above Steps</h3><p>Assume we’ll simulate a real-world use case here where a user might ask specific questions about your company. Here’s the approach we’ll take:</p><ol><li><strong>Load Data</strong>: Import data from a custom PDF file.</li><li><strong>Embed and Store</strong>: Process the data by embedding it and storing the embeddings in <strong>Pinecone</strong>.</li><li><strong>Retrieve Relevant Data</strong>: Query Pinecone to retrieve contextually relevant information, which will then be provided as context to the LLM for generating accurate responses.</li></ol><p><strong><em>Loading Data</em></strong></p><p>you’ll need to add pdf-parse for pdfs load</p><pre>pnpm add pdf-parse</pre><p><em>Load your data</em></p><pre>import { PDFLoader } from &quot;@langchain/community/document_loaders/fs/pdf&quot;;<br><br>const loader = new PDFLoader(&quot;./example.pdf&quot;);<br><br>const docs = await loader.load();</pre><p><em>Split your data</em></p><pre>import { RecursiveCharacterTextSplitter } from &quot;@langchain/textsplitters&quot;;<br><br>const textSplitter = new RecursiveCharacterTextSplitter({<br>  chunkSize: 1000,<br>  chunkOverlap: 200,<br>});<br><br>const splittedDocs = await textSplitter.splitDocuments(docs);</pre><p><strong><em>Embedding your data</em></strong></p><pre>import { OpenAIEmbeddings } from &quot;@langchain/openai&quot;;<br><br>const embeddings = new OpenAIEmbeddings({<br>  model: &quot;text-embedding-3-small&quot;,<br>});<br><br>const documentRes = await embeddings.embedDocuments(docs)</pre><p><strong><em>store data into pinecone</em></strong></p><pre>import { PineconeStore } from &quot;@langchain/pinecone&quot;;<br>import { OpenAIEmbeddings } from &quot;@langchain/openai&quot;;<br>import type { Document } from &quot;@langchain/core/documents&quot;;<br><br>import { Pinecone as PineconeClient } from &quot;@pinecone-database/pinecone&quot;;<br><br>const pinecone = new PineconeClient();<br><br>const pineconeIndex = pinecone.Index(process.env.PINECONE_INDEX!);<br><br>const vectorStore = await PineconeStore.fromExistingIndex(embeddings, {<br>  pineconeIndex,<br>  // Maximum number of batch requests to allow at once. Each batch is 1000 vectors.<br>  maxConcurrency: 5,<br>  // You can pass a namespace here too<br>  // namespace: &quot;foo&quot;,<br>});<br><br>await vectorStore.addDocuments(documentRes, { ids: [...] }); // ids optional</pre><p><strong><em>Retrieve from pinecone</em></strong></p><pre>// Optional filter<br>const filter = {}; // a match to your metdata when insert<br><br>const similaritySearchResults = await vectorStore.similaritySearch(<br>  &quot;user-query&quot;,<br>  2,  // number of results<br>  filter // optional<br>);<br><br>for (const doc of similaritySearchResults) {<br>  console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);<br>}</pre><p><em>Also you can query as Retriever (the LLM way)</em></p><pre>const retriever = vectorStore.asRetriever({<br>  filter: filter,<br>  k: 2, // number of results<br>});<br><br>await retriever.invoke(&quot;user-query&quot;);</pre><p><em>User Query</em></p><pre>import { ChatOpenAI } from &quot;@langchain/openai&quot;;<br>import { PromptTemplate } from &quot;@langchain/core/prompts&quot;;<br>import { StringOutputParser } from &quot;@langchain/core/output_parsers&quot;;<br><br>// LLM<br>const llm = new ChatOpenAI({<br>  model: &quot;gpt-4o&quot;,<br>  temperature: 0.1<br>});<br><br>// PROMPT<br>const customTemplate = `Use the following pieces of context to answer the question at the end.<br>If you don&#39;t know the answer, just say that you don&#39;t know, don&#39;t try to make up an answer.<br>Use three sentences maximum and keep the answer as concise as possible.<br>Always say &quot;thanks for asking!&quot; at the end of the answer.<br><br>{context}<br><br>Question: {question}<br><br>Answer:`;<br><br><br>const customRagPrompt = PromptTemplate.fromTemplate(customTemplate);<br><br>const customRagChain = await createStuffDocumentsChain({<br>  llm: llm,<br>  prompt: customRagPrompt,<br>  outputParser: new StringOutputParser(), // output result as string<br>});<br><br>const userQuery = &quot;What services can you offer?&quot;;<br><br><br>const context = await retriever.invoke(userQuery);<br><br>const res = await customRagChain.invoke({<br>  question: userQuery,<br>  context,<br>});<br><br><br>console.log(&#39;res&#39;, res)</pre><p><strong>Resources</strong></p><ul><li><a href="https://js.langchain.com/docs/introduction/">Langchain JS</a> including the repo examples</li><li><a href="https://www.pinecone.io/">Pineone</a></li><li><a href="https://weaviate.io/blog/vector-embeddings-explained">https://weaviate.io/blog/vector-embeddings-explained</a></li><li><a href="https://platform.openai.com/docs/guides/embeddings/what-are-embeddings?lang=node">https://platform.openai.com/docs/guides/embeddings/what-are-embeddings?lang=node</a></li><li><a href="https://blogs.nvidia.com/blog/what-is-retrieval-augmented-generation/">https://blogs.nvidia.com/blog/what-is-retrieval-augmented-generation</a></li></ul><p><strong><em>This article has been reviewed by</em></strong></p><ul><li><strong><em>Eng Hakeem Sebssi </em></strong><em>(AI Engineering Manager)</em></li><li><strong><em>Eng Ahmed Maher </em></strong><em>(Senior Data Engineer)</em></li><li><strong>Sherif ElAgami </strong>(Technical Lead)</li></ul><p><em>Thank you very much for your support and feedback!</em></p><p><strong><em>Finally</em></strong><em> I hope you’ve learned something new today!</em></p><p><strong><em>In the Next Article I will write in details how to enhance your RAG system, By applying different strategies, and techniques in how to achieve this as the best practice. if you’re interested, please follow to keep up to date!</em></strong></p><p>#openai #langchain #langchainjs #pinecon #embeddings #rag #AI #vector_databases #pdf #document_loaders</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3755c65d5052" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Playwright]]></title>
            <link>https://medium.com/@mustafaskyer/getting-started-with-playwright-0cb92b8af81e?source=rss-6ec8da7ec721------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cb92b8af81e</guid>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[playwright-test]]></category>
            <dc:creator><![CDATA[Mustafa Elsayed]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 08:55:15 GMT</pubDate>
            <atom:updated>2024-06-30T09:02:23.224Z</atom:updated>
            <content:encoded><![CDATA[<p>Playwright is a reliable end-to-end testing framework for modern web apps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qB8zdMK2sgdGQZvd2KEJFQ.jpeg" /></figure><blockquote>Just because you’ve counted all the trees doesn’t mean you’ve seen the forest. Anonymous</blockquote><p><strong>playwright</strong> is an End-to-end testing library to simulate the end user interacting with your web application.</p><p>e.g. a user visits your page. click login, enter credentials, and submit the form</p><p>you can simulate all of these steps as an end user. by using playwright tests which run in all browsers and all platforms</p><h3><strong>Agenda</strong></h3><p>what we’ll cover in this article</p><ul><li><strong>Setup</strong></li><li><strong>Write Your First Test</strong></li><li><strong>CLI Options</strong></li><li><strong>Take Screenshots / Videos of your tests</strong></li><li><strong>Hooks</strong></li><li><strong>Page Object Models</strong></li><li><strong>Visual Regression Testing</strong></li><li><strong>REST API’s Testing</strong></li></ul><h3>Setup</h3><pre>pnpm create playwright</pre><p>you’ll be prompted to answer a few questions, here’s my answers</p><pre>✔ Do you want to use TypeScript or JavaScript? · TypeScript<br>Where to put your end-to-end tests? · tests<br>Add a GitHub Actions workflow? (y/N) › false</pre><p>This will create a playwright app with the following structure</p><pre>- tests<br>- tests-examples<br>- package.json<br>- playwright.config.ts</pre><p>Run the example test</p><pre>pnpm exec playwright test // npx playwright test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*Sl_8j7w5cx0zHVS5_J8QGg.png" /><figcaption>pnpm exec playwright test</figcaption></figure><p>After the test is complete.A report should be generated automatically by the playwright.</p><pre>// show the report<br><br>pnpm exec playwright show-report</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a20kAJPw1wcqNVLK7nFK7A.png" /><figcaption>playwright report</figcaption></figure><p>Notice you have filters to filter between passed, failed and skipped tests.</p><h3>Write your first test</h3><pre>import { test, expect } from &#39;@playwright/test&#39;;<br><br>test(&#39;has title&#39;, async ({ page }) =&gt; {<br><br>  // visiting the page<br>  await page.goto(&#39;https://playwright.dev/&#39;);<br><br>  // Expect a title &quot;to contain&quot; a substring.<br>  await expect(page).toHaveTitle(/Playwright/);<br><br>});</pre><p>Explanation.</p><ol><li>We’ve created a test called has title each test callback as an async. and it produces page and you’ve other params such as browser and userAgent</li><li>we’re visiting the page <a href="https://playwright.dev">https://playwright.dev</a> and wait until it’s load</li><li>we assert that the page should have a title with /Playwright/ which is a regex.</li></ol><h4>Second test</h4><p>let’s write a more complex scenario which is:</p><p>visiting github page. search for playwright. clicking on playwright repo. and assert we&#39;re on the repo as we expect!</p><pre>import { expect, test } from &#39;@playwright/test&#39;<br><br>test(&#39;playwrigh github&#39;, async ({ page }) =&gt; {<br>  await page.goto(&#39;https://github.com/&#39;)<br>  await page.click(&#39;button[data-target=&quot;qbsearch-input.inputButton&quot;]&#39;)<br>  const input = await page.$(&#39;#query-builder-test&#39;)<br>  input?.focus()<br>  input?.fill(&#39;Playwright&#39;)<br>  input?.press(&#39;Enter&#39;)<br><br>  await expect(page).toHaveTitle(/results/)<br>  const link = await page.waitForSelector(&#39;a[href=&quot;/microsoft/playwright&quot;]&#39;)<br>  await link?.click()<br><br>  await expect(page).toHaveTitle(/microsoft\/playwright/)<br>})</pre><p>Run the test</p><pre>npx playwright test tests/playwright-github.spec.ts --headed --project=chromium </pre><p>I added more args to the CLI to view the test visually and in the Chromium browser like the below image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3_O2DUfS7cfHbRtKlNSVdQ.gif" /><figcaption>result of playwright test on github</figcaption></figure><p>Explanation</p><ol><li>visiting the github.com page</li><li>clicking on the search bar. I’ve inspected it and found it easy to select using the data-target button[data-targer=&quot;...&quot;]</li><li>select the input. also, I’ve inspected and found its ID. you can choose ID by# sign following with the id value</li><li>I’ve saved the input since We will need it to focus, fill, and submit the form.</li><li>After summiting we’re asserting that we’ve moved to a new page. and expect to have /results/ as a regex</li><li>again inspect the target result and found it has a unique href value. and we’ve to save the link since we’ll need to click</li><li>the last step. we’re asserting that we’re in the repo by checking the right URL github.com/microsoft/playwright</li></ol><h3>CLI Options</h3><ol><li>--headed this will visually preview tests in the target browser</li><li>--browser run tests in a specific browser or all</li></ol><pre>pnpm exec playwright test --browser=chromium|all|firefox</pre><p>3. select specific test/tests</p><pre>// pnpm exec playwright test &lt;path-to-test-file1&gt; &lt;path-to-file2&gt; ...etc<br><br>pnpm exec playwright test tests/playwright-github.spec.ts</pre><p>4. --ui run tests in interactive UI mode. ( supports watch mode also )</p><p>this will open a new portal to run your tests manually like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JwO4dtl5dN2QgOeqNQoWgA.png" /></figure><pre>pnpm exec playwright test --ui</pre><p>5. --reporter generate test results in a specific format like html</p><p>options are line dot html json …etc</p><pre>pnpm exec playwright test --report=html // this is the default</pre><h3>Take Screenshots / Videos of your tests</h3><p>some tests require you to take screenshots/videos of your tests. simply you can update this from playwright.config.ts in the use property like below</p><pre>export default defineConfig({<br>  // ...<br>  use: {<br>    video: &#39;on&#39;,<br>    screenshot: &#39;on&#39;,<br>  },<br>})</pre><h3>Hooks</h3><p>Before &amp; After Hooks</p><ul><li>beforeAll run once before all tests</li><li>beforeEach run every time before each test</li><li>afterAll run once after all tests</li><li>afterEach run every time after each test</li></ul><p>Example</p><pre>test.describe(&#39;Screenshots&#39;, () =&gt; {<br><br>  test.beforeEach(async ({ page }) =&gt; {<br>    await page.goto(&#39;https://example.com&#39;);<br>  });<br><br>  <br>  test(&#39;Screenshots&#39;, async ({ page }) =&gt; {<br>    await page.screenshot({<br>      path: `screenshots/example.com.png`,<br>      fullPage: true,<br>    });<br>  });<br><br>  test(&#39;Single Element Screenshot&#39;, async ({ page }) =&gt; {<br>    const element = await page.locator(&#39;div&#39;);<br>    await element?.screenshot({ path: `screenshots/example.com-h1.png` });<br>  });<br>});</pre><p>Here before each test, we want to visit the example.com web page. so the second test assumes that we’re already in exmple.com and hence take the screenshot of the page itself.</p><h3>Page Object Models</h3><p>is a design pattern that creates an object repository for storing web elements</p><p>it’s useful for reducing code duplication and improving test cases</p><h4>Example</h4><p>Create a Page Object Model for a login page of zero.webappsecurity.com</p><pre>import { Locator, Page, expect } from &#39;@playwright/test&#39;;<br><br>export class LoginPage {<br> // selectors<br>  readonly page: Page;<br>  readonly usernameInput: Locator;<br>  readonly passwordInput: Locator;<br>  readonly submitButton: Locator;<br>  readonly errorMessage: Locator;<br><br> // initialzation<br>  constructor(page: Page) {<br>    this.page = page;<br>    this.usernameInput = page.locator(&#39;#user_login&#39;);<br>    this.passwordInput = page.locator(&#39;#user_password&#39;);<br>    this.submitButton = page.locator(&#39;input[type=&quot;submit&quot;]&#39;);<br>    this.errorMessage = page.locator(&#39;.alert-error&#39;);<br>  }<br><br> /** methods */<br><br>  async visit() {<br>    await this.page.goto(&#39;http://zero.webappsecurity.com&#39;);<br>  }<br><br>  async login(username: string, password: string) {<br>    await this.page.click(&#39;#signin_button&#39;);<br>    await this.usernameInput.fill(username);<br>    await this.passwordInput.fill(password);<br>    await this.submitButton.click();<br>  }<br><br>  async assertErrorMessage() {<br>    return await expect(this.errorMessage).toContainText(<br>      &#39;Login and/or password are wrong.&#39;,<br>    );<br>  }<br>}</pre><p>Explanation</p><ol><li>create a class with page object modal name. and export it</li><li>define selectors e.g page usernameInput … etc</li><li>define methods e.g visit login assertErrorMessage</li></ol><p>Example usage</p><pre>import { LoginPage } from &#39;./page-objects/LoginPage&#39;;<br><br><br>test(&#39;Login / Logout Flow&#39;, () =&gt; {<br><br>  let loginPage: LoginPage;<br>  <br>  test.beforeEach(async ({ page }) =&gt; {<br>    loginPage = new LoginPage(page);<br>    await loginPage.visit();<br>  });<br><br><br>  test(&#39;Success [Login]&#39;, async ({ page }) =&gt; {<br>    await loginPage.login(&#39;username&#39;, &#39;password&#39;);<br>    await page.goto(&#39;http://zero.webappsecurity.com/bank/transfer-funds.html&#39;);<br>    const summaryTab = await page.locator(&#39;#account_summary_tab&#39;);<br>    await expect(summaryTab).toBeVisible();<br>  });<br><br><br>});</pre><p>Explanation</p><ol><li>importing the page object mode which is LoginPage</li><li>assign a login page to the loginPage before each test</li><li>using methods of login page</li></ol><h3>Visual Regression Testing</h3><p>is a process that checks a user interface to ensure that recent changes don’t affect previously passed tests by comparing current screenshots to previously passed screenshots.</p><p>In other words</p><p>suppose you write a test. the passed test will be captured as a screenshot. in case you run the test and find a difference between the new screenshot and the current one. the test should fail.</p><p><em>note that in case there’s a little bit different change such as text color changes from</em><em>red-400 to </em><em>red-300 it will notice that and hence will fail the test</em></p><p>Example</p><pre>test.describe(&#39;Visual Regression Test Exampel&#39;, () =&gt; {<br>  test(&#39;Full Page Snapshot&#39;, async ({ page }) =&gt; {<br>    await page.goto(&#39;https://example.com&#39;);<br>    expect(await page.screenshot()).toMatchSnapshot(&#39;example-web.png&#39;);<br>  });<br>});</pre><p>Note that the first time will always fail since there aren’t shots yet. but the second time it should pass.</p><p>In case you need to update the snapshot (override it)</p><pre>pnpm exec playwright test --update-snapshots</pre><h3>Rest API Testing</h3><p>we’ll be using the <a href="https://reqres.in/">ReqRes</a> acting as a backend side for our case here</p><p><strong>Example</strong></p><p>Assert Response status to be 200 (success response)</p><pre>import { expect, test } from &#39;@playwright/test&#39;<br><br>test.describe(&#39;&#39;, () =&gt; {<br>  test(&#39;Simple API Test - Assert Response Status&#39;, async ({ request }) =&gt; {<br>    const response = await request.get(&#39;https://reqres.in/api/users/2&#39;)<br>    await expect(response.status()).toBe(200)<br>  })<br>})</pre><p>Assert Invalid Endpoint</p><pre> test(&#39;Simple API Test - Assert Invalid Endpoint&#39;, async ({ request }) =&gt; {<br>    const response = await request.get(<br>      &#39;https://reqres.in/api/users/invalid-endpoint&#39;,<br>    )<br>    console.log(&#39;Response 404:&#39;, response.status())<br>    await expect(response.status()).toBe(404)<br>  })</pre><p>Parsing the Response</p><pre>test(&#39;Simple API Test - Assert Response Status&#39;, async ({ request }) =&gt; {<br>    const response = await request.get(&#39;https://reqres.in/api/users/2&#39;)<br>    console.log(&#39;Response 200:&#39;, response.status())<br>    const text = await JSON.parse(await response.text())<br>    console.log(&#39;Response Text:&#39;, JSON.stringify(text, null, 2))<br>    await expect(response.status()).toBe(200)<br>  })</pre><p>Assert Single User</p><pre>  test(&#39;Simple API Test - Assert User Detai;s&#39;, async ({ request }) =&gt; {<br>    const response = await request.get(&#39;https://reqres.in/api/users/1&#39;)<br>    const responseBody = await response.json()<br>    expect(responseBody.data.id).toBe(1) // id should be 1<br>    expect(responseBody.data.first_name?.length).toBeGreaterThan(0) // should exist<br>    expect(responseBody.data.last_name?.length).toBeGreaterThan(0) should exist<br>    expect(responseBody.data.email).toMatch(/@reqres.in$/) // email should be `*@reqres.in`<br>    expect(response?.status()).toBe(200)<br>  })</pre><p>Thanks for reaching out here. hopefully, this was helpful for you!</p><p>Thanks to <a href="https://www.linkedin.com/in/shreifashrafelagamy/">Sherif Ashraf</a> and <a href="https://www.linkedin.com/in/mahmoud-ebrahim20">Mahmoud Awad</a> for the Review.</p><p>Best Regards</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cb92b8af81e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Immutability with React Native Using Immer.js]]></title>
            <link>https://medium.com/@mustafaskyer/immutability-with-react-native-using-immer-js-fe3dc0e5dc95?source=rss-6ec8da7ec721------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe3dc0e5dc95</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[immer]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Mustafa Elsayed]]></dc:creator>
            <pubDate>Sat, 31 Aug 2019 20:22:38 GMT</pubDate>
            <atom:updated>2019-08-31T20:22:38.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wb4xecNqjE1iB77J6OV6xA.jpeg" /></figure><blockquote>Life without dreams is like a bird with a broken wing — it can’t fly. #<strong>Dan Pena</strong></blockquote><p><strong><em>— Topics to cover in this share</em></strong></p><ul><li><em>Understanding The Immutability</em></li><li><em>Persistence Data Structure</em></li><li><em>Why Immutability</em></li><li><em>Immer.js</em></li><li><em>Immer Examples with React Native (state, reducer, hooks)</em></li></ul><p><strong><em>— Understanding Immutability</em></strong></p><blockquote><strong><em>Objects that after created, will never change or update</em></strong></blockquote><pre>const books = [{...},{...},{...},{...}]</pre><p>Immutability means that after you created books array you can’t update any book or add a new book to the original books</p><p>Okay Cool, why I need to use Immutability,</p><p>we can just use (const, Object.freeze or Object.seal)</p><p>First to know is <strong>const</strong> neither <strong>Object.freeze </strong>makes your object Immutable, you always can make a change or update it after created.</p><pre>const arr = [.....] // const doesn&#39;t allow to reasign the object</pre><pre>arr = {} // ❌ not allowed =&gt; can&#39;t reassign arr<br><strong>// But<br>arr.push()  // ✅ can update<br>arr[0] = {} // ✅ can update</strong></pre><pre>// ----------------- <strong>Object.freeze</strong> -----------------<br>// yes you can&#39;t update the array items, <br>// but just try to updated deeply items, it will update</pre><pre>const arr = Object.freeze([<br>      { id: 1, name: &#39;ss&#39; },</pre><pre>      { id: 2, name: &#39;ss&#39; },</pre><pre>      { id: 3, name: &#39;ss&#39; }</pre><pre>])</pre><pre>arr[1] = null // ❌ array item not updated</pre><pre>arr[1].name = &#39;updated&#39; // updated ✅</pre><p><em>Why Immutability?</em></p><p><em>or ask instead </em><strong><em>why not Immutability</em></strong><em> ??</em></p><ul><li><em>Mutations are unpredictable, so it’s not safe</em></li><li><em>Mutations hiding changes &amp; allows producing side effects</em></li><li><em>harder to reason about and can cause nasty bugs</em></li><li><em>Mutations may cost you performance and more memory</em></li></ul><p><strong><em>— Persistence Data Structure</em></strong></p><blockquote>a <strong>persistent data structure</strong> is a <a href="https://en.wikipedia.org/wiki/Data_structure">data structure</a> that always preserves the previous version of itself when it is modified. Such data structures are effectively <a href="https://en.wikipedia.org/wiki/Immutable_object">immutable</a>, as their operations do not (visibly) update the structure in-place, but instead always yield a new updated structure.</blockquote><p>by saying never change, what if we have to update an object or add new data Using Immutability,</p><p>Immutability never update the object, rather it will make a new copy with the new updates for it, so the original object didn’t touch by any way</p><p>But, sure that cost you more memory hence more time</p><p>Fortunately, Immutability uses Structure sharing which not copy the original, just refer to it</p><blockquote>Structure sharing is the way how we copy the new array we just make the new update and still sharing others nodes with the two arrays</blockquote><p><strong>Trie</strong></p><blockquote>a <strong>trie </strong>is a kind of <a href="https://en.wikipedia.org/wiki/Search_tree">search tree</a> — an ordered <a href="https://en.wikipedia.org/wiki/Tree_(data_structure)">tree</a> <a href="https://en.wikipedia.org/wiki/Data_structure">data structure</a> used to store a <a href="https://en.wikipedia.org/wiki/Set_(abstract_data_type)">dynamic set</a> or <a href="https://en.wikipedia.org/wiki/Associative_array">associative array</a> where the keys are usually <a href="https://en.wikipedia.org/wiki/String_(computer_science)">strings</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*B2S4D_mmo35Ak1oaB5EGHQ.gif" /><figcaption>an image that describes how structural sharing works (<strong>Trie</strong>)</figcaption></figure><blockquote><em>Life is really simple, but we insist on making it complicated. #Confucius</em></blockquote><p><a href="https://github.com/immerjs/immer"><strong><em>— Immer.js</em></strong></a></p><blockquote>immer is a tiny package that allows you to work with immutable state in a more convenient way. It is based on the <a href="https://en.wikipedia.org/wiki/Copy-on-write"><em>copy-on-write</em></a> mechanism</blockquote><blockquote>The basic idea is that you will apply all your changes to a temporarily <em>draftState</em>, which is a proxy of the <em>currentState</em>. Once all your mutations are completed, Immer will produce the <em>nextState</em> based on the mutations to the draft state. This means that you can interact with your data by simply modifying it while keeping all the benefits of immutable data</blockquote><p><strong><em>Immer with React Native</em></strong></p><blockquote><strong><em>Example setState</em></strong></blockquote><pre><em>import produce from &quot;immer&quot;;</em></pre><pre><em>this.setState({ user: {} })</em></pre><pre><em>------------------------------------</em></pre><pre><em>this.setState(produce(draft =&gt; drafte.user = {}))</em></pre><blockquote><strong><em>Reducer Example</em></strong></blockquote><pre><strong><em>import produce from &quot;immer&quot;;</em></strong></pre><pre><em>import {</em></pre><pre><em>LOGIN_USER,</em></pre><pre><em>} from &#39;REDUX_TYPES&#39;;</em></pre><pre><em>const INITIAL_STATE = { user: null };</em></pre><pre><em>export default (state = INITIAL_STATE, action) =&gt; {</em></pre><pre><em>      </em><strong><em>return produce(state, draft =&gt; {</em></strong></pre><pre><strong><em>      switch (action.type) {</em></strong></pre><pre><strong><em>            case LOGIN_USER:</em></strong></pre><pre><strong><em>            draft = { loading: true };</em></strong></pre><pre><strong><em>            return draft;</em></strong></pre><pre><strong><em>      }</em></strong></pre><pre><strong><em>    });</em></strong></pre><pre><em>};</em></pre><p><a href="https://github.com/immerjs/use-immer"><strong><em>Use Immer</em></strong></a><strong><em> with Hooks</em></strong></p><blockquote><strong><em>Hooks Example</em></strong></blockquote><pre><strong><em>import { useImmer } from &quot;use-immer&quot;;</em></strong></pre><pre><em>function UseImmerEx(props) {</em></pre><pre>      <strong><em>const [active, setActive] = useImmer(false);</em></strong></pre><pre>      <em>useEffect(() =&gt; {</em></pre><pre><em>            /**  */</em></pre><pre>            <strong><em>setActive(draft =&gt; draft = true)<br>     <br></em></strong><em>            return (() =&gt; {<br>                   // unmount</em></pre><pre><em>            })</em></pre><pre><em>      },[]);</em></pre><pre><em>      return (</em></pre><pre><em>            &lt;View /&gt;</em></pre><pre><em>      )</em></pre><pre><em>}</em></pre><p><em>Thanks for reading :)</em></p><p><em>Feedbacks are very welcome, regards</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe3dc0e5dc95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting SVG Images to react/react-native Components By Using CLI]]></title>
            <link>https://medium.com/@mustafaskyer/converting-svg-images-to-react-react-native-components-by-using-cli-a3202d3d2586?source=rss-6ec8da7ec721------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3202d3d2586</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native-svg]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[svg]]></category>
            <dc:creator><![CDATA[Mustafa Elsayed]]></dc:creator>
            <pubDate>Wed, 16 Jan 2019 19:29:37 GMT</pubDate>
            <atom:updated>2019-01-16T19:29:37.622Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Converting SVG Images to react/react-native Components By Using CLI</em></strong></p><p><em>Using SVG in your projects is lighting your images in a much better way,</em></p><p><em>It shows images more clear than others</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*QaBxmNGApuBwp_pruDS2RQ.jpeg" /></figure><h3>SVGR/CLI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*M708ovwtNLGGeNXe8TJm-A.png" /></figure><p><strong>What SVGR/CLI?</strong></p><blockquote>SVGR transforms SVG into ready to use components.</blockquote><blockquote><em>Simply , it turns your SVG images to reusable react native component</em></blockquote><blockquote>SVGR, can convert all *.svg in a specific directory to an *.js components,</blockquote><blockquote>by only one command line :^)</blockquote><p><strong>Before we dive into with CLI</strong></p><p>you can try it without opening the terminal or write any commands, by opening the playground <a href="https://www.smooth-code.com/open-source/svgr/playground/">link</a>,</p><p>It’s very simple process,</p><p>Give it your SVG file and it’ll produce .js component :)</p><h4>Installation</h4><pre>npm install @svgr/cli</pre><pre><em># or use yarn</em></pre><pre>yarn add @svgr/cli</pre><pre># install npx globaly</pre><pre>npm i -g npx</pre><pre># or</pre><pre>yarn add global npx</pre><blockquote>Note</blockquote><pre>--native, means that&#39;s you target react native framework,<br>otherwise, your target is react for web</pre><h4>Usage</h4><pre>npx @svgr/cli --native path-to-icon/icon.svg</pre><blockquote>create a new component from SVG file</blockquote><pre>npx @svgr/cli --native path-to-icon/icon.svg &gt; components-path/icon.js</pre><blockquote>Before</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFdJGB1b2zuUoprb8qkATg.png" /></figure><blockquote>After</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ogbHYHs-vWP4Y1gJDIqEQ.png" /></figure><blockquote>Convert the whole directory with SVG files</blockquote><pre>npx @svgr/cli -d --native svg-dir svg-dir/</pre><pre># NOTE<br>-d directory<br>--native create react native components<br>svg-dir the directory which contains *.svg files<br>svg-dir also will create *.js file in the same directory</pre><p><em>this will convert all *.svg to a react native components,</em></p><p><em>Finally, you can read more about that awesome package from the following link </em><a href="https://github.com/smooth-code/svgr"><em>https://github.com/smooth-code/svgr</em></a></p><p><em>hopefully, that helps</em></p><p><em>thanks for reading :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3202d3d2586" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Closures & Scopes JS]]></title>
            <link>https://medium.com/@mustafaskyer/closures-scopes-js-afbf816b71cd?source=rss-6ec8da7ec721------2</link>
            <guid isPermaLink="false">https://medium.com/p/afbf816b71cd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[scopes]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Mustafa Elsayed]]></dc:creator>
            <pubDate>Sat, 24 Nov 2018 16:17:36 GMT</pubDate>
            <atom:updated>2019-01-12T22:14:27.440Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Most of the biggest problems in software are problems of misconception “Rich Hickey”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGOv6BZJR1v2-IUjo79BnQ.jpeg" /></figure><h3>Introduction</h3><p><em>Scopes and Closures are very important in JS, I am sure that you use it before for many times without knowing or recognizing, so let me explain more about it in this share.</em></p><p><strong><em>How does JS engine works?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*QiZxk0Hk0Bk644guPfww5g.png" /></figure><p><em>To Understand How js engine work, we have to explain how it store variables and how to find these variables in need.</em></p><p><strong><em>AST (Abstract Syntax Tree)</em></strong><em> which is represent the parsing stage in the above picture, it takes an array of tokens and turns it into a tree of nested elements.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*U_GaAB5yXYc9HnazUqNwBQ.png" /></figure><pre>let message = &#39;Message ...&#39;</pre><pre>function foo(){<br>   console.log(&#39;Hello ..&#39;);<br>}<br>foo()</pre><p><strong>RHS &amp; LHS (Right Hand Side &amp; Left Hand Side)</strong></p><blockquote><em>but we can consider that</em><strong><em> RHS(retrieve his/her source)</em></strong></blockquote><p><em>so we can say that the message variable on the left side is an </em><strong><em>LHS</em></strong><em>,</em></p><p><em>foo() is an </em><strong><em>RHS </em></strong><em>which is referred to its reference foo function</em></p><p><em>I won’t go deep into these here, but in case you are, I’d recommend for you to read </em><a href="https://codeburst.io/understanding-javascripts-engine-with-cartoons-3ef56487a987"><em>Understanding JavaScript’s Engine with Cartoons</em></a><em>.</em></p><p><strong><em>What is a Scope?</em></strong></p><ul><li><em>The accessibility of variables, functions, and objects in some particular part of your code during runtime.</em></li><li><em>a set of rules for storing variables in some location and find these variables for future use.</em></li></ul><p><strong><em>what’s type error ?</em></strong></p><p><em>type error occurs when you try to execute a function with a non-function,</em></p><p><em>or reference to a property on a null or undefined value.</em></p><pre>let message = &#39;Message&#39;<br>message(); // &quot;<strong>TypeError</strong>: message is not a function&quot;</pre><p><strong><em>Explanation</em></strong><em>: message already exist in our scope, but you try to execute it as a-function which is none-function</em></p><p><strong><em>What is reference error ?</em></strong></p><p><em>is a scope resolution failure related, when scope compiler works to find RHS &amp; LHS &amp; find no results, you’ll get a reference error :-</em></p><pre>console.log(noneExistVariable); <br>              // &quot;<strong>ReferenceError</strong>://noneExistVariable is not defined&quot;</pre><p><strong><em>Reference error &amp; Type Error</em></strong></p><ul><li><em>reference error is a scope resolution failure related .</em></li><li><em>type error implies that scope resolution was successful, but there was an impossible action attempted against the result.</em></li></ul><p><strong><em>Lexical Scope (Static)</em></strong></p><p><em>lexical scope is based on where variables and blocks of scope are authored by you at write time, defines how variable names are resolved in nested functions.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*R6d-JBN0NGefNLK1uiUAyA.png" /></figure><p><em>in the above pic, we have three scopes</em></p><ul><li><strong><em>Global Scope </em></strong><em>which it’s variables can access from any other scopes</em></li><li><strong><em>Function Scope foo, </em></strong><em>sure it access global scope and variables, function inside it’s body, but none inside inner function such as </em><strong><em>bar </em></strong><em>function</em></li><li><strong><em>Function Scope Bar </em></strong><em>which can access global, foo scopes, and sure variables and functions inside it’s body</em></li></ul><blockquote>We can call this Lexical scope, which explains that inner functions contain the scope of parent functions even if the parent function has returned.</blockquote><p><strong><em>Block Scope</em></strong></p><p><em>The block statement is often called compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement.</em></p><ul><li><em>Block Statement</em></li></ul><pre>{<br>  <em>StatementList</em><br>}</pre><ul><li><em>Labeled Statement</em></li></ul><pre><em>LabelIdentifier</em>: {<br>  <em>StatementList</em><br>}</pre><blockquote>var x statement within the block is in the same scope as the var xstatement before the block</blockquote><pre>var x = 1;<br>{<br>  var x = 2;<br>}<br>console.log(x);  // 2</pre><h4><em>But, With </em><em>let OR const</em></h4><p><em>identifiers declared with </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><em>let</em></a><em> and </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><em>const</em></a><em> </em><strong><em>do have </em></strong><em>block scope</em></p><pre>let x = 1;<br>{<br>  let x = 2;<br>}<br>console.log(x); // 1</pre><p><em>outside block has no accessible for inner block, so in case we want to access y, we get a reference error</em></p><pre>{<br>  let y = 2;<br>}<br>console.log(y); // &quot;ReferenceError: y is not defined&quot;</pre><blockquote>Functions are the most common units of scope</blockquote><p><strong><em>IIFE ( Immediately Invoking Function Expression )</em></strong></p><p><em>It is a design pattern which is also known as a </em><a href="https://developer.mozilla.org/en-US/docs/Glossary/Self-Executing_Anonymous_Function"><em>Self-Executing Anonymous Function</em></a><em> and contains two major parts. The variable within the expression can not be accessed from outside it.</em></p><ul><li><em>First s the anonymous function with lexical scope enclosed within the (..func body..)</em></li><li><em>second () creates the immediately executing function expression</em></li></ul><pre>(function () { <br>    let msg = &quot;Message ...&quot;; <br>    console.log(msg);<br>})();  // &quot;Message ...&quot;</pre><pre>console.log(msg); // &quot;ReferenceError: msg is not defined&quot;</pre><blockquote>Javascript code interprets line by line, top-down in orders</blockquote><p><strong>Hoisting</strong></p><p><em>a general way of thinking about how execution contexts (specifically the creation and execution phases) work in JavaScript</em></p><pre>console.log(num); // Returns undefined <br>var num;<br>num = 6;</pre><p><em>Don’t think that the log will return reference error, don’t be confuse</em></p><p><em>try to explain :)</em></p><pre>var num = 7</pre><p><em>When JS code try to compile that little bit code , compiler see it in two pieces like so:</em></p><ul><li><em>var num =&gt; we call that </em><strong><em>declarations</em></strong><em> of variables or functions …etc</em></li><li><em>num = 7 =&gt; this is the assignment and we call it </em><strong><em>execution code</em></strong></li></ul><p><em>Declarations proceed first before any part of program code like execution code, so the above example returned undefined</em></p><p><em>think of scenario again</em></p><pre>console.log(num)   // this is an execution which run in order (2)<br>var num;          // this is a declaration which proceed first (1)<br>num = 6           // another execution which run in order (3)</pre><p><strong><em>Functions first</em></strong></p><p><em>both functions &amp; variables are hoisted, but if we have duplicated of function and variable, which will run in your opinion ?</em></p><p><em>the answer is that functions hoisted first, then variables</em></p><pre>foo(); // 1</pre><pre>foo = function() {<br> console.log( 2 );<br>};</pre><pre>function foo() {<br> console.log( 1 );<br>}</pre><p><em>even so foo variables coming first, but foo function is the result, which log 1</em></p><blockquote>Assignment of function expression is not hoisted</blockquote><p><strong><em>Scope Closure</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*f12rRf7S0nB0gamocPrUzw.png" /></figure><p>A <em>closure</em> is the combination of a function and the lexical environment within which that function was declared.</p><p>in other words The ability of function to access and run inner variables and functions, even when that function executing outside it’s lexical scope</p><pre>function makeFunc() {<br>  var name = &#39;Mozilla&#39;;<br>  function displayName() {<br>    alert(name);<br>  }<br>  return displayName;<br>}<br><br>var myFunc = <strong>makeFunc()</strong>; // Closure<br>myFunc();</pre><blockquote>Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow us to associate some data (the object’s properties) with one or more methods.</blockquote><p><strong><em>Loops and Closure</em></strong></p><pre>for (var i=1; i&lt;=5; i++) {  <br> setTimeout( function timer(){  <br>   console.log( i );  <br>  }, i*1000 ); <br>} // 6, 6, 6, 6, 6</pre><p><em>if you expect that result will be 1,2,3,4,5 Unfortunately completely wrong</em></p><p><em>but log will print for us 6 for 5 times</em></p><p><em>so what happens here ?</em></p><p><em>output here is reflecting the final value of loop, and that’s because of timeout callback runs after the completion of the code</em></p><p><em>so what we missed here ?</em></p><p><em>we need a new closure scope for each iteration of the loop, what about </em><strong><em>IIFE</em></strong></p><p><em>IIFE will help to create a new scope for each iteration</em></p><pre>for (var i=1; i&lt;=5; i++) {  <br> ((i) =&gt; {<br>   setTimeout( function timer(){  <br>   console.log( i );  <br>  }, i*1000 ); <br> })(i)<br>} // 1, 2, 3, 4, 5</pre><p><em>so the solution was to create a closure scope for each iteration, try with </em><strong><em>let</em></strong></p><pre>for (var i=1; i&lt;=5; i++) { <br>  let j = i<br> setTimeout( function timer(){  <br>   console.log( j );  <br>  }, i*1000 ); <br>} // 1, 2, 3, 4, 5</pre><blockquote><strong>let</strong> statement declares a block scope local variable, optionally initializing it to a value.</blockquote><blockquote>so also works with let or const :)</blockquote><p><strong><em>Dynamic Scope</em></strong></p><p><em>the referent is determined by looking up through the nested function calls that are active at the time the value is required.</em></p><p><em>in other words scope can determine dynamically at runtime, for example that’s is a Lexical scope that scope determine by write-time</em></p><pre>function foo(){<br>  console.log(a)<br>}</pre><pre>function bar(){<br>  var a = 3<br>  foo()<br>}</pre><pre>var a = 2<br>foo()     // 2</pre><p><em>So, if we try this example in dynamic scope, will log different result</em></p><pre>function foo(){<br>  console.log(a)<br>}</pre><pre>function bar(){<br>  var a = 3<br>  foo()<br>}</pre><pre>var a = 2<br>foo()     // 3</pre><blockquote>JS dose not have dynamic scopes, But lexical (Static).</blockquote><blockquote>Lexical scope is write time, where as dynamic scopes are run time.</blockquote><blockquote>Lexical scopes cares where function was declared.</blockquote><blockquote>Dynamic scopes cares where function was called from.</blockquote><p><strong><em>References:</em></strong></p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Hoisting">https://developer.mozilla.org/en-US/docs/Glossary/Hoisting</a></li><li><a href="https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures">https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures</a></li><li><a href="https://8thlight.com/blog/jarkyn-soltobaeva/2017/06/13/scope-and-closures-in-javascript.html">https://8thlight.com/blog/jarkyn-soltobaeva/2017/06/13/scope-and-closures-in-javascript.html</a></li><li><a href="https://codeburst.io/understanding-javascripts-engine-with-cartoons-3ef56487a987">https://codeburst.io/understanding-javascripts-engine-with-cartoons-3ef56487a987</a></li><li><a href="https://javascriptstore.com/2017/10/02/abstract-syntax-trees/">https://javascriptstore.com/2017/10/02/abstract-syntax-trees/</a></li></ul><blockquote><em>Finally, Hopefully that help</em></blockquote><blockquote><strong><em>Next</em></strong><em>: Immutable Data</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afbf816b71cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composition & Currying in JS]]></title>
            <link>https://medium.com/@mustafaskyer/composition-currying-in-js-76b0ca60f0a0?source=rss-6ec8da7ec721------2</link>
            <guid isPermaLink="false">https://medium.com/p/76b0ca60f0a0</guid>
            <category><![CDATA[recompose]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[currying]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[composition]]></category>
            <dc:creator><![CDATA[Mustafa Elsayed]]></dc:creator>
            <pubDate>Wed, 14 Nov 2018 11:47:33 GMT</pubDate>
            <atom:updated>2018-11-14T11:48:31.675Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Composition &amp; Currying in JS</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdrI5piyUFTj0sG77YbDMg.jpeg" /></figure><p><strong>One of the most two essential functional programming techniques are <em>composition</em> </strong>&amp; <strong><em>currying</em></strong></p><p><strong>what is currying ?</strong><br>is when you break down a function that takes multiple arguments into a series of functions, each function takes single argument</p><p>for example<br>we have function sum that makes the total of ( X, Y, Z )</p><pre>const sum = (x,y,z) =&gt; {</pre><pre>return x + y + z</pre><pre>}</pre><pre>console.log(sum(2,3,4)) // 9</pre><p>Curry It</p><pre>const currySum = x =&gt; y =&gt; z =&gt; {</pre><pre>return x + y + z</pre><pre>}</pre><pre>console.log(currySum(2)(3)(4)) // 9</pre><blockquote>The idea of currying is that a function of (n) arguments won’t actually realize its effect until it has all (n) arguments. The benefit of this is that you can pass some arguments (but not all) to a function</blockquote><p>e.g</p><pre>const sum = x =&gt; y =&gt; x + y</pre><pre>console.log(sum(5)(3)) // 8</pre><pre>const add5 = sum(5)</pre><pre>console.log(add5(3)) // 8</pre><blockquote>get easier reuse of more functions</blockquote><p>Last Scenario of Currying from <a href="https://ramdajs.com/docs/#curry">Ramda</a></p><pre>const addFourNumbers = (a, b, c, d) =&gt; a + b + c + d;</pre><pre>const curriedAddFourNumbers = <strong>R.curry</strong>(addFourNumbers);</pre><pre>const <strong>curryMoreTwoNums</strong> = curriedAddFourNumbers(1, 2);</pre><pre>const <strong>curryMoreOne</strong> = <strong>curryMoreTwoNums</strong>(3)</pre><pre>const <strong>curryLastOne</strong> = n =&gt; <strong>curryMoreOne</strong>(n)</pre><pre><strong>curryLastOne</strong>(4) // 10</pre><p><strong><em>Currying &amp; Partial Application</em></strong></p><p><strong>Currying</strong> is about turning into n of arguments to a sequence of functions each function take a single argument,</p><p><strong>Partial Application</strong> Calling a function with fewer arguments than it expects and It returns a function that takes the remaining arguments.</p><p>And this is called Partial Application of Functions.</p><p>e.g</p><pre>function askPassword(ok, fail) {<br>  let password = prompt(&quot;Password?&quot;, &#39;&#39;);<br>  if (password == &quot;rockstar&quot;) ok();<br>  else fail();<br>}</pre><pre>let user = {<br>  name: &#39;John&#39;,</pre><pre>login(result) {<br>    alert( this.name + (result ? &#39; logged in&#39; : &#39; failed to log in&#39;) );<br>  }<br>};</pre><pre>askPassword(?, ?); // ?</pre><p>More Focus in Partial Application I’d recommend this article for <a href="https://medium.com/u/923b9579a727">Functional Reactive Ninja</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YF_FQkwwDxKO5fsULrgzqQ.jpeg" /></figure><h3>Composition</h3><p>Is a mechanism of combining multiple simple functions, to build a more complicated one, the result of each function passed to the next one &amp; so on</p><p>for example<br>say we have a simple mathematical equation like so ((1+1) * 5) / 2</p><pre>// ((1+1) * 5) / 2<br>const sum = (a, b) =&gt; a + b<br>const multi = (a, b) =&gt; a * b<br>const div = (a, b) =&gt; a/b</pre><pre>console.log(div(multi(sum(1,1),5),2)) // <strong>5</strong></pre><blockquote>so, simply take the output of function &amp; pass it as an argument to the next one &amp; so on.</blockquote><p><strong>More with composition,</strong><br>we have a bunch of data with names &amp; ages .</p><pre>const people = [<br>    { name:&#39;A&#39;, age:22,  },<br>    { name:&#39;B&#39;, age:19,  },<br>    { name:&#39;C&#39;, age:11,  },<br>]<br>const getObjGt15 = object =&gt; R.filter(obj =&gt; obj.age &gt; 15 , people)<br>const getName = arr =&gt; R.map(obj =&gt; obj.name, arr)<br>const getAge = obj =&gt; obj.age<br>console.log(<br><strong>R.compose</strong>(getName, getObjGt15)(people)  <strong>// [&quot;A&quot;, &quot;B&quot;]</strong><br>)</pre><p><a href="https://github.com/acdlite/recompose"><strong>Recompose</strong></a> is a React utility belt for function components and higher-order components. Think of it like lodash for React.</p><p>Simple Example of compose form recompose</p><pre>import { <br>   pure, <br>   branch, <br>   withProps, <br>   compose, <br>   renderComponent<br> } from &#39;recompose&#39;;<br></pre><pre>const Header = ({title, onPress}) =&gt; <br>              &lt;View title={title} onPress={onPress} /&gt;</pre><pre>const InnerHeader = ({title, onPress, style }) =&gt; <br>              &lt;View title={title} onPress={onPress} style={style} /&gt;</pre><pre>export default <strong>compose</strong>(</pre><pre>pure,</pre><pre>withProps(props =&gt; ({...props})),</pre><pre>branch( props =&gt; props.hasDetails,renderComponent(InnerHeader)),</pre><pre>)<strong>(Header)</strong></pre><p><strong>Compose &amp; Pipe</strong></p><p><strong>A pipe</strong> is a form of redirection that is used in Linux and other Unix-like operating systems to send the output of one program to another program for further processing .</p><p>For me, <strong>Pipe</strong> is the same as <strong>composing</strong>, but compose has much more to do than the pipe</p><p>Why Compose Over Pipe? Think this will help</p><p><a href="https://github.com/ramda/ramda/issues/1642">Why prefer compose over pipe? · Issue #1642 · ramda/ramda</a></p><blockquote>pipe example</blockquote><pre>const _pipeee = (...fncs) =&gt; x =&gt; fncs.reduce((y,f) =&gt; f(y), x)</pre><pre>const people = [ <br> { name:&#39;Mustafa&#39;, age:11 }, <br> { name:&#39;Ahmed&#39;, age:12 }, <br> { name:&#39;Medo&#39;, age:13 }, <br> { name:&#39;Zaki&#39;, age:14 },<br> ]</pre><pre>const printResult = res =&gt; console.log(res)<br>const join = x =&gt; x.join(&quot; &quot;)<br>const split = x =&gt; x.split()<br>const names = arr =&gt; arr.map(o =&gt; o.name)<br>const ages = (arr,name) =&gt; arr.find(o =&gt; o.name === name)<br>const getAge = arr =&gt; arr.map(o =&gt; o.age)<br>const withName = o =&gt; `${o}`<br>const onlyAges = arr =&gt; getAge(arr[0].split(&quot;,&quot;).map(ob =&gt; ages(people, ob)))</pre><pre>_pipeee(<br>  names,<br>  withName,     // only get names<br>  split,<br>  onlyAges,    <br>  printResult  // only get ages<br>)(people) // [11, 12, 13, 14]</pre><p>Hope so that makes sense :)</p><p><strong>References</strong></p><ul><li><a href="https://javascript.info/currying-partials">https://javascript.info/currying-partials</a></li><li><a href="http://www.drdobbs.com/open-source/currying-and-partial-functions-in-javasc/231001821">http://www.drdobbs.com/open-source/currying-and-partial-functions-in-javasc/231001821</a></li><li><a href="https://medium.com/@JosephJnk/partial-function-application-in-javascript-and-flow-7f3ca87074fe">https://medium.com/@JosephJnk/partial-function-application-in-javascript-and-flow-7f3ca87074fe</a></li></ul><p><strong>Where we go Next</strong></p><p>Closures &amp; Scopes :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76b0ca60f0a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>