<?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 Zied Hamdi - https://github.com/ziedHamdi on Medium]]></title>
        <description><![CDATA[Stories by Zied Hamdi - https://github.com/ziedHamdi on Medium]]></description>
        <link>https://medium.com/@zhamdi?source=rss-deb121b7e0d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*n9yK64dr3FMoAYv7L9s6qw.jpeg</url>
            <title>Stories by Zied Hamdi - https://github.com/ziedHamdi on Medium</title>
            <link>https://medium.com/@zhamdi?source=rss-deb121b7e0d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:51:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zhamdi/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[From 3 to 365 Days: How to turn a forum exhibition into an automated lead engine]]></title>
            <link>https://medium.com/@zhamdi/from-3-to-365-days-how-to-turn-a-forum-exhibition-into-an-automated-lead-engine-c41441f7a1a1?source=rss-deb121b7e0d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c41441f7a1a1</guid>
            <category><![CDATA[supply-chain]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[b2b-marketing]]></category>
            <category><![CDATA[transportation]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Zied Hamdi - https://github.com/ziedHamdi]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 15:31:38 GMT</pubDate>
            <atom:updated>2026-06-04T15:31:38.329Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Every year, millions of CZK move through the European railway supply chain. Companies heading to regional trade shows like Rail Business Days 2026 in Ostrava invest heavily in physical booths, rolling stock transport, and executive personnel to capture new contracts.</blockquote><blockquote>It is an excellent way to secure branding, prestige, and face-to-face trust. However, there is a massive opportunity to compound that physical investment. With the right strategy, the digital leverage companies get out of these expensive physical events can be multiplied exponentially — turning a three-day exhibition into a year-round lead engine.</blockquote><blockquote>By shifting from a purely physical presence to a structured, semantic data model, B2B companies can significantly maximize their sales network, expand their visibility, and capture a rapidly growing procurement market: Autonomous AI Sourcing.</blockquote><blockquote>Here are three practical ways to scale your event ROI and ensure your technology stays discoverable long after the venue doors close.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbteyOFoW0uNv6iMkO9SHA.jpeg" /></figure><h3>1. Upgrade from Flat Indexes to Deep-Tech Discovery</h3><p>When an event directory lists your brand name and a corporate logo, it works perfectly for buyers who already know exactly who you are. But the real growth happens when you capture the buyers who are searching strictly by specialization, capability, and compliance.</p><p>Imagine an engineer or procurement manager walking into an exhibition looking for a highly specific solution — such as an integration partner to navigate the sweeping new NIS2 cybersecurity directive for rolling stock. Currently, their primary tools are a flat, alphabetical index of corporate names or a locked, unindexed PDF floor map.</p><p>By upgrading your profile data from a simple company name to a rich, keyword-optimized description of your actual technical parameters, you drastically reduce the friction for new buyers. When your services and direct sales contacts are mapped to specific technical categories, you instantly turn casual foot traffic into targeted, high-intent B2B consultations.</p><h3>2. Capture “Virtual Leverage” to Expand Your Network</h3><p>Some of the most aggressive networkers at any major event don’t actually occupy a physical square meter on the floor. These are the agile sales reps, technical experts, and founders who travel to the forum with a laptop and a calendar packed with back-to-back café meetings.</p><p>These mobile experts possess incredible networking speed, but their presence has always been ephemeral. The moment they finish a 10-minute coffee meeting, they disappear from the event ecosystem.</p><p>By introducing a structured digital anchor for these mobile teams, they can sit directly alongside physical exhibitors as Virtual Exhibitors. This allows them to list their product decks, core technical focus areas, and direct LinkedIn links in the central digital showroom for an entire year.</p><p>This gives lean tech providers a permanent, visible anchor to capture regional event traffic all year round, compounding their networking results without the massive capital expenditure of physical booth construction.</p><h3>3. Position Your Business for the Autonomous Procurement Loop</h3><p>The largest untapped growth lever for modern B2B marketing isn’t human — it’s algorithmic. Enterprise procurement teams are rapidly establishing a permanent habit: <strong>delegating complex vendor research entirely to autonomous AI agents.</strong></p><p>The modern procurement process has shifted:</p><ol><li>A corporate user prompts an AI agent: <em>“Find and compare all European suppliers at Rail Business Days specializing in NIS2-compliant onboard routers.”</em></li><li>The AI agent independently crawls the web, extracts semantic context, and outputs a structured table of three options.</li><li>The employee copies that table directly into a presentation deck for executive review.</li></ol><p>This introduces <strong>The Manager’s Dilemma</strong> to the enterprise world.</p><p>As a manager, you cannot micro-manage how your employees source information; you have always relied on their final recommendations. If an employee shows you the vetted sources an AI provided, you accept it as due diligence. You will never know that a superior, unindexed competitor was completely left out of the selection loop simply because an AI crawler couldn’t find them.</p><p>If your technical parameters, compliance certifications, and specific services are locked inside a flat PDF map or a generic brand name list, <strong>you do not exist to the AI.</strong></p><blockquote>This shift is already getting deployed at the corporate level. With my company, <a href="https://berberinna.cc/"><strong>Berberinna</strong></a>, we are collaborating with <strong>Heaton</strong>, a highly regulated pharmaceutical enterprise in a pilot program architecting and deploying a highly secure corporate AI Swarm solution.</blockquote><h3>My prposed solution: Indexpo</h3><p>To bridge this data discovery gap for the Ostrava event, I scraped the raw exhibitor metadata and built a searchable digital showroom called <a href="https://indexpo.eu/"><strong>Indexpo</strong></a>.</p><p>The response was immediate: the concept racked up over <strong>10,000 views</strong> in its first day, after a few posts on reddit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbi2vDOhPfeH0OTLd4yqqg.png" /></figure><p>Marketers and SEO specialists are aware of the value of transforming a temporary physical exhibition into a permanent, searchable semantic web. Not only does it allow human visitors to prepare their visit by identifying the exhibitors they should not miss upfront. But these details persist on the web, making the algorythms “understand” what each company does, and how much it is present on the physical market.</p><p>Once this basis has been achieved, I started thinking about the “mobile experts”. These are not even mentioned on the exhibition official website <em>“they don’t even exist in the virtual world”</em>. On <a href="https://indexpo.eu/">indexpo</a>, they sit directly alongside official physical exhibitors as <strong>Virtual Exhibitors</strong>. This ensures their digital decks, core technical focus areas, and LinkedIn links remain discoverable for coffee meetings during the event, and for SEO/AIO all the time.</p><p>To maintain a premium, highly curated ecosystem, we’ve structured the virtual layout on a rolling tier model:</p><ul><li><strong>The first 20 companies</strong> can claim their virtual seat completely <strong>Free</strong>.</li><li><strong>Companies 21 through 50</strong> lock in their year-round digital footprint for <strong>4,990 Kč/year</strong>.</li><li><strong>Entries 51+</strong> (and those who claim a profile after the event started) secure their permanent archive spot for <strong>6,990 Kč/year</strong>.</li></ul><h3>Turning Temporary Events into Cumulative Assets</h3><p>The fundamental flaw of the traditional trade show model is that it treats data as ephemeral. The doors close, the booths are torn down, and next year, everyone starts from scratch.</p><p>By reorganizing how event data is indexed, we ensure that high-quality contextual backlinks pointing to an exhibitor’s site provide immense traditional SEO value, while organizing the data in a way that modern AI agents can easily digest and recommend to human managers.</p><p>The physical doors in Ostrava open and close in a matter of days, but your digital footprint should be permanent.</p><p><em>Explore the platform, search by technical niche, or secure your Virtual Exhibitor seat today at </em><a href="https://indexpo.eu/"><em>Indexpo.eu</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c41441f7a1a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fail-Fast Strategy for Enterprise Releases]]></title>
            <link>https://medium.com/@zhamdi/fail-fast-strategy-for-enterprise-releases-1f0afd8c72e3?source=rss-deb121b7e0d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f0afd8c72e3</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Zied Hamdi - https://github.com/ziedHamdi]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 20:52:10 GMT</pubDate>
            <atom:updated>2026-04-23T20:52:10.657Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YM-E4Elw2-1kKKDy1KEbLw.jpeg" /><figcaption><em>Photo by </em><a href="https://unsplash.com/@kolamdigital?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em>Andy Hermawan</em></a><em> on </em><a href="https://unsplash.com/photos/a-red-and-white-toy-rocket-on-a-blue-background-bVBvv5xlX3g?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em>Unsplash</em></a></figcaption></figure><blockquote><strong><em>Pro Tip:</em></strong><em> You can easily extend this article’s logic to other security checks. Like ensuring source maps are stripped from production deliverables. 🤪<br>If you think I am targeting a specific AI company here, I honestly don’t have any </em><strong><em>claw</em></strong><em> about what’s on your mind. 😁</em></blockquote><p>If you work in a modern software development company, you probably noticed a wall between “Devs” and “DevOps.” For a client I will not mention for obvious reasons, there was a strong “not my job” paradigm that made <strong>Release Versioning</strong> a “burning potato” everyone was passing to the other.</p><p>Additionally, the actual incrementing of version numbers, tagging, and branching is often delegated to a DevOps pipeline — a black box of huge YAML files and obscure bash scripts that went against everything we learned from the development world: “testing is king.” Frequent back-and-forth discussions to decide if a change was a major, minor, or fix iteration were common, slowing us down from achieving our weekly delivery goals.</p><p>To sum it up, developers have every reason to take this “heavy lifting” onto themselves, occupying a strategic position between Dev and DevOps: a <strong>“DevDevOps.”</strong> What if our release pipelines were testable, mockable Infrastructure-as-Code written in the language the developers already know?</p><p>In this article, I show you how to build a testable, fully automatic release architecture that uses package.json as the trigger and single source of truth for creating deliverables, tagging git versions, and committing changes to a version branch.</p><blockquote><em>You can find a template project to start from on the </em><a href="https://github.com/ziedHamdi/versioning-as-code"><em>versioning-as-code github repository</em></a></blockquote><h3>1. The YAML Gray Box</h3><p>My initial attempt at automating version bumps looked like most enterprise setups: a complex GitHub Action. We embedded shell commands directly into the YAML to read the last commit, parse the package.json, compare it to the current commit, and execute Git tags if they differed.</p><pre># The &quot;Push and Pray&quot; Anti-Pattern<br>run: |<br>  NEW_VERSION=$(node -p &quot;require(&#39;./package.json&#39;).version&quot;)<br>  OLD_VERSION=$(git show HEAD~1:package.json | node -p &quot;JSON.parse(require(&#39;fs&#39;).readFileSync(0, &#39;utf8&#39;)).version&quot;)<br>  # ... 20 more lines of non-code code</pre><p><strong>The Problem:</strong> Yaml is a patched code, it is not a development langaguage: you cannot unit test a shell pipe inside a YAML file. Testing required committing, pushing to a remote branch, waiting 10 minutes for a runner, which translated to 20, because you grabbed a coffee and found collegues next to the machine. It was brittle, focus-dissipating, untestable, and completely opaque to the development team (not my job).</p><h3>2. The Way: Testable Infrastructure-as-Code</h3><p>I realized that “logic shouldn’t live in YAML.” Extracting the entire versioning logic into clean, isolated <strong>TypeScript</strong> files (check-version.ts and tag-and-branch.ts) transformed it into regular code that we can test in a few milliseconds. This allowed us to iterate quickly and add constraints, such as verifying the version string format or preventing commits if the format failed a Regex test.</p><h3>Testable and Mockable: Reliable</h3><p>To make the code testable without triggering actual file system reads or Git commands, I wrapped the native interactions in an exported versionHelpers object:</p><pre>// scripts/release/check-version.ts<br>import { execSync } from &#39;child_process&#39;;<br>import fs from &#39;fs&#39;;<br><br>const SEMVER_REGEX = /^\d+\.\d+\.\d+$/;<br><br>export const versionHelpers = {<br>    getCurrentVersion: () =&gt; JSON.parse(fs.readFileSync(&#39;./package.json&#39;, &#39;utf8&#39;)).version,<br>    getPreviousVersion: () =&gt; JSON.parse(execSync(&#39;git show HEAD~1:package.json&#39;, { encoding: &#39;utf8&#39; })).version<br>};<br><br>export function checkVersion() {<br>    const newV = versionHelpers.getCurrentVersion();<br>    const oldV = versionHelpers.getPreviousVersion();<br><br>    // Logic: Catch &quot;Negative Bumps&quot; and bad formatting<br>    const comparison = compareSemver(newV, oldV);<br><br>    if (comparison === 1) { // New is greater<br>        return { bumped: true, version: newV };<br>    }<br>    return { bumped: false };<br>}</pre><p>By structuring it this way, we immediately gained the ability to write regular unit tests using our usual stack (Vitest). We could mock the “Git history” and assert that the script correctly parsed versions without ever touching a real repository (do the math for creating a fake repository to test yml files):</p><pre>// scripts/release/check-version.test.ts<br>import { describe, it, expect, vi } from &#39;vitest&#39;;<br>import { checkVersion, versionHelpers } from &#39;./check-version&#39;;<br><br>describe(&#39;Release Logic&#39;, () =&gt; {<br>    it(&#39;detects a version bump correctly&#39;, () =&gt; {<br>        // Safe, targeted mocks of internal methods<br>        vi.spyOn(versionHelpers, &#39;getCurrentVersion&#39;).mockReturnValue(&#39;1.1.0&#39;);<br>        vi.spyOn(versionHelpers, &#39;getPreviousVersion&#39;).mockReturnValue(&#39;1.0.0&#39;);<br><br>        const result = checkVersion();<br><br>        expect(result.bumped).toBe(true);<br>        expect(result.version).toBe(&#39;1.1.0&#39;);<br>    });<br>});</pre><p>With the logic rigorously unit-tested locally, our DevOps YAML file is reduced to its absolute minimum — a few lines of orchestration that just trigger our tested <strong>programs</strong>:</p><pre># .github/workflows/tag-on-bump.yml<br>jobs:<br>  tag-and-branch:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>        with: { fetch-depth: 2 }<br>      - name: Check version bump<br>        id: check<br>        run: npx tsx scripts/release/check-version.ts<br>      - name: Tag and Branch<br>        if: steps.check.outputs.bumped == &#39;true&#39;<br>        run: npx tsx scripts/release/tag-and-branch.ts --run \<br>          --version &quot;${{ steps.check.outputs.version }}&quot; \<br>          --majorMinor &quot;${{ steps.check.outputs.major_minor }}&quot;</pre><h3>Semantic Safety Pre-checks: Defense in Depth</h3><p>Because we are using TypeScript, we can easily go beyond simple string comparison. We implemented a <strong>Semantic Comparison</strong> logic that detects and forbids “Negative Version Bumps” (downgrades).</p><p>But a check is only as good as its enforcement. We use a <strong>“Defense in Depth”</strong> strategy:</p><ol><li><strong>The Edge (Local Git Hook)</strong>: We use a Git <strong>pre-push</strong> hook. This is a built-in Git mechanic that triggers a script on the developer&#39;s machine <em>before</em> the push happens. If the developer tries to push a negative bump, the script fails locally, and Git literally blocks the push. The &quot;Safety Valve&quot; is at the developer&#39;s fingertips.</li><li><strong>The Auditor (GitHub Actions)</strong>: Even if a developer bypasses the hook (using --no-verify), the GitHub Action runs the exact same script on the server. If it fails there, the release pipeline (tagging and branching) is aborted, and the sabotage is logged.</li><li>As mentioned in the intro, you can add source map file removal here… if you care 😁</li></ol><p>By combining these two distinct tools — <strong>Local Git Hooks</strong> for immediate developer feedback and <strong>GitHub Actions</strong> as a final safety audit — we obtain a fully safe, “fail-early” system where the versioning logic is managed entirely as code.</p><h3>What the Hook looks like</h3><p>The beauty of this system is its simplicity. Here is a snippet of our .git/hooks/pre-push script:</p><pre>#!/bin/bash<br># .git/hooks/pre-push<br><br>echo &quot;🔍 Running pre-push validation...&quot;<br><br># 1. Ensure the code is stable<br>npm run test:run<br><br>if [ $? -ne 0 ]; then<br>  echo &quot;❌ Local tests failed! Push aborted.&quot;<br>  exit 1<br>fi<br><br># 2. Run the &quot;Versioning as Code&quot; validation logic<br>npx tsx scripts/release/check-version.ts<br><br>if [ $? -ne 0 ]; then<br>  echo &quot;❌ Version validation failed! Push aborted.&quot;<br>  exit 1<br>fi<br><br>echo &quot;✅ All checks passed. Proceeding with push.&quot;<br>exit 0</pre><h3>4. Enforcing the Culture: The Onboarding</h3><p>A technical hurdle is only solved if it’s adopted. To ensure every developer “sticks to the plan”. We provide a simple scripts/setup-hooks.sh that automates the installation of the local safety valves.</p><p>We then link this directly in our <a href="https://../welcome-developer.md">docs/welcome-developer.md</a> guide. Newcomers are greeted with a clear &quot;Run this immediately&quot; instruction. By making the setup part of the onboarding ritual, we ensure the &quot;Defense in Depth&quot; isn&#39;t just an architect&#39;s dream, but a shared reality for the whole team.</p><p>By combining the local hook with the github actions, we ensure that the Git history remains a pristine, 1-to-1 mirror of our delivery history.</p><h3>3. Bonus Brick: Frictionless Local Delivery</h3><p>Because we shifted the “historian” duties (tagging and branching) to the cloud based entirely on Git pushes, we unlocked a massive secondary benefit: <strong>Frictionless Offline Builds.</strong></p><p>For consultants or teams working with air-gapped enterprise clients, you often need to deliver heavy Docker images via physical media (like a USB stick). Because your local package.json is already validated and bumped, you don&#39;t have to wait for the cloud CI to build a GB Docker artifact just so you can download it.</p><p>You simply push your bump (to let the cloud do the tagging), and immediately run a local ./bundle.sh script that builds your Docker image, validates it via multi-stage testing, and ZIPs it up for handover. (since you already check the health locally at git push)</p><h3>The Edge Cases (What’s Next?)</h3><p>While this system gives developers immense control and guarantees a consistent Git history, it does not currently orchestrate <strong>remote merge conflicts</strong> on the release branch.</p><p>If two developers simultaneously push a version bump (e.g., both bump to 1.1.2) to the same release branch, the last push will be rejected by Git. Currently, this requires standard Git hygiene: the second developer must run a local git pull --rebase to resolve the conflict before pushing.</p><h3>Conclusion</h3><p>By treating our release pipeline as actual, testable software, we removed the friction of version bumping. Developers manage the version in the file they stare at every day (package.json), and the infrastructure dutifully, safely, and predictably documents that history in Git. That is versioning like a pro.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f0afd8c72e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rethinking ReBAC: From Accidental Discovery to Zero-Latency Reads]]></title>
            <link>https://medium.com/@zhamdi/rethinking-rebac-from-accidental-discovery-to-zero-latency-reads-7277706a760f?source=rss-deb121b7e0d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7277706a760f</guid>
            <category><![CDATA[rebac]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[zanzibar]]></category>
            <category><![CDATA[oidc]]></category>
            <dc:creator><![CDATA[Zied Hamdi - https://github.com/ziedHamdi]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 01:50:03 GMT</pubDate>
            <atom:updated>2026-04-12T01:50:03.789Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://dev.to/t/rebac">#rebac</a> <a href="https://dev.to/t/architecture">#architecture</a> <a href="https://dev.to/t/zanzibar">#zanzibar</a> <a href="https://dev.to/t/oidc">#oidc</a></p><blockquote><strong><em>I needed to solve a common hierarchical permission problem on my project… and unknowingly arrived at ideas that extend Google’s Zanzibar paper.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*z8rQsdNJiIhwRZj7.jpg" /></figure><blockquote><em>Photo by </em><a href="https://unsplash.com/@notethanun?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em>note thanun</em></a><em> on </em><a href="https://unsplash.com/photos/rows-of-colorful-lanterns-in-red-yellow-blue-and-pink-IiCujDqXxSw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em>Unsplash</em></a></blockquote><p>I was building a mechanism for “setting-spreading”. If a parent company upgraded to a premium tier (enabled a specific feature module), or added a user as a manager of some data, that setting needed to automatically cascade down to specific subsidiaries, team members, and/or related entities based on dynamic rules.</p><p>Starting with a single case, the idea was seductive so I extended it to more complex scenarios, before I decided to isolate it as a stand alone solution. Once there, I did my duty of researching whether the problem I was tackling was already solved and open sourced. Surprisingly, it was not so democratized, but it already had a name: ReBAC (Relationship-Based Access Control), formalized by Google’s Zanzibar paper.</p><p>But as I explored Zanzibar and its modern SaaS implementations (like SpiceDB or Auth0 FGA), I realized a critical bottleneck: <strong>Latency</strong>.</p><blockquote><strong><em>Here’s what I’ll cover: the latency problem with standard ReBAC, how AOT materialization solves it, the three abstraction layers that make this engine reusable, and the governance benefits that emerged unexpectedly.</em></strong></blockquote><h3>The Zanzibar Latency Paradigm</h3><p>Google Zanzibar is a phenomenally robust distributed system designed to compute permissions in real-time. It operates as a centralized authorization engine. (Analogy: OIDC scopes and claims, but resolved live across interrelated services)</p><p>The standard approach for modern ReBAC environments is to operate as centralized microservices relying on Just-In-Time (JIT) graph traversal. When a user requests access to a resource, the engine calculates the permissions over the network.</p><p>This is elegant on paper and adopts a nice microservice SaaS architecture, but in the real world, it becomes a bottleneck:</p><ol><li><strong>Network Hops</strong>: Every isAuthorized check requires a remote network call.</li><li><strong>Read-Time Overhead</strong>: As relationship depth increases, computing the graph at read-time causes latency spikes.</li></ol><p>If your platform needs sub-millisecond read responses, taking a network hit on every single API check quickly becomes a difficult-to-resolve issue without abandoning the architecture.</p><h3>The Pivot: Spread at Write, Optimize Read</h3><p>My approach was iterative — I started denormalizing from the first version. The result is a highly flexible <strong>Ahead-Of-Time (AOT) Materialized Engine</strong>.</p><p>If a user’s rights are inherited by their relationships in the hierarchy, we materialize those rights only once: the moment the relationship changes, not each time he wants to access data.</p><h3>How it Works</h3><p>Our Materialized ReBAC engine acts as a background hydration pipeline:</p><ol><li><strong>The Graph Traverser</strong>: When a trigger occurs (e.g., adding an Owner to a Holding Company, or activating a paid module), the engine consults declarative SpreadingConfig rules. It uses a GraphNavigator to traverse the Holding-Subsidiaries database relationships. Through a unified interface, implemented in concrete project-specific code, which is easier to test and debug.</li><li><strong>Hydration Jobs</strong>: It traverses downstream (or upstream) and injects the resulting permissions or modules directly into the target entities’ database records (granting the user inline permissions or activating the paid feature locally).</li><li><strong>Constant-Time Reads</strong>: Because the permissions are materialized on the target node, authorization at the API level requires zero mathematical computation or graph traversal. It is a simple object check: entity.modules.includes(&#39;ANALYTICS&#39;) or user.roles.includes(&#39;OWNER&#39;).</li></ol><p>The read latency dropped from network-dependent dozen milliseconds per call (because of network latencies) to absolute zero algorithmic overhead, as it resolves to a db-read that usually is executed along with other data querying in the same network request.</p><h4>Three Abstraction Axes for Project-Agnostic Design</h4><p><strong>1. Graph Navigation Abstraction</strong></p><p>The engine never hardcodes “how to find neighbors.” It consumes an injected GraphNavigator interface that yields adjacent nodes. The engine knows <em>that</em> traversal happens, not <em>how</em>—whether across PostgreSQL, GraphQL, or REST endpoints.</p><p><strong>2. Policy Decision Abstraction</strong></p><p>The engine delegates all condition evaluations to registered ConditionHandler plugins. Instead of parsing rigid rule strings, it passes typed entities to project-specific code that answers &quot;yes/no&quot; based on business logic (subscription tiers, payment status, etc.).</p><p><strong>3. Action Execution Abstraction</strong></p><p>The engine uses the Command Pattern for state mutation. It receives an Action payload and blindly calls .execute(). The engine doesn&#39;t know if it&#39;s granting a role, activating a module, or firing a webhook—it just runs the command.</p><h4>Testing Advantage: Layered Confidence</h4><p><strong>Unit tests on the engine itself</strong> verify the <em>mechanics</em>: cycle detection, depth limits, queue ordering, FILO rollback logic, and correlation ID tracking. These run in milliseconds with zero infrastructure — pure Go/Rust/TypeScript logic.</p><p><strong>Project-specific plugin tests</strong> verify the <em>integration</em>: that your CompanyGraphNavigator correctly queries subsidiaries, that your SubscriptionConditionHandler properly evaluates tier levels, and that your RoleMaterializer writes to the correct database tables.</p><p><strong>Beyond reusability, the critical advantage of this design is isolation</strong>. Because the engine depends only on interfaces, you can test:</p><ul><li>Engine behavior with mock plugins (fast, deterministic, exhaustive)</li><li>Plugin behavior against real databases using project-specific classes and methods. This removes abstraction layers and eases code reading — no unnecessary mental indirection.</li></ul><h3>Beyond Speed: Some Nice Side Effects</h3><p>But beyond speed, some nice side effects showed up: <strong>governance</strong>.</p><p>Because we materialize permissions through an event-driven queue, we can safely emulate (dry-run) outcomes before applying them. This allows for governance patterns that are traditionally difficult to achieve in JIT engines:</p><ul><li><strong>Terraform-Style Dry Runs &amp; Pending Changes:</strong> By treating permissions as a queue of upcoming events, we can simulate massive cascades and stage “Pending Changes” before they are committed (navigating the tree again to activaite nodes on payment success).</li><li><strong>The “Human in the Middle”:</strong> An administrator can review the simulated propagation tree and explicitly lock specific entities or deactivate spreading on specific modules <em>before</em> executing the materialization. It turns authorization into a clear <strong>Permission Staging</strong> pipeline that can be submitted for review before getting materialized.</li><li><strong>Atomic Correlation &amp; Rollbacks:</strong> Every wave of spreading is tied to a correlationId. If an upstream change is undone (or a human makes a mistake), the engine can perfectly roll back the entire materialized state across the tree. Repeatedly in a FILO (first in, last out) manner.</li><li><strong>Decision Transparency:</strong> Every time the engine <em>refuses</em> to spread a module down a valid path (due to failing a conditional check), it records the detailed structural reasoning in a unified AuditLog for better understanding of the reasons of refusal.</li><li><strong>Cycle &amp; Depth Safety:</strong> To prevent infinite loops, the queue maintains a strict pathHistory for cycle detection and enforces per-operation-type configuration-specific depth limits to stop cascade exhaustion.</li></ul><p>Solving for these edge cases effectively blurred the line between a basic Policy Engine and a full-fledged Identity Governance Administration (IGA) system.</p><h3>Conclusion</h3><p>Zanzibar definitively proved that static roles are dead and relationships are the future of access control.</p><p>But adopting ReBAC doesn’t mean you have to surrender your application to the latency of external API computations. By embracing AOT Materialization, it is possible to build a generic, extensible engine that guarantees the dynamic power of relationship-based access with the uncompromising speed of local read queries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7277706a760f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running AirLLM Locally on Apple Silicon: Not So Good]]></title>
            <link>https://medium.com/@zhamdi/running-airllm-locally-on-apple-silicon-not-so-good-2b48d41cdb7c?source=rss-deb121b7e0d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b48d41cdb7c</guid>
            <category><![CDATA[mlx]]></category>
            <category><![CDATA[apple-silicon]]></category>
            <category><![CDATA[airllm]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Zied Hamdi - https://github.com/ziedHamdi]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 14:45:27 GMT</pubDate>
            <atom:updated>2026-01-28T14:45:27.134Z</atom:updated>
            <content:encoded><![CDATA[<p>This week, armed with an article on huggingface talking about <a href="https://huggingface.co/blog/lyogavin/airllm">how AirLLM can run 70b models on 4GB of GPU</a>, I thought. my M4 MacBook Pro (48GB RAM) could run a local coding assistant. Especially that Kilo Code discontinued the free xGrog AI, the timing was as falling from the sky.</p><h3>The Goal</h3><p>Create a local xGrog replacement after xGrog became paid on Kilo code. I wanted to run models like:</p><ul><li>CodeLlama 13B/70B</li><li>DeepSeek-OCR models</li><li>Llama 3.1 variants</li></ul><blockquote><em>Funny fact: I didn’t have to type all the commands and python files by hand, just asking deepseek to do it for me. And giving directions on failures.</em></blockquote><h3>What Actually Worked</h3><h3>✅ Success: AirLLM with Mistral 7B</h3><p>Using AirLLM’s MLX backend, I successfully ran Mistral 7B without quantization. The key was proper PyTorch-to-MLX tensor conversion:</p><pre># First, upgrade pip<br>pip install --upgrade pip<br># run python in virtualized env<br>python -m venv venv  <br>source venv/bin/activate <br># Install airllm<br>pip install airllm<br># Install PyTorch for Mac (MPS support)<br>pip install torch torchvision torchaudio<br># Optional: for better performance<br>pip install accelerate<br># had to add these (compared to official docs)<br>pip install mlx-lm <br>pip install transformers<br>pip install safetensors</pre><pre># airllm_working_mac.py<br>from airllm import AutoModel<br>import mlx.core as mxprint(&quot;🚀 AirLLM on Apple Silicon - Working Version&quot;)<br>print(&quot;=&quot;*60)<br># Load model<br>model = AutoModel.from_pretrained(&quot;mistralai/Mistral-7B-Instruct-v0.1&quot;)<br>print(&quot;✅ Model loaded successfully&quot;)<br><br>def generate_response(prompt, max_tokens=100):<br>    &quot;&quot;&quot;Generate a response using AirLLM on Mac&quot;&quot;&quot;<br># Tokenize<br>    input_tokens = model.tokenizer(<br>        [prompt],<br>        return_tensors=&quot;pt&quot;,<br>        return_attention_mask=False,<br>        truncation=True,<br>        max_length=512,<br>        padding=False<br>    )<br>    # Convert PyTorch → NumPy → MLX<br>    pt_tensor = input_tokens[&#39;input_ids&#39;]<br>    numpy_array = pt_tensor.cpu().numpy()<br>    mlx_array = mx.array(numpy_array, dtype=mx.int32)<br>    print(f&quot;📝 Input length: {mlx_array.shape[1]} tokens&quot;)<br>    # Generate - returns STRING directly<br>    response = model.generate(<br>        mlx_array,<br>        max_new_tokens=max_tokens,<br>        use_cache=True,<br>        temperature=0.7<br>    )<br>    # Clean up the response (remove extra end tokens)<br>    cleaned_response = response.replace(&#39;&lt;/s&gt;&#39;, &#39;&#39;).strip()<br>    return cleaned_response<br># Test it<br>test_prompts = [<br>    &quot;What is the capital of France?&quot;,<br>    &quot;Write a Python function to calculate factorial&quot;,<br>    &quot;Explain quantum computing in simple terms&quot;<br>]<br>for i, prompt in enumerate(test_prompts):<br>    print(f&quot;\n{&#39;=&#39;*60}&quot;)<br>    print(f&quot;TEST {i+1}: {prompt}&quot;)<br>    print(f&quot;{&#39;=&#39;*60}&quot;)<br>    response = generate_response(prompt, max_tokens=50)<br>    print(f&quot;🤖 Response:\n{response}&quot;)<br>    # Save to file<br>    with open(f&quot;response_{i+1}.txt&quot;, &quot;w&quot;) as f:<br>        f.write(f&quot;Prompt: {prompt}\n\nResponse: {response}&quot;)<br>print(f&quot;\n{&#39;=&#39;*60}&quot;)<br>print(&quot;✅ All tests completed! Responses saved to response_*.txt&quot;)<br>print(f&quot;{&#39;=&#39;*60}&quot;)</pre><p><strong>Performance</strong>: Every question took ~10 minutes, subsequent runs were not faster. I could have expected that, as the very principle of AirLLM is to clear context between the different layers. But somehow I expected easier prompts to auto-adjust the number of needed layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*yUvPglpaJM4vCJiE.png" /></figure><h3>What about bigger models?</h3><h3>❌ Quantization Woes</h3><p>The biggest limitation: <strong>bitsandbytes doesn’t work on Mac</strong>. This meant:</p><ol><li><strong>No 4-bit compression</strong> for larger models</li><li><strong>48GB RAM limits</strong> us to ~13B models max without quantization</li><li><strong>mlx-community models</strong> (pre-quantized) had loading issues</li></ol><pre># This fails on Mac - bitsandbytes needs CUDA<br>model = AutoModel.from_pretrained(&quot;Phind-CodeLlama-34B-v2&quot;, compression=&#39;4bit&#39;)<br># Error: &quot;Torch not compiled with CUDA enabled&quot;</pre><p>In addition, I was eager to try deepseek-ocr on airllm, because it would have combined the layer by layer approach of airllm with the token 10x times optimization of deepseek-ocr. So I was imagining giving it my <a href="https://svelter.me/">entire project</a> to fit in memory and analyze, and do the tech debt for me :-)</p><h3>❌ File Format Frustrations</h3><p>Downloaded mlx-community/CodeLlama-13b-Python-4bit-MLX (7GB) but hit:</p><pre>FileNotFoundError: No safetensors found in [path]</pre><p>The pre-converted MLX models didn’t match MLX-LM’s expected file structure.</p><h3>❌ Performance Reality</h3><p>Even with successful 7B models:</p><ul><li><strong>8.5 minutes</strong> for initial AirLLM layer splitting</li><li><strong>Significant disk space</strong> needed for cache (20+ GB)</li><li><strong>Memory pressure</strong> even with “small” models</li></ul><h3>The Architecture Limitation</h3><p>Apple’s MLX framework is promising but immature:</p><ul><li><strong>No native quantization</strong> support (relies on bitsandbytes)</li><li><strong>Model ecosystem</strong> is spotty</li><li><strong>Documentation gaps</strong> for edge cases</li></ul><h3>Conclusion:</h3><p>Hosted Solutions Still Win for now. The Mac Studio (M3 Ultra, 192GB RAM) looks like a good silent AI workstation at home. But:</p><ul><li><strong>Same quantization issues</strong> apply</li><li><strong>Still limited</strong> by MLX ecosystem maturity</li><li><strong>Cost</strong>: $7,000+ for hardware vs $20/month cloud</li></ul><h3>Lessons Learned</h3><ol><li><strong>AirLLM</strong> has significant run overhead, a very “smart” model could compensate for the loading time by executing a complex task, but there are many bottelnecks to only getting it running</li><li><strong>Apple Silicon needs</strong> native quantization tools</li><li><strong>The ecosystem</strong> is moving fast but isn’t production-ready</li><li><strong>For serious work</strong>, cloud solutions still dominate</li></ol><h3>What else I tried on my Mac?</h3><p><strong>Ollama with smaller models</strong>:</p><pre>brew install ollama<br>ollama run codellama:13b-python</pre><p>It just works. No tensor conversions, no quantization headaches, but is very slow: of no help in the real world tasks, and killed memory consumption.<br>(there are articles out there on how to run it, if you’re curious)</p><blockquote><em>So the biggest challenge to learn AI model manipulation today is the hardware entry ticket.<br>Any alternatives you tried on your side? Tell me in the comments</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b48d41cdb7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing GitHub OAuth with Lucia in a SvelteKit Project]]></title>
            <link>https://medium.com/@zhamdi/implementing-github-oauth-with-lucia-in-a-sveltekit-project-9fbdf1f0800c?source=rss-deb121b7e0d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fbdf1f0800c</guid>
            <category><![CDATA[prototyping]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[iam-roles]]></category>
            <dc:creator><![CDATA[Zied Hamdi - https://github.com/ziedHamdi]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 13:48:24 GMT</pubDate>
            <atom:updated>2025-12-15T18:12:48.887Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*51CMgjnTSC33yTao" /><figcaption>Photo by <a href="https://unsplash.com/@shmdsgn?utm_source=medium&amp;utm_medium=referral">stefan moertl</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this blog post, I’ll walk you through how I integrated GitHub OAuth authentication into my <a href="https://svelter.me/">SvelteKit project</a> using Lucia for session management. I’ll jump straight into the code and explain the theory behind key decisions as we go.</p><h3>Step 1: Redirecting the User to GitHub</h3><p>When the user clicks the “Login with GitHub” button, they are redirected to GitHub’s authorization page. This is handled by a SvelteKit endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-V4iXVO4mAh-b97N-lueMw.png" /></figure><p>Code: /src/routes/login/github/+server.ts</p><pre>import { generateState } from &quot;arctic&quot;;<br>import { github } from &quot;$lib/server/oauth&quot;;<br>import type { RequestEvent } from &quot;@sveltejs/kit&quot;;<br><br>export async function GET(event: RequestEvent): Promise&lt;Response&gt; {<br>    // Generate a unique state for the OAuth transaction<br>    const state = generateState();<br><br>    // Create the GitHub authorization URL<br>    const url = github.createAuthorizationURL(state, []);<br><br>    // Store the state in a secure, HTTP-only cookie<br>    event.cookies.set(&quot;github_oauth_state&quot;, state, {<br>        path: &quot;/&quot;,<br>        httpOnly: true,<br>        maxAge: 60 * 10, // 10 minutes<br>        sameSite: &quot;lax&quot;<br>    });<br><br>    // Redirect the user to GitHub&#39;s authorization page<br>    return new Response(null, {<br>        status: 302,<br>        headers: {<br>            Location: url.toString()<br>        }<br>    });<br>}</pre><h3>Why the State Parameter?</h3><p>The state parameter is a unique, random string that prevents <strong>Cross-Site Request Forgery (CSRF)</strong> attacks. By storing it in a secure cookie and verifying it later, we ensure that the OAuth flow was called back for the same user and not by a malicious actor.</p><h3>Step 2: Handling the GitHub Callback</h3><p>After the user authorizes the application, GitHub redirects them to our callback URL (you set that up on your GitHub app settings page). Here, we validate the state, exchange the authorization code for an access token, and retrieve the user’s GitHub profile.</p><p>Code: /src/routes/login/github/callback/+server.ts</p><pre>import { Session, User } from &quot;$lib/server/db/model&quot;;<br>import { github, setSessionTokenCookie } from &quot;$lib/server/oauth&quot;;<br>import type { RequestEvent } from &quot;@sveltejs/kit&quot;;<br>import type { OAuth2Tokens } from &quot;arctic&quot;;<br>import type { IUser } from &quot;$lib/server/db/schema/entities&quot;;<br>import { SvelteLibraryFetcher } from &quot;$lib/server/scrape/GitHubScraper&quot;;<br>import logger from &quot;$lib/common/Logger&quot;;<br><br>export async function GET(event: RequestEvent): Promise&lt;Response&gt; {<br>    // Extract the code and state from the callback URL<br>    const code = event.url.searchParams.get(&quot;code&quot;);<br>    const state = event.url.searchParams.get(&quot;state&quot;);<br>    const storedState = event.cookies.get(&quot;github_oauth_state&quot;) ?? null;<br><br>    // Validate the state and code<br>    if (code === null || state === null || storedState === null || state !== storedState) {<br>        return new Response(null, { status: 400 });<br>    }<br><br>    // Exchange the authorization code for an access token<br>    let tokens: OAuth2Tokens;<br>    try {<br>        tokens = await github.validateAuthorizationCode(code);<br>    } catch (e) {<br>        return new Response(null, { status: 400 });<br>    }<br><br>    // Fetch the user&#39;s GitHub profile<br>    const githubUserResponse = await fetch(&quot;https://api.github.com/user&quot;, {<br>        headers: {<br>            Authorization: `Bearer ${tokens.accessToken()}`<br>        }<br>    });<br>    const userDetails = await githubUserResponse.json();<br>    const githubId = userDetails.id;<br><br>    // Check if the user already exists in the database<br>    const existingUser = await User.findOne({ githubId }).exec();<br>    if (existingUser) {<br>        return await sessionOk(existingUser, event, false);<br>    }<br><br>    // Create a new user if they don&#39;t exist<br>    const newUser = await User.create(SvelteLibraryFetcher.toLocalUser(userDetails));<br>    return await sessionOk(newUser, event, true);<br>}<br><br>// Helper function to create a session and redirect the user<br>async function sessionOk(user: IUser, event: RequestEvent, isNewUser: boolean): Promise&lt;Response&gt; {<br>    const sessionToken = Session.generateSessionToken();<br>    const session = await Session.createSession(user._id.toString(), sessionToken);<br>    setSessionTokenCookie(event, sessionToken, session.expires_at);<br>    return new Response(null, {<br>        status: 302,<br>        headers: {<br>            Location: &quot;/&quot;<br>        }<br>    });<br>}</pre><p>After saving the user, we are unconditionally redirecting to the landing page, this can be improved later by keeping in a cookie the page the user intended to visit before logging in (the one that triggered the login), and redirecting him back to it on success. We can also show the user a tutorial on his first connection through the <em>isNewUser</em> forking variable.</p><h3>Why Validate the State?</h3><p>Validating the state parameter ensures that the callback request is legitimate. If the state doesn’t match the one we stored, we reject the request to prevent CSRF attacks. That attack consists of a hacker calling the callback URL as if it was called by GitHub to mislead the app and cause it to grant him access.</p><h3>Step 3: Managing Sessions with Lucia</h3><p>Lucia handles session management by validating session tokens and managing cookies. The session token is stored in an HTTP-only cookie, making it inaccessible to client-side JavaScript.</p><p>The hook below is a middleware: it intercepts any request coming to the Sveltekit server. We use that opportunity to read the session cookie, and find the user corresponding to it (validateSessionToken()), which we set into the request context, making it readable by all the next request handlers.</p><p>Code: /src/hooks.server.ts</p><pre>import {<br>    validateSessionToken,<br>    setSessionTokenCookie,<br>    deleteSessionTokenCookie<br>} from &quot;$lib/server/oauth&quot;;<br>import type { Handle } from &quot;@sveltejs/kit&quot;;<br><br>export const handle: Handle = async ({ event, resolve }) =&gt; {<br>    const token = event.cookies.get(&quot;session&quot;) ?? null;<br><br>    if (token === null) {<br>        event.locals.user = null;<br>        event.locals.session = null;<br>        return resolve(event);<br>    }<br><br>    // Validate the session token<br>    const { session, user } = await validateSessionToken(token);<br><br>    if (session !== null) {<br>        setSessionTokenCookie(event, token, session.expires_at);<br>    } else {<br>        deleteSessionTokenCookie(event);<br>    }<br><br>    event.locals.session = session;<br>    event.locals.user = user;<br>    return resolve(event);<br>};</pre><blockquote>Why Use HTTP-Only Cookies?</blockquote><blockquote>HTTP-only cookies cannot be accessed by client-side JavaScript, which prevents <strong>cross-site scripting (XSS)</strong> attacks from stealing session tokens.</blockquote><h3>Step 4: Passing the information to the front-end</h3><p>At the root of the project templates, I added a +layout.server.ts file that will be called on any page display. As it is run on the server side, it gets the user we just set in the code above and makes it available to the svelte frontend pages by returning it (adding it to the data that is preloaded before running the template pages).</p><p>To read more about how layouts work in SvelteKit, check <a href="https://svelte.dev/docs/kit/routing#layout">this page</a>.</p><p>To read more about data preloading in Svelte, check the <a href="https://svelte.dev/docs/kit/load">official documentation</a>, which is very well explained.</p><p>Code: /src/routes/+layout.server.ts</p><pre>import type { LayoutServerLoad } from &#39;./$types&#39;;<br><br>export const load: LayoutServerLoad = async ({ locals }) =&gt; {<br>    return {<br>        user: locals.user, // Pass the user object to the client<br>    };<br>};</pre><h3>Step 5: Making The User App-widely Available</h3><p>The connected user is central information any component can need, whether to check the rights, display an avatar, or make changes to his information. On Svelte, you can achieve this by combining two features: <a href="https://svelte.dev/docs/svelte/stores">stores</a> (to get notified of changes) and <a href="https://svelte.dev/docs/kit/state-management#Using-state-and-stores-with-context">context</a> (to make a variable available to any component that requests it).</p><p>Code: /src/lib/stores/userStore.ts</p><pre>import {type Writable, writable} from &#39;svelte/store&#39;;<br>import type {UserDTO} from &quot;$lib/dto/UserDTO&quot;;<br><br>export const userStore: Writable&lt;UserDTO | null&gt; = writable(null);</pre><p>All the work has been done for you, making the store declaration a one line call.</p><p>Code: /src/routes/+layout.svelte</p><pre>&lt;script lang=&quot;ts&quot;&gt;<br> import { writable } from &#39;svelte/store&#39;;<br> import { i18n } from &#39;$lib/i18n&#39;;<br> import { ParaglideJS } from &#39;@inlang/paraglide-sveltekit&#39;;<br> import &#39;../app.css&#39;;<br> import &#39;@fortawesome/fontawesome-free/css/all.min.css&#39;<br><br> import { onMount, setContext } from &#39;svelte&#39;;<br> import {userStore} from &quot;$lib/stores/userStore&quot;;<br> import type {UserDTO} from &quot;$lib/dto/UserDTO&quot;;<br><br> const screenSize = &#39;(min-width: 640px)&#39;;<br> const isDesktop = writable(false);<br> // Provide the user store to the context<br> setContext(&#39;user&#39;, userStore);<br> setContext(&#39;isDesktop&#39;, isDesktop);<br><br> <br> interface PageData {<br>  user: UserDTO;<br> }<br> let { data, children } = $props&lt;{ data: PageData; children: any }&gt;()<br> userStore.set(data.user);<br><br> // Initialize the store with the user data from the server<br> userStore.set(data.user);<br> // detect if the size of the screen matches a mobile or desktop layout<br> function updateMedia() {<br>  isDesktop.set( window.matchMedia(screenSize).matches );<br> }<br><br> onMount(() =&gt; {<br>  // Set initial value<br>  updateMedia();<br><br>  // Add event listener for window resize<br>  const mediaQuery = window.matchMedia(screenSize);<br>  mediaQuery.addEventListener(&#39;change&#39;, updateMedia);<br><br>  // Clean up listener<br>  return () =&gt; mediaQuery.removeEventListener(&#39;change&#39;, updateMedia);<br> });<br><br>&lt;/script&gt;<br><br>&lt;ParaglideJS {i18n}&gt;<br> {@render children()}<br>&lt;/ParaglideJS&gt;</pre><p>I intentionally added another example of an app-wide store you might want to take decisions upon: here it is a detection of screen size changes to trigger a mobile view. You can also use this example to see that we can create stores both in separate js/ts files or directly in svelte components.</p><h3>Step 6: Displaying the User in the UI</h3><p>Code: /src/lib/comp/desktop/Header.svelte</p><pre>&lt;script lang=&quot;ts&quot;&gt;<br>    import { writable } from &#39;svelte/store&#39;;<br>    import LoginPopup from &quot;$lib/comp/desktop/login/LoginPopup.svelte&quot;;<br>    import type { UserDTO } from &quot;$lib/dto/UserDTO&quot;;<br><br>    export let user: UserDTO;<br><br>    const showLoginPopup = writable(false);<br><br>    function openLoginPopup(event: MouseEvent) {<br>        event.stopPropagation();<br>        showLoginPopup.set(true);<br>    }<br>&lt;/script&gt;<br><br>&lt;header id=&quot;header&quot; class=&quot;sticky top-0 bg-white border-b border-gray-200 z-50&quot;&gt;<br>    &lt;div class=&quot;container mx-auto px-6 py-4 flex justify-between items-center&quot;&gt;<br>        &lt;!-- Logo and navigation --&gt;<br>        &lt;div class=&quot;flex items-center space-x-6&quot;&gt;<br>            &lt;img src={user?.icon} alt=&quot;Profile&quot; class=&quot;w-8 h-8 rounded-full&quot; on:click={openLoginPopup}&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;LoginPopup bind:showPopup={$showLoginPopup} /&gt;<br>&lt;/header&gt;</pre><h3>Why Pass the User Object?</h3><p>Passing the user object to the client allows us to personalize the UI, such as displaying the user’s avatar and enabling user-specific actions.</p><h3>Conclusion</h3><p>Integrating GitHub OAuth with Lucia and Arctic, took me three hours, and now I have a widely available user I can access anywhere from the app.</p><p>If you’re building a project from scratch or an MVP, I highly recommend using SvelteKit. It’s lightweight, flexible, and easy to learn.</p><blockquote>You can see the project live on https://svelter.me</blockquote><h3>Annex:</h3><p>You are probably wondering what is in the functions I didn’t show the code of. I grouped them in an interface here, but you can do whatever strategy you pick here. As a temporary quick win solution, I am saving the sessions in MongoDb, but you could want to use JWT to avoid having to read and write into db on each request:</p><pre>export interface ISessionFeatures {<br>    generateSessionToken: () =&gt; string;<br>    createSession: (userId: string, sessionToken: string) =&gt; Promise&lt;SessionDocument&gt;;<br>    getSession: (sessionToken: string) =&gt; Promise&lt;SessionDocument | null&gt;;<br>    deleteSession: (sessionToken: string) =&gt; Promise&lt;boolean&gt;;<br>    updateSessionExpiration: (sessionToken: string, newExpiration: Date) =&gt; Promise&lt;boolean&gt;;<br>}</pre><p>So if you want, like me, to jump-start. Here’s a KISS implementation :-)</p><pre>import  { Document, Schema, Model } from &#39;mongoose&#39;;<br>import { randomBytes } from &#39;crypto&#39;;<br>import {connectToDatabase} from &quot;$lib/server/db&quot;;<br><br>export interface ISession {<br>    id: string; // Session token (64-character hex string)<br>    user_id: string; // User ID associated with the session<br>    expires_at: Date; // Expiration date of the session<br>}<br><br>// Define the Session interface<br>export type SessionDocument = Document &amp; ISession;<br><br>// Define the Session schema<br>export const sessionSchema: Schema = new Schema({<br>    id: {<br>        type: String,<br>        required: true,<br>        unique: true, // Ensures the field is unique<br>        index: true,  // Adds an index to the field<br>    },<br>    user_id: {<br>        type: String,<br>        required: true,<br>        index: true,  // Optionally, add an index to `user_id` if you query by it frequently<br>    },<br>    expires_at: {<br>        type: Date,<br>        required: true,<br>    },<br>});<br><br>// Define the static methods in an object<br>const sessionStatics = {<br>    /**<br>     * Generates a secure random session token.<br>     * @returns A unique session token.<br>     */<br>    generateSessionToken: function (): string {<br>        return randomBytes(32).toString(&#39;hex&#39;); // 64-character hex string<br>    },<br><br>    /**<br>     * Creates a new session.<br>     * @param userId - The ID of the user associated with the session.<br>     * @param sessionToken - The session token to be used as the session ID.<br>     * @returns The created session document.<br>     */<br>    createSession: async function (<br>        this: Model&lt;SessionDocument&gt;, // Explicitly define `this` as the Mongoose model<br>        userId: string,<br>        sessionToken: string<br>    ): Promise&lt;SessionDocument&gt; {<br>        await connectToDatabase();<br>        return await this.create({<br>            id: sessionToken, // Use the session token as the session ID<br>            user_id: userId,<br>            expires_at: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7 * 4), // 4 week from now<br>        });<br>    },<br><br>    /**<br>     * Retrieves a session by its token.<br>     * @param sessionToken - The session token to search for.<br>     * @returns The session document if found, otherwise null.<br>     */<br>    getSession: async function (<br>        this: Model&lt;SessionDocument&gt;, // Explicitly define `this` as the Mongoose model<br>        sessionToken: string<br>    ): Promise&lt;SessionDocument | null&gt; {<br>        await connectToDatabase();<br>        return await this.findOne({ id: sessionToken }).exec();<br>    },<br><br>    /**<br>     * Deletes a session by its token.<br>     * @param sessionToken - The session token to delete.<br>     * @returns A boolean indicating whether the session was deleted.<br>     */<br>    deleteSession: async function (<br>        this: Model&lt;SessionDocument&gt;, // Explicitly define `this` as the Mongoose model<br>        sessionToken: string<br>    ): Promise&lt;boolean&gt; {<br>        await connectToDatabase();<br>        const result = await this.deleteOne({ id: sessionToken }).exec();<br>        return result.deletedCount &gt; 0; // Returns true if a session was deleted<br>    },<br><br>    /**<br>     * Updates the expiration date of a session.<br>     * @param sessionToken - The session token to update.<br>     * @param newExpiration - The new expiration date.<br>     * @returns A boolean indicating whether the session was updated.<br>     */<br>    updateSessionExpiration: async function (<br>        this: Model&lt;SessionDocument&gt;, // Explicitly define `this` as the Mongoose model<br>        sessionToken: string,<br>        newExpiration: Date<br>    ): Promise&lt;boolean&gt; {<br>        await connectToDatabase();<br>        const result = await this.updateOne({ id: sessionToken }, { expires_at: newExpiration }).exec();<br>        return result.modifiedCount &gt; 0; // Returns true if the session was updated<br>    },<br><br>};<br><br>// Add the static methods to the schema one by one<br>for (const [methodName, methodImplementation] of Object.entries(sessionStatics)) {<br>    sessionSchema.statics[methodName] = methodImplementation;<br>}</pre><p>I hope you enjoyed this article. Feel free to ask any questions, I’ll be happy to help.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fbdf1f0800c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to transform your idea into a project. Day two: Svelte components]]></title>
            <link>https://medium.com/@zhamdi/how-to-transform-your-idea-into-a-project-day-two-svelte-components-4dc53ec30e5c?source=rss-deb121b7e0d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dc53ec30e5c</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[startup-life]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[bootstrapping]]></category>
            <dc:creator><![CDATA[Zied Hamdi - https://github.com/ziedHamdi]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 16:56:55 GMT</pubDate>
            <atom:updated>2025-12-15T18:15:08.950Z</atom:updated>
            <content:encoded><![CDATA[<p>Using AI to build fast projects</p><blockquote>This is the second part of a journey of building the <a href="https://svelter.me/">svleter project</a> in public through AI. You can visit the<a href="https://medium.com/@zhamdi/how-to-transform-your-idea-into-a-project-day-one-ux-and-svelte-77f64f8e30a0"> first part here.</a> This is now outdated as I use KiloCode, Google Jules, Google Antigravity and Amazon Kiro to accomplish my code tasks.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1zeikGeHGbn1oCXB" /><figcaption>Photo by <a href="https://unsplash.com/@trintaycinco?utm_source=medium&amp;utm_medium=referral">Nathalia Segato</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Decomposing the page components:</h3><p>It is tedious repetitive and not much of a smart task to decompose a page into smaller components, and to create the <strong><em>DTO</em></strong>s that go with it. So that&#39;s a perfect job for AI. Below is the prompt I used.</p><p>I first described the project and asked ChatGPT to rephrase it (and pushed that in the previous blog post 🤓). So now I can be confident ChatGPT knows what the project is about because he rephrased it correctly.</p><p>I could have not been clear in my description, so the best way to verify that is to ask it to tell you what you just told him in his words, and see if it matches the image you have in your mind. So now I can build on top of that. This is how I prompted it to decompose my HTML screen into components:</p><blockquote>Thank you! Now for that same idea, I have a complete screen that I would like to split into different components. Could you help me doing that, and create the typescript DTOs that will feed these screens with data? Here’s the first mobile page:<br>&lt;div id=”root” class=”bg-gray-50&quot;&gt;<br> … (the rest of the huge page code)</blockquote><p>That worked, but not as I expected: It generated dumb DTOs separating the WinningLibraryDto from the LibraryDto. It also created DTOs for the header and footer, which are good, but not exactly what I&#39;m focusing on for now. You will often face this type of misunderstanding when using AI, you have to adjust what you expect in a followup prompt.</p><p>Keep in mind that by thanking ChatGPT, you are telling him that he is on the right path, and there are only some tweaks needed. Not thanking him, would make him think he had it all wrong, and rebuild from scratch.</p><blockquote>Always remember to start by expressing your satisfaction with the part you are liked before digging into criticism <em>🤓 </em>(it is not about being polite with themachine, but it gives amazing results and is a good way to maintain your good habits now that you will talk more and more often to machines <em>🤪</em>)</blockquote><p>So here&#39;s the adjusting prompt:</p><blockquote>That is a great job! I need to specify a bit further my needs though: I’d like you to only focus on the dynamic parts of the data, even though, it is a good idea to extract the hero section data from the component, that is something I will focus on later. Also, the winning library is a library, so could you factorize a bit that data so that my services return more generic data types, for example merging WinnerCardDTO and LibraryCardDTO into a single data type, as the only difference is that it won (by the way, it can win multiple consecutive times, so adapt to that too please). Finally, could you decompose the svelte components and display them jest after or before the belonging DTO so that it is easier to handle for me?</blockquote><p>And now results are amazing again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*cBRUF4ExghAmbU8JNR2Yvg.png" /></figure><p>I got four atomic components and a <strong>DTO</strong> that I copied into my project. I only had to replace ../ by <strong>$lib. </strong>However, ChatGPT forgot to include the main page that uses these components, so instead of writing it manually, I prompted again and also asked it to start the automatic testing code. See the next section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueo-BodQMI44mv2bku1odA.png" /><figcaption>Components successfully created with ChatGPT</figcaption></figure><h3>Testing the project so far:</h3><blockquote>It is a good habit to verify your advancement often to be able to react to errors before things become too complex.</blockquote><p>So here is my finalizing prompt that asks ChatGPT to finish the work and write code to test what it just generated (as long as it remembers it)</p><blockquote>That is awesome, I think you forgot to rebuild the original page with the components you created. Could you also use this mock data to verify everything is in place through playwright tests?</blockquote><h4>Results:</h4><p>After some path adjustments, and addition of elements the AI missed generating. I can finally see the following screen 🥰:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*ZK5tV6UpqpDAhgdH51dmhg.png" /></figure><p>Four end-to-end tests were generated, two of which were immediately working, I fixed the two others and rapidly. I will iterate on improving tests later, but now I have a working structure I can build on top of. So I am confident leaving it like this for now. So it&#39;s time to put that all on GitHub, so that I can understand which changes broke my code later when it happens.</p><p>Also, accessibility errors are displayed in the console, I know I can get back to them later, as they couldn’t go unnoticed even if they tried. So no fears of missing that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMswgpWzodw9ctp6QAeFhg.png" /><figcaption>Run under WebStorm, my preferred IDE</figcaption></figure><h3>Desktop version:</h3><p>Before the AI forgets what we are speaking about, I asked it to decompose the desktop version of the HTML I generated with UX Pilot (see <a href="https://medium.com/@zhamdi/how-to-transform-your-idea-into-a-project-day-one-ux-and-svelte-77f64f8e30a0">previous article</a>).</p><p>It flawlessly generated four components along with the index files that use them. I adjusted the components paths and called the index file <strong><em>HomePage.svelte. </em></strong>For code readability, I named the desktop component files the same way they are on the mobile version.</p><p>Finally, I compared the two visual. There were some missing parts, buttons and styles, but it was definitely worth it to get them generated, as I only had to compare and fill the blanks. Below is the index file using all desktop components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*GZh6bWON3tRCSdNXT2oVqA.png" /></figure><h3><strong>Code extracts:</strong></h3><p>To rapidly see what results I&#39;ve reached, I shortcut the app by mocking the server response, and worked on the central part that switches between the desktop and the mobile version. Let&#39;s start with the latter part.</p><h4>Responsive Design: Handling Desktop and Mobile Views:</h4><p>At the root of the project routes, the file <strong><em>src/routes/+layout.svelte</em></strong> will be loaded on any screen in the app before loading the actual page. So it is a good idea to put the screen size detection there.</p><blockquote>ChatGPT wrote a non-working draft of the code below, it was setting the context on each method call. So a bit of Svelte stores and context knowledge was required here. But nothing that you coudn&#39;t find in the docs. I explain the details below the code sample.</blockquote><pre>&lt;script lang=&quot;ts&quot;&gt;<br>  import { writable } from &#39;svelte/store&#39;;<br>  import { i18n } from &#39;$lib/i18n&#39;;<br>  import { ParaglideJS } from &#39;@inlang/paraglide-sveltekit&#39;;<br>  import &#39;../app.css&#39;;<br>  import &#39;@fortawesome/fontawesome-free/css/all.min.css&#39;<br><br>  import { onMount, setContext } from &#39;svelte&#39;;<br><br>  const isDesktop = writable(false);<br>  setContext(&#39;isDesktop&#39;, isDesktop);<br><br>  const screenSize = &#39;(min-width: 640px)&#39;;<br><br>  function updateMedia() {<br>   isDesktop.set( window.matchMedia(screenSize).matches );<br>  }<br><br>  onMount(() =&gt; {<br>   // Set initial value<br>   updateMedia();<br><br>   // Add event listener for window resize<br>   const mediaQuery = window.matchMedia(screenSize);<br>   mediaQuery.addEventListener(&#39;change&#39;, updateMedia);<br><br>   // Clean up listener<br>   return () =&gt; mediaQuery.removeEventListener(&#39;change&#39;, updateMedia);<br>  });<br><br>  let { children } = $props();<br>&lt;/script&gt;<br><br>&lt;ParaglideJS {i18n}&gt;<br>  {@render children()}<br>&lt;/ParaglideJS&gt;</pre><p><strong><em>There are a few things to know here:</em></strong></p><p>The context can only be set once, it is not designed to change after the page is displayed. But! We can put a store as the context value, and the content of that store can change over time, keeping the same pointer. Therefore, we set the context immediately after creating the writable. And we set its value on screen size changes.</p><p><strong>The switch:</strong></p><pre>&lt;script lang=&quot;ts&quot;&gt;<br>  import { getContext, onMount } from &#39;svelte&#39;;<br>  import type { Writable } from &#39;svelte/store&#39;;<br>  import HomePageMobile from &#39;$lib/comp/mobile/HomePage.svelte&#39;;<br>  import HomePageDesktop from &#39;$lib/comp/desktop/HomePage.svelte&#39;;<br><br>  // Get the isDesktop value from root layout<br>  const isDesktopWritable = getContext(&#39;isDesktop&#39;) as Writable&lt;boolean&gt;;<br>  let isDesktop = $derived($isDesktopWritable);<br><br>&lt;/script&gt;<br><br>{#if isDesktop}<br>  &lt;HomePageDesktop {libraries} {weeklyWinners} {categories} /&gt;<br>{:else}<br>  &lt;HomePageMobile {libraries} {weeklyWinners} /&gt;<br>{/if}</pre><p><em>We derive the store value of </em><strong><em>isDesktopWritable </em></strong><em>to make the page react to its changes. Specifically, we access the proxy value (with the $ operator) and make a derived variable from it: </em><strong><em>$derived($isDesktopWritable)</em></strong></p><p>Again, having a non-working code from ChatGPT was worth it, as it set the media query, know it was the window width we have to react to, and not the document, the kind of things you have to research before writing such code.</p><p>This pattern will be in any page in the application. I intentionally made two different versions of the graphical components of the application to be able to evolve each of them separately instead of having a bunch of <strong><em>#if :else</em></strong> blocs on each.</p><h4>Mocking the API endpoints:</h4><p>As you might already know, <a href="https://svelte.dev/docs/kit/routing#server">+server.js(or .ts)</a> files are only run server side. So I added the files below, that will later serve real data, but for now I just used the mocked DTO values generated by ChatGPT (see prompt above).</p><figure><img alt="routes under /route/api/ with +server.ts files" src="https://cdn-images-1.medium.com/max/223/1*pK9uF1YfRPZRSXyIKccSuA.png" /></figure><p>For example, this is how the <strong><em>/api/libraries</em></strong> endpoint returns the mocked values:</p><pre>import { json } from &#39;@sveltejs/kit&#39;;<br><br>export function GET() {<br><br>  return json([<br>   {<br>    id: &#39;1&#39;,<br>    name: &#39;SvelteKit Auth&#39;,<br>    description: &#39;Authentication library for SvelteKit with multiple providers.&#39;,<br>    categories: [&#39;Auth&#39;, &#39;TypeScript&#39;, &#39;OAuth&#39;],<br>    votes: 245,<br>    githubStars: 1200,<br>    downloads: &#39;15k/week&#39;,<br>   },<br>   {<br>    id: &#39;2&#39;,<br>    name: &#39;SvelteKit DataTables&#39;,<br>    description: &#39;Powerful data tables with sorting and filtering options.&#39;,<br>    categories: [&#39;UI&#39;, &#39;Data&#39;, &#39;Tables&#39;],<br>    votes: 178,<br>    githubStars: 856,<br>    downloads: &#39;8k/week&#39;,<br>   },<br>  ]);<br>}</pre><p>These display in the app (desktop version) like follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*a-HR_gAHMUh825EhUBeRyQ.png" /></figure><p>The endpoint calls happen in the <strong><em>+page.svlete</em></strong> root route (I stripped out part of the code when I was explaining how responsiveness works, so here is the complete file code)</p><pre>&lt;script lang=&quot;ts&quot;&gt;<br>  import { getContext, onMount } from &#39;svelte&#39;;<br>  import type { Writable } from &#39;svelte/store&#39;;<br>  import type { LibraryDTO } from &#39;$lib/dto/LibraryDTO&#39;;<br>  import HomePageMobile from &#39;$lib/comp/mobile/HomePage.svelte&#39;;<br>  import HomePageDesktop from &#39;$lib/comp/desktop/HomePage.svelte&#39;;<br>  import type { CategoryDTO } from &#39;$lib/dto/CategoryDTO&#39;;<br><br>  let libraries: LibraryDTO[] = $state([]), weeklyWinners: LibraryDTO[] = $state([]), categories: CategoryDTO[] = $state([]);<br><br>  async function loadData() {<br>   const endpoints = [<br>    { url: &#39;/api/libraries&#39;, variable: &#39;libraries&#39; },<br>    { url: &#39;/api/weeklyWinners&#39;, variable: &#39;weeklyWinners&#39; },<br>    { url: &#39;/api/categories&#39;, variable: &#39;categories&#39; },<br>   ] as const;<br><br>   const results: {libraries:LibraryDTO[], weeklyWinners:LibraryDTO[], categories:CategoryDTO[]} = {libraries:[], weeklyWinners: [], categories: []};<br><br>   for (const { url, variable } of endpoints) {<br>    const res = await fetch(url);<br>    if (res.ok) {<br>     results[variable] = await res.json();<br>    }<br>   }<br><br>   return results;<br>  }<br><br>  // Get the isDesktop value from root layout<br>  const isDesktopWritable = getContext(&#39;isDesktop&#39;) as Writable&lt;boolean&gt;;<br>  let isDesktop = $derived($isDesktopWritable);<br>  onMount(async () =&gt; {<br>   // Fetch the data<br>   const results = await loadData();<br><br>   // Destructure and assign the result to the reactive variables<br>   ({ libraries, weeklyWinners, categories } = results);<br>  });<br>&lt;/script&gt;<br><br>{#if isDesktop}<br>  &lt;HomePageDesktop {libraries} {weeklyWinners} {categories} /&gt;<br>{:else}<br>  &lt;HomePageMobile {libraries} {weeklyWinners} /&gt;<br>{/if}</pre><p><em>It might be optimized by parallelizing the load calls, but will do it for now.</em></p><h4>End-to-end Tests code:</h4><p>Even though the tests could cover a lot more, having a working testing code makes it easier to iterate later on it.</p><p>Here&#39;s what ChatGPT generated the first time I asked it to do it:</p><pre>import { test, expect } from &#39;@playwright/test&#39;;<br>import { libraries, weeklyWinners } from &#39;./data&#39;;<br><br>test.describe(&#39;Home Page&#39;, () =&gt; {<br>  test.beforeEach(async ({ page }) =&gt; {<br>   await page.route(&#39;/api/libraries.json&#39;, async (route) =&gt; {<br>    await route.fulfill({<br>     status: 200,<br>     contentType: &#39;application/json&#39;,<br>     body: JSON.stringify(libraries)<br>    });<br>   });<br><br>   await page.route(&#39;/api/winners.json&#39;, async (route) =&gt; {<br>    await route.fulfill({<br>     status: 200,<br>     contentType: &#39;application/json&#39;,<br>     body: JSON.stringify(weeklyWinners)<br>    });<br>   });<br>   // Navigate to the home page<br>   await page.goto(&#39;/&#39;);<br>  });<br><br>  test(&#39;should display the hero section&#39;, async ({ page }) =&gt; {<br>   const heroTitle = page.locator(&#39;h1&#39;, { hasText: &#39;Discover the Best Svelte Libraries&#39; });<br>   const heroSubtitle = page.locator(&#39;p&#39;, { hasText: &#39;Curated list of trending&#39; });<br><br>   await expect(heroTitle).toBeVisible();<br>   await expect(heroSubtitle).toBeVisible();<br>  });<br><br>  test(&#39;should render trending libraries section with correct data&#39;, async ({ page }) =&gt; {<br>   const sectionTitle = page.locator(&#39;h2&#39;, { hasText: &#39;Trending Today&#39; });<br>   await expect(sectionTitle).toBeVisible();<br><br>   const firstCardTitle = page.locator(&#39;h3&#39;, { hasText: &#39;SvelteKit Auth&#39; });<br>   const secondCardTitle = page.locator(&#39;h3&#39;, { hasText: &#39;SvelteKit DataTables&#39; });<br><br>   await expect(firstCardTitle).toBeVisible();<br>   await expect(secondCardTitle).toBeVisible();<br><br>   const voteCount = page.locator(&#39;span&#39;, { hasText: &#39;245&#39; });<br>   await expect(voteCount).toBeVisible();<br>  });<br><br>  test(&#39;should render weekly winners with winning weeks&#39;, async ({ page }) =&gt; {<br>   const sectionTitle = page.locator(&#39;h2&#39;, { hasText: &#39;Weekly Winners&#39; });<br>   await expect(sectionTitle).toBeVisible();<br><br>   const winnerTitle = page.locator(&#39;h3&#39;, { hasText: &#39;SvelteKit Forms&#39; });<br>   await expect(winnerTitle).toBeVisible();<br><br>   const wonWeeksText = page.locator(&#39;p&#39;, { hasText: &#39;Won Week &#39; });<br>   await expect(wonWeeksText).toBeVisible();<br>  });<br><br>  test(&#39;should verify buttons and links are interactive&#39;, async ({ page }) =&gt; {<br>   const upvoteButtons = page.locator(&#39;button&#39;, { has: page.locator(&#39;i.fa-arrow-up&#39;) }).first();<br>   //expect(await upvoteButtons.count()).toBeGreaterThan(0);<br>   await expect(upvoteButtons).toBeVisible();<br><br>   const githubLink = page.locator(&#39;a&#39;, { hasText: &#39;1200&#39; }).first();<br>   await expect(githubLink).toHaveAttribute(&#39;href&#39;, &#39;/&#39;);<br>  });<br>});</pre><h3>Summary</h3><p>The day two of creating the app was pretty satisfactory too, I now can confidently add the missing information for these welcome screens and decompose the other ones I created with <a href="https://uxpilot.ai/">UX Pilot</a>. I will not talk about that other routes as there will be no interesting information for you on how to do that effectively. So I hope to see you in a few days when my other screens will be ready</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dc53ec30e5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to transform your idea into a project. Day one: UX and Svelte]]></title>
            <link>https://medium.com/@zhamdi/how-to-transform-your-idea-into-a-project-day-one-ux-and-svelte-77f64f8e30a0?source=rss-deb121b7e0d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/77f64f8e30a0</guid>
            <category><![CDATA[startup-life]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[bootstrapping]]></category>
            <dc:creator><![CDATA[Zied Hamdi - https://github.com/ziedHamdi]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 10:29:06 GMT</pubDate>
            <atom:updated>2025-12-15T18:10:12.905Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lean startup, learn fast, fail fast</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ynR9c6_IhRhnESac" /><figcaption>Photo by <a href="https://unsplash.com/@florianklauer?utm_source=medium&amp;utm_medium=referral">Florian Klauer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is important to validate your idea as soon as possible, getting feedback from your typical users. In this series of articles, I’ll be building in public and showing how I move fast. This is my third one-month-MVP, so I hope my articles will help you get started fast in your project idea</p><blockquote><strong>So let me tell you about my project idea, this is needed to understand the coming steps.</strong></blockquote><h3>The idea:</h3><p>A <em>Product Hunt</em>-inspired platform <a href="https://svelter.me/">showcasing <strong>SvelteKit libraries</strong></a>. Each library features key details: descriptions, alternatives, category tags, and user engagement metrics like upvotes, comments, and weekly winners. The platform aggregates essential developer data — GitHub stars, NPM weekly downloads, and project web links — prioritizing relevance.</p><h3>The steps:</h3><h3><strong>1 — UX:</strong></h3><p>There is an awesome AI tool called <a href="https://uxpilot.ai/">Ux Pilot</a> that allows you to describe your project and get ready-to-use screens.</p><p>In the pro version, you can immediately extract the visuals into Html + <a href="https://tailwindcss.com/">TailwindCss</a> + <a href="https://fontawesome.com/">Font Awesome</a>.</p><p>A screen is generated through two input fields: a context, and a flow. You can use pretty straightforward descriptions in both these fields, pick the mobile or desktop selector, and generate.</p><p>I got the design below for the welcome screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*Gkwe8WTYASG2qBMbUpjbpg.png" /></figure><p>All I had to enter was this prompt, the first block being the context, and the second the flow:</p><pre>- I&#39;d like to create a producthunt like app but that lists sveltekit libraries along with their descriptions, alternative libraries, an image representing each of them, and information about votes people can upvote, comment and see the winning libraries of each week. Libraries being classified in categories and attributed tags.<br>   Each project has a link to github along with information about the starred count, a link to npm along with information about the weekly downloads, and a link to the webpage. I let you judge when it is relevant to display which information<br><br> - **style**:<br>The colors should express joy without overdoing it. It should also feel as a serious page, and partly and subtly use the svelte logo colors just to remind that we are a website about svelte. It should also feel familiar to people used to producthunt, reminding them of the experience but not copying it exactly, making the user experience designed for developers.<br><br> - **screen**:<br> - **logo**: The logo should look like a fire inside the html typical chars: &quot;&lt;(fire icon)/&gt;&quot;</pre><pre>I&#39;d like you to create a landing page where the user can immediately understand what the project is about.</pre><p>You can then improve a generated screen by specifying what you&#39;d like to change. Below is the result when I selected a screen zone and asked if it could add a “Read more” button for longer descriptions and if it could handle more tags (which it didn&#39;t respond to, but gave me an alternative view)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qSYyyQ_um5hiKYligKtwg.png" /></figure><p>I then generated all the screens I needed and started feeling eager to start developing it all, as I could now visualize how it would all look like and got very excited about it.</p><h3>2 — The Svelter project:</h3><p>From here, we need to start coding, and I cannot think of a faster way to get it done than by using <a href="https://svelte.dev/tutorial/svelte/welcome-to-svelte">SvelteKit</a>. So I started right away:</p><pre>npx sv create onsvelte<br>cd onsvelte<br>pnpm i<br>pnpm dev</pre><p>I chose to include TailwindCss and Lucia, and asked to generate a demo app so that I can rapidly see my screens without much setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*BNiS5K1AqsglEa3NPsHmdw.png" /></figure><p>In the /routes section, there is this <strong><em>+page.svelte</em></strong> file that is the landing page of the project. I modified it to look like follows:</p><pre>&lt;script&gt;<br>  import Home from &#39;$lib/comp/mobile/Home.svelte&#39;;<br>&lt;/script&gt;<br><br>&lt;Home/&gt;</pre><p>You must wonder what is the imported component. That&#39;s the one containing the source code I copied from <a href="https://uxpilot.ai/">Ux Pilot</a> for the mobile home screen.</p><p>So now I can see my complete welcome page. That one will have to be decomposed into reusable components, but I wanted to make sure everything works before starting that work. Indeed, something is missing: some icons display and some don&#39;t. The arrows, the GitHub logo, etc…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PGuu6yGp0bMHVvKcvVKqWw.png" /></figure><p>So I checked in the source code, and it showed that these were icons from <a href="https://fontawesome.com/">Font Awesome</a>.</p><h4>Installing font awesome on Svelte:</h4><p>This is not as easy as it seems, because of the way Svelte loads resources. But this is how you should do it:</p><p>Install the font awesome package</p><pre>pnpm add @fortawesome/fontawesome-free</pre><p>Import the CSS file containing all icons in <strong><em>routes/+layout.svelte</em></strong> to make it available to all project pages</p><pre>&lt;script lang=&quot;ts&quot;&gt;<br> import { i18n } from &#39;$lib/i18n&#39;;<br> import { ParaglideJS } from &#39;@inlang/paraglide-sveltekit&#39;;<br> import &#39;../app.css&#39;;<br> import &#39;@fortawesome/fontawesome-free/css/all.min.css&#39;<br> let { children } = $props();<br>&lt;/script&gt;<br><br>&lt;ParaglideJS {i18n}&gt;<br> {@render children()}<br>&lt;/ParaglideJS&gt;</pre><p>And it works! Now you&#39;re ready to start decomposing your pages into reusable components. But let&#39;s leave that to the next article.</p><h3>Summary</h3><p>In this article, you were able to move from the idea of an application that you had in your mind to a real set of screens running on your local server. That&#39;s a pretty good advancement you can do in one day (or two if there are new things you have to learn). It cost me 29$ for the <a href="https://uxpilot.ai/">Ux Pilot</a> subscription that I purchased only for one month (but that I needed to avoid having to build the screens in CSS from scratch). And now I&#39;m ready to start filling these screens with real data.<br>Drop me a comment if you liked this article and want to see the other steps.</p><blockquote>Update the appliaction is now available on https://svelter.me</blockquote><p><a href="https://medium.com/@zhamdi/how-to-transform-your-idea-into-a-project-day-two-svelte-components-4dc53ec30e5c"><strong>&lt; Click here to read part 2: Day two: Svelte components &gt;</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77f64f8e30a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to hack these hackers?]]></title>
            <link>https://medium.com/@zhamdi/how-to-hack-these-hackers-e860e7edad76?source=rss-deb121b7e0d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e860e7edad76</guid>
            <dc:creator><![CDATA[Zied Hamdi - https://github.com/ziedHamdi]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 14:04:25 GMT</pubDate>
            <atom:updated>2024-08-27T14:04:25.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCgBYIeI8hG2oVewrzljfA.png" /></figure><h3>Short story short:</h3><p>I received this Ns SMS telling me that my package was not delivered, and that I should visit a short url to check what when wrong.<br>In a short url, you don&#39;t know what you can expect behind it, so I copied that url from my phone to ma secured computer and visited it (because I was really expecting a package). <br>It showed to be a spam as I suspected. So I decided to attack back.</p><h3>What happened when I visited the url?</h3><p>The url was like <a href="https://is.gd/mJzSHL?poG=ujsw57Px2L?DgV=n3zSd/C8tC">https://is.gd/mJzSHL?poG=ujsw57Px2L?DgV=n3zSdC8tC</a> which resolved to <a href="https://ceska-p.top/cz">https://ceska-p.top/cz</a></p><p>These non sens words in the url like <a href="https://is.gd/mJzSHL?poG=ujsw57Px2L?DgV=n3zSd/C8tC"><strong>mJzSHL</strong></a><strong> </strong>are unique to the SMS they sent to my phone (number), confirming that I clicked on the link, so that I could be targeted again for their next trap.</p><p>So I decided that I will not get bombarded with these SMSes without doing anything. The messages arrive each time from a different number: once they know you react, they add you to their database.</p><h3>The revenge idea</h3><p>But if they are bombarded with false clicks that they didn&#39;t expect, the smallest pain is that their servers will be overloaded, the ideal case would be to mess out their database.</p><p>So with the help of ChatGpt, I wrote a simple batch program that generates random strings and visits their url shortener with these made-up strings. I sent a few thousand false clicks just for the joy of it :-D</p><p>Below is the script.</p><h3>Why did I write this post?</h3><p>I thought it could be a good idea to gather each time to attack the attacker from multiple computers with scripts like this one, making them unable to harm. But the idea of how to find each other is still not mature enough. So don&#39;t hesitate to write in your comments if you have an idea, or if something like this already exists.</p><h3>The script:</h3><pre>#!/bin/bash<br><br># Function to generate a random string of a specified length<br>generate_random_string() {<br>    length=$1<br>    # Generate a random string of the specified length in base64 encoding and trim it to the exact length<br>    openssl rand -base64 $length | cut -c1-$length<br>}<br><br># Loop 100 times<br>for ((i=1;i&lt;=10000;i++)); do<br>    # Generate random values for poG and DgV<br>    poG=$(generate_random_string 10)<br>    DgV=$(generate_random_string 10)<br><br>    # Construct the URL with the random parameters<br>    url=&quot;https://is.gd/mJzSHL?poG=${poG}?DgV=${DgV}&quot;<br><br>    # Make the curl request<br>    curl -v --header &quot;Connection: keep-alive&quot; &quot;$url&quot;<br><br>    # Sleep for 1 second before the next iteration<br>    sleep 1<br>done</pre><p>That&#39;s it for now, see you in the comments or on the next idea ❤.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e860e7edad76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to design Bundled Offers in your Credit Management]]></title>
            <link>https://medium.com/@zhamdi/how-to-design-bundled-offers-in-your-credit-management-8b294af2c8c6?source=rss-deb121b7e0d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b294af2c8c6</guid>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[pay-as-you-go]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[bootcamp]]></category>
            <category><![CDATA[stripe]]></category>
            <dc:creator><![CDATA[Zied Hamdi - https://github.com/ziedHamdi]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 17:52:04 GMT</pubDate>
            <atom:updated>2023-12-05T17:52:04.222Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the latest update to the <a href="http://user-credits.dev/">user-credits</a> library, I’m thrilled to unveil two game-changing features: Bundled Offers and the Deduction of Expired Credits. These additions mark a significant milestone, propelling the library to its <a href="https://www.npmjs.com/package/@user-credits/stripe-mongoose">1.0.0-beta release</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hBg58Zf4tVFajcuRgQcTgw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@cravethebenefits?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Brenda Godinez</a> on <a href="https://unsplash.com/photos/bowl-of-sliced-fruits-on-white-textile-_Zn_7FzoL1w?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Bundled Offers: Managing Complexity</h3><p>Managing multiple offers simultaneously posed challenges, but with Bundled Offers, it’s a breeze. Now, users can combine offers to create packages, akin to mobile service providers with multiple parallel credits like calling quotas, data, games etc... For a detailed understanding, delve into the <a href="https://dev.to/zhamdi/bundled-offers-with-user-credits-npm-1pbd">article here</a>.</p><h3>Real-Time Credit Tracking</h3><p>With the new feature, developers can effortlessly track users’ credit balances and consumption for each bundled offer, providing unparalleled visibility and enhancing the overall user experience.</p><h3>Deduction of Expired Credits: Streamlining Processes</h3><p>Efficient credit management involves handling expired credits. The Deduction of Expired Credits feature streamlines this process, ensuring users are informed before and credits are deducted seamlessly. The token consumption call signature is as follows:</p><pre>tokensConsumed(userId: K, offerGroup: string, count: number): Promise&lt;ITokenTimetable&lt;K&gt;&gt;;</pre><h3>Real-Time Monitoring and Warnings</h3><p>The library empowers developers with real-time monitoring and warnings for low credits and imminent expiry. This function cleans the database while providing timely alerts about credit levels and offer expiry.</p><pre>const { expired, warnings } = await service.checkForExpiredOrders(userId, warningDuration, lowLimits);</pre><h3>Conclusion: Elevate Your Credit Management Game</h3><p>In conclusion, Bundled Offers and the Deduction of Expired Credits usher in a new era of simplicity and effectiveness in credit management. These features not only enhance user experience but also open doors to innovative pricing models and subscription plans.</p><p>Ready to empower your credit management? Host the user-credits library in a VM and call it in parallel to your existing system to explore it without risks. Your credit management could end up being a micro-service 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b294af2c8c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design your pay-as-you-go offers with user-credits]]></title>
            <link>https://medium.com/@zhamdi/design-your-pay-as-you-go-offers-with-user-credits-21cb8d9f162d?source=rss-deb121b7e0d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/21cb8d9f162d</guid>
            <category><![CDATA[pay-as-you-go]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[business-models]]></category>
            <dc:creator><![CDATA[Zied Hamdi - https://github.com/ziedHamdi]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 12:21:08 GMT</pubDate>
            <atom:updated>2023-11-07T11:00:03.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NASbv4bzVI1lpICZF9HUJA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@joshuakettle?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Joshua Kettle</a> on <a href="https://unsplash.com/photos/a-night-view-of-the-gardens-by-the-bay-in-singapore-s3i02B7qiVA?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Crafting a Compelling Subscription Offer Ecosystem With a Ready-to-use Library</h3><p>In this guide, we’ll explore how to create enticing subscription offers that attract early adopters and deliver real value to your customers using the concepts presented in the <a href="https://github.com/ziedHamdi/UserCredits">user-credits</a> open-source library. We’ll do a practical case study with a typical offering for an early stage startup that we called “WonderAI”.</p><h3>The Core Offerings</h3><p>WonderAI, our fictional startup, offers three primary subscription types: “Startup,” “Business,” and “ScaleUp,” catering to different stages of a customer’s journey.</p><ul><li>Startup: Ideal for budding entrepreneurs and startups entering the world of AI.</li><li>Business: Tailored for established startups ready to take their AI ventures to the next level.</li><li>ScaleUp: The top-tier subscription for rapidly growing startups.</li></ul><h3>Attracting Early Birds</h3><p>To stand out and entice early adopters, WonderAI not only offers competitive core subscriptions but also exclusive VIP offers available to all subscribers, regardless of their stage. This approach provides premium features to customers at different stages.</p><h3>Monthly vs. Yearly Payments</h3><p>WonderAI offers flexibility with monthly and yearly payment options, including two months free with yearly subscriptions.</p><h3>The Power of Offer Groups</h3><p>Offer Groups are crucial for managing subscriptions, especially in the context of AI and SaaS companies. They help connect related subscriptions and handle complex scenarios.</p><h3>Functional Tags Simplify Offer Display</h3><p>Functional Tags allow you to filter and display offers effectively. They guide users to the right options, enhancing their experience.</p><h3>Unleash VIP Offers</h3><p>Unlocking VIP offers can be complex, but Offer Groups simplify the process. They ensure the right customers have access to exclusive services.</p><h3>Completing With Free Subscriptions</h3><p>Include free subscriptions to gather user emails and connect with them through irresistible offers. This is a strategic move for engaging your customer base.</p><p>This guide provides a concise overview of creating a successful subscription offer ecosystem, offering practical advice for businesses looking to attract and retain customers effectively. It uses the concepts introduced by the node.js library <a href="https://github.com/ziedHamdi/UserCredits">user-credits</a> available on <a href="https://www.npmjs.com/package/user-credits">npm </a>and its SvelteKit based implementation <a href="https://github.com/ziedHamdi/svelte-user-credits">svelte-user-credits</a>.</p><blockquote>Please be aware that as of writing this article, the library is in its alpha release, and it’s expected that many concepts will undergo further development. You’re welcome to participate and contribute to the ongoing initiative to enhance it.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obCD-6dG113xn99ULT5DbA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jessevanvliet?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Jesse van Vliet</a> on <a href="https://unsplash.com/photos/person-in-black-and-white-diving-suit-wearing-goggles-_8b7AW-p3Js?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><blockquote>In the ever-evolving landscape of tech startups, one thing remains constant: the race to attract and retain customers. Imagine a startup, let’s call it WonderAI, embarking on this very journey. WonderAI’s vision is clear — they aim to entice their first customers, those early adopters who can help pave the way for success. To achieve this, they’ve carefully crafted a set of offers designed to captivate their target audience.</blockquote><p>WonderAI’s core offerings are divided into three categories:</p><p>— <strong>Startup: </strong>Designed for budding entrepreneurs and startups looking to get their feet wet in the world of AI.</p><p>— <strong>Business:</strong> Tailored for established startups that have found their footing and are ready to take their AI ventures to the next level.</p><p>— <strong>Scale-up:</strong> The top-tier subscription, reserved for rapidly growing startups looking to make a global impact.</p><blockquote>However, WonderAI isn’t content with just these offerings. They’ve hatched a brilliant strategy to sweeten the deal for their early adopters, whom they affectionately refer to as “Early Birds.</blockquote><p>What sets WonderAI’s approach apart is its willingness to not only lower the prices of its core offers for Early Birds, but also to unlock a world of VIP benefits. These premium perks, including opportunities to showcase their businesses on the WonderAI platform and speak at prestigious WonderAI conferences, are typically reserved for <strong>Scale-up</strong> subscribers. However, Early Birds get special treatment, gaining access to these VIP offerings even with the “<strong>Startup</strong>” and “<strong>Business</strong>” packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFjHptq9JOIA2ahzJTJZ7Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@neom?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">NEOM</a> on <a href="https://unsplash.com/photos/a-person-swimming-in-the-ocean-near-a-coral-reef-g_suks3yx-U?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>This article will delve into the intricacies of creating and managing such a versatile and enticing offer ecosystem. We’ll explore the key components of this approach and the utility methods within our library that enable businesses like WonderAI to structure and maintain their offerings efficiently.</p><blockquote>Join us on this journey to understand how to organize your very own offer ecosystem, leverage the power of different fields within our comprehensive interface, and harness utility methods to streamline the management of your subscription services. Whether you’re a startup, an established business, or a fast-growing enterprise, these insights will empower you to tailor your offers to the right audience, just like WonderAI.</blockquote><blockquote>Like many startups, WonderAI provides a range of subscription offers, but let’s focus on the core concepts for now. We’ll delve into adding free trials and basic services towards the end of this article once we’ve got a solid grasp of these fundamental principles.</blockquote><h3>Offer Groups</h3><p>WonderAI, much like its startup counterparts, wants to offer its users the flexibility to pay on a monthly or yearly basis, with the added benefit of cost savings for annual subscriptions (for instance, getting two months free with a yearly subscription). So, our three primary offers, “<strong>Startup</strong>,” “<strong>Business</strong>,” and “<strong>ScaleUp</strong>,” come in <strong><em>four </em></strong>different flavors:</p><p>— “<strong>EarlyBird</strong>” (offering both <strong>monthly </strong>and <strong>yearly </strong>options) and</p><p>— “<strong>Standard</strong>” (with <strong>monthly </strong>and <strong>yearly </strong>plans).</p><p>Now, here’s where things get interesting, and it might not be immediately apparent to users, but it’s crucial for us when writing the code for these offers. Imagine a scenario where a “<strong>Standard</strong>” subscriber initially opts for three months of the “<strong>Startup</strong>” offer and later decides to upgrade to a one-year “<strong>Startup</strong>” subscription. In this case, the expiry date for that annual subscription must <strong>build upon the existing three months</strong> they’ve already purchased.</p><p>However, if the user is still within the initial three months of the “<strong>Startup</strong>” subscription and decides to purchase a “<strong>Business</strong>” offer, these purchases must be handled separately. This doesn’t just pertain to triggering a refund for the remaining “<strong>Startup</strong>” subscription; it’s about managing the “<strong>Startup</strong>” subscriptions for <strong>yearly </strong>and <strong>monthly </strong>plans in a way that they are somehow interconnected. We call this grouping of offers an ‘offer group.’</p><p>Now, let’s talk about the <strong>Early Bird</strong> subscriptions. These can be enticing lifetime offers, but they may also have a time limit, such as <strong>‘get 50% off for three years.’</strong> Depending on the developer’s choice, the Early Bird offers may or may not belong to the same ‘offer group’ as their ‘Standard’ counterparts. This decision provides flexibility and control in how these offers are managed.</p><blockquote>In essence, this “<strong>offer group”</strong> distinction provides developers with the ability to tailor their offerings to cater to different customer segments, allowing a finer level of control over how <strong>Early Bird</strong> deals are integrated into their <strong>subscription </strong>framework. It’s a dynamic approach that aligns with the unique requirements and strategies of each platform or service.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJxS2cndgdzSJqqGFBz-qw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@neom?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">NEOM</a> on <a href="https://unsplash.com/photos/a-scuba-diver-swims-over-a-colorful-coral-reef-_tDdlCJIwOA?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Token Management</h3><p>As we dive deeper into the world of subscription offers, it becomes evident that ‘<strong>Offer Groups</strong>’ serve as a fundamental framework for managing the intricacies of subscription services, particularly in the context of AI and SaaS companies. These businesses often offer <strong>pay-as-you-go</strong> models where users purchase a predefined set of credits or <strong>tokens</strong>, each representing a unit of service consumption, much like buying tickets at an amusement park.</p><p>Consider the scenario at WonderAI, where they provide customers the opportunity to book conference speaker talks (talking about their company at the same time). A user may choose to purchase a single talk for 1000$, represented as <strong>1 token</strong>, or opt for a bundle of three talks at 2000$, denoted as <strong>3 tokens</strong>. The versatility of this system allows customers to not only buy multiple instances of a one-token offer but also combine various token packages. In such cases, it is essential that these token offers are <strong>grouped together</strong>, which brings us back to the concept of <strong>Offer Groups</strong>.</p><blockquote><em>If for instance, a ‘</em><strong><em>Startup</em></strong><em>’ customer that has 2 tokens remaining in their credits decides to upgrade to the ‘</em><strong><em>Business</em></strong><em>’ plan, subsequently purchasing an additional token. The question arises: </em>should all these tokens fall under the same basket, or should they remain separate?<em> The answer, as you might have guessed, is: </em><strong><em>it depends</em></strong><em>. In practice, it’s often more efficient to keep each ‘</em><strong><em>token</em></strong><em>’ offer within its respective </em><strong><em>“offer group order”</em></strong><em> and to search for available </em><strong><em>tokens</em></strong><em> across all active subscriptions. This approach permits a more flexible and organized way to manage token-based services while ensuring that </em><strong><em>tokens</em></strong><em> with closer </em><strong><em>expiry dates</em></strong><em> are prioritized. We start to see the reason why a dedicated library to manage all this could save us time and pain.</em></blockquote><h4>Takeaways about offer groups</h4><p>In the evolving landscape of subscription offerings, comprehending the role of ‘<strong>Offer Groups</strong>’ empowers businesses to construct tailored subscription models that align with their unique strategies and user experiences. This level of customization not only simplifies subscription management but also enriches the user’s journey, making it a win-win-win situation for developers, companies and customers.</p><h3>Functional Tags</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9BqVoo4jH_cmm1YsEEUnFg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@spensersembrat?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Spenser Sembrat</a> on <a href="https://unsplash.com/photos/a-large-body-of-water-with-a-sky-background-iyUKO_NjObM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In our intricate world of subscription offers, where concepts like <strong>Offer Groups</strong>, <strong>Tokens</strong>, and <strong>Startup Offers</strong> play pivotal roles, another crucial element comes into play: <strong>Functional Tags</strong>. These are not your typical tags visible to users but rather have a specific function, guiding the system’s behavior.</p><blockquote><em>So far, we’ve laid the foundation with six </em><strong><em>Offer Groups</em></strong><em>, thoughtfully organized as two sets of three: “</em><strong><em>Startup</em></strong><em>,” “</em><strong><em>Business</em></strong><em>,” and “</em><strong><em>ScaleUp</em></strong><em>” offers groups for each of “</em><strong><em>Standard</em></strong><em>” and “</em><strong><em>Early Bird</em></strong><em>”, and each housing both </em><strong><em>monthly</em></strong><em> and </em><strong><em>yearly</em></strong><em> subscription options. So a total of twelve basic offers. As you can see, the complexity is growing.</em></blockquote><p>Now, let’s tackle the challenge of displaying the right offers to our users. We don’t want to overwhelm them with all options at once, and we need to differentiate between “<strong>Early Bird</strong>” and “<strong>Standard</strong>” offers based on the user’s status, perhaps through an invitation link or a specific <strong><em>end-of-happy-days date</em></strong>. Moreover, displaying both <strong>monthly</strong> and <strong>yearly</strong> subscriptions simultaneously may not be ideal. Users usually prefer a clean interface with a switch to toggle between subscription durations, with a message highlighting the yearly subscription’s advantages, such as “two months free”.</p><p>Functional <strong>Tags</strong> come to the rescue here. We can begin by tagging all our subscription offers with the label “<strong>subscription</strong>”. This sets them apart from other types of <strong>offers</strong>. Now, remember, we haven’t even delved into the exclusive <strong>VIP</strong> offers yet, available only to “<strong>ScaleUp</strong>” subscribers in the “<strong>Standard</strong>” scenario but accessible to all “<strong>Early Bird</strong>” subscribers. These six core offers can all bear the “<strong>subscription</strong>” tag, distinguishing them.</p><p>However, we still have 12 offers to manage, and we need to further categorize them. Six can be marked with the “<strong>monthly</strong>” tag, while the remaining six get tagged as “<strong>yearly</strong>,” indicating yearly subscriptions. This results in two sets of six offers each. To refine the selection, we add the tags “<strong>Standard</strong>” and “<strong>Early Bird</strong>,” creating four distinct combinations: “Standard Monthly,” “Early Bird Monthly,” “Standard Yearly,” and “Early Bird Yearly.”</p><h4>Takeaways about Tags</h4><p>Now, the user environment, influenced by their status, will determine whether to display “<strong>Early Bird</strong>” or “<strong>Standard” offers</strong>. Then, the switch on the display page lets users toggle between “<strong>Monthly</strong>” and “<strong>Yearly</strong>” subscriptions. The power of <strong>Functional Tags</strong> lies in their role as filters, streamlining the offers presented to users. They don’t carry hidden functionalities like <strong>Offer Groups</strong>, which influence expiry dates and token counts, making them a valuable tool for effective offer presentation.</p><blockquote><em>In the complex world of subscription offers, maintaining a streamlined and efficient system is essential. That’s where a dedicated library for handling various aspects of offers, like </em><strong><em>Functional Tags</em></strong><em>, proves invaluable.</em></blockquote><p>Now, let’s dive into a more intricate topic: <strong>Offer Unlocking</strong>.</p><h3>Unleashing Exclusive VIP Offers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qjZi_4YDmLnIxgaXiCaXA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@spensersembrat?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Spenser Sembrat</a> on <a href="https://unsplash.com/photos/a-large-body-of-water-with-a-sky-background-iyUKO_NjObM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In the <strong>Standard</strong> section, the process of unlocking <strong>VIP</strong> offers for “<strong>ScaleUp</strong>” subscribers might initially appear straightforward. One might think of designating an offer as a child of the “<strong>ScaleUp</strong>” subscriptions, ensuring that subscribers to these offers gain access to the VIP service. However, a complication arises. We provide two variations of “<strong>ScaleUp</strong>” subscriptions: <strong>monthly</strong> and <strong>yearly</strong> plans. An even bigger issue is that we desire the same <strong>VIP</strong> offer to be accessible to other offer groups in the “<strong>EarlyBird</strong>” section.</p><blockquote>How can we achieve this?</blockquote><p>To tackle this challenge, we harness the <strong>unlockedBy</strong> field. Instead of creating child offers (as our initial intuition might suggest), we precisely specify, for each <strong>VIP offer</strong>, the particular <strong>offerGroup</strong>(s) it is unlocked by.</p><p>The “<strong>unlockedBy</strong>” field proves to be a versatile solution that enhances the management and accessibility of <strong>related services</strong> across different subscription types. Even if we refer to the unlocked offers as <strong>sub-offers</strong>, it’s more accurate to think of them as “<strong>unlocked by</strong>”. We are usually confined to having only two parents, and in the programming world, it’s even worse: we have only one parent (or one-to-many relationships). Using the term “<strong>parentOfferGroups</strong>” (as initially in the library) would have been misleading as it holds a potentially long list of parents.</p><h4>Offer Group Sub-Offers</h4><p>Within the “<strong>EarlyBird</strong>” section, identified by the “<strong>Eb</strong>” prefix, we showcase a <strong>VIP offer</strong> named “<strong>EventTalk</strong>”. This offer can be unlocked by purchasing an offer from one of the three offer groups: “<strong>EbStartup</strong>,” “<strong>EbBusiness</strong>,” and “<strong>EbScaleUp</strong>” within the “<strong>EarlyBird</strong>” section. Moreover, it can also be unlocked by the “<strong>ScaleUp</strong>” offer in the “<strong>Standard</strong>” section, as we discussed earlier. To achieve this high degree of flexibility, we once again make use of the unlockedBy field.</p><p>The EventTalk.unlockedBy field now contains an array of strings: [&quot;EbStartup&quot;, &quot;EbBusiness&quot;, &quot;EbScaleUp&quot;, &quot;ScaleUp&quot;]. This setup enables us to create a single offer that can be unlocked by purchasing offers from different sections, seamlessly bridging the gap between the &quot;<strong>EarlyBird</strong>&quot; and &quot;<strong>Standard</strong>&quot; sections.</p><p><strong>At this point, a question may arise:</strong></p><p>when the order creation method is called, should we allow a locked offer to be purchased (even if the user didn’t unlock it)? The short answer is “Yes”:</p><p>Unlocking offers may happen in various different ways: one of them is by purchasing a “releasing offer”, but it might also be through a special ‘coupon’ or through another constraint you defined in your app. So as mentioned at the start of the article, the library presumes you made all necessary checks before calling a method: it relies on you for all authorization routines. So you will have to check if a user unlocked an offer in your code if hierarchy is the only way to unlock an offer in your use case.</p><blockquote>This approach streamlines our offer hierarchy and ensures that an offer can be associated with multiple <strong>unlocking offers</strong> (don’t think <strong>parent offers</strong> <em>😄</em>). <br>It’s a powerful and versatile solution that enhances the management and organization of offers within the library.</blockquote><h3>Completing With Free Subscriptions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LZ3ZbVu-BRLUo84j8opPQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dnmgns?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Magnus Lindvall</a> on <a href="https://unsplash.com/photos/photography-of-sea-and-rocks-kRpYCajakTU?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Now, let’s discuss how to incorporate a free subscription offer into the mix. This is a strategic move for WonderAI to gather user emails and connect with them through compelling irresistible offers.</p><p>The free subscription offer comes with three essential tags: “subscription,” “monthly,” and “yearly.” If the perks for early adopters align with those of “standard” customers, it’s possible to include a fourth tag, “earlybird.” This tag ensures that you can locate the free subscription offer in any query that searches for root offers. However, for better organization as your customer base grows, it’s recommended to create a separate offer exclusively for “Early Birds.” This approach facilitates easy management and access, particularly as your customer numbers increase, which is something I wish for you now that you know how to serve them well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21cb8d9f162d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>