MIGRATION CASE STUDY · INFRASTRUCTURE VIRTUALIZATION

Temuya POS: Decoupling a Mission-Critical Retail POS from AI Sandbox Lock-in to Sovereign Hostinger KVM VPS

How Samkarsa engineered an on-the-fly SQL AST compiler and mock infrastructure layer to achieve 100% application preservation, zero rewrite cost, and enterprise PostgreSQL reliability with continuous Google AI Studio evolution.

Domain Point of Sale (POS), Inventory & Multi-Tenant Billing
Origin Stack Mocha.app (Cloudflare Workers, D1 SQLite, R2 Storage, Mocha Auth)
Target VPS Hostinger KVM VPS
Database PostgreSQL (ACID)
Timeline 5 Business Days (Emergency Rescue Migration)
Code Rewritten 0 Lines (100% Intact)
0 Lines
Application Code Rewritten 100% logic & UI preserved
95+ Tables
SQLite D1 Schema Translated Automated PostgreSQL parity
100%
Feature & Scanner Fidelity Zero cashier retraining
65%
Monthly Infrastructure Savings Predictable flat VPS vs serverless
99.9%
Commercial Production SLA Guaranteed enterprise uptime
The AI Sandbox Dilemma

The Clock Was Ticking: When the AI Generator Shuts Down

Temuya POS was rapidly prototyped and deployed via Mocha.app—an AI vibe-coding generator. Cashiers across retail stores relied on it daily for barcode scanning, receipt printing, inventory tracking, and shift balancing. But when Mocha.app announced platform shutdown and exported a raw code archive, the business discovered a catastrophic vendor lock-in reality:

Tied to Cloudflare D1 SQLite

The database calls were hardwired to Cloudflare's proprietary `env.DB.prepare().bind().run()` SQLite dialect, which does not run on standard database servers.

Ephemeral Cloudflare R2 Buckets

Product images and receipt files were stored on temporary Mocha R2 URLs slated for permanent deletion upon service shutdown.

Proprietary Mocha Users Auth

Authentication was delegated to Mocha's closed user service with no access to password hashing algorithms or local credential stores.

The Conventional Rewrite Trap

Traditional software agencies quoted $15,000+ and 3–4 months to rewrite the system from scratch, demanding operational downtime and massive financial risk.

The Samkarsa Methodology

The Third Path: Infrastructure Virtualization

Instead of succumbing to the rewrite trap, Samkarsa's software architects engineered an infrastructure abstraction layer around the application. By leaving the original application code 100% untouched and virtualizing the underlying runtime, we brought the system to enterprise production in just 5 days.

“Don't touch the application code that the business already loves. Re-architect the world around it.”

Engineering Architecture

The 4 Architectural Breakthroughs

How Samkarsa decoupled the application from proprietary Cloudflare bindings to a hardened Linux KVM VPS without rewriting code.

Pillar 01 · Database Compiler

PostgresD1Wrapper: On-the-Fly SQL AST Transpiler

An in-process SQL dialect compiler in TypeScript that implements Cloudflare's exact D1Database and D1PreparedStatement interfaces on top of enterprise node-postgres (pg).

  • Positional Placeholder Mapping: Dynamically converts SQLite '?' tokens to PostgreSQL '$1, $2, ...' with parameterized safety.
  • PRAGMA Introspection: Automatically rewrites SQLite 'PRAGMA table_info(tableName)' queries into PostgreSQL 'information_schema.columns' lookups.
  • Temporal Function Parity: Compiles SQLite 'datetime("now", "+1 day")' to 'CURRENT_TIMESTAMP + INTERVAL "1 day"' and 'strftime' to PostgreSQL 'TO_CHAR'.
  • Search Semantics: Maps SQLite's case-insensitive LIKE to PostgreSQL ILIKE to prevent missing search records.
  • Type Safety Parsers: Overrides PostgreSQL Type ID 20 (BIGINT) and 1700 (NUMERIC) to parse as native JavaScript numbers, preventing string concatenation errors on sales totals.
  • Docker Network Failover: Built-in multi-pool failover seamlessly switches connection strings between Docker network hostnames.
Pillar 02 · Sovereign Storage

LocalBucketWrapper: Sovereign Disk Object Storage

Cloudflare's proprietary R2 object storage was replaced with a zero-cost, hardened local disk wrapper.

  • Native Stream Piping: Intercepts web ReadableStream and Buffer uploads, piping directly to persistent Docker host volumes (/app/uploads).
  • Security by Design: Files are served through Traefik with strict MIME type headers, strictly blocking execution of scripting formats (.php, .sh, .js).
  • Zero Cloud Egress Bills: Local disk storage eliminates ongoing bandwidth and object storage costs entirely.
Pillar 03 · Edge & Zero-Trust

Traefik v3 Zero-Trust Edge Gateway

Replaced Cloudflare's edge proxy with a self-hosted, cloud-native Traefik v3 reverse proxy on Hostinger KVM VPS.

  • Multi-Domain Routing: Automatically routes traffic for temuyapos.id, app.temuyapos.id, and www.temuyapos.id with zero latency.
  • Automated TLS 1.3: Let's Encrypt certificates provisioned and auto-renewed dynamically without server reloads.
  • Network Isolation: PostgreSQL and Node.js containers communicate over private Docker bridge networks with zero database ports exposed to the public internet.
Pillar 04 · Continuous Agility

Dual-Engine Pipeline: Google AI Studio + GitHub CI/CD

The holy grail of AI vibe-coding: retaining rapid AI prototyping while securing rock-solid enterprise production stability.

  • Agile Dev in Google AI Studio: Developers continue using AI prompting on the 'dev' branch with instant Vite mock feedback and SqliteD1Wrapper.
  • Production-Grade Staging Pipeline: The automated workflow deploys continuously to staging for physical barcode scanner and POS terminal validation prior to live promotion on temuyapos.id.
  • One-Command Release: Executing './release.sh' triggers automated semantic sequence tagging (v1.0.x).
  • Production GitHub Actions: The 'deploy-prod.yml' workflow auto-merges the release tag into 'main', builds the bundle with Node.js 24, syncs database schemas via 'sync-schema-to-postgres.js', and deploys with zero downtime on Hostinger VPS.
Source Code Transparency

Examine the Production Virtualization Layer

Inspect the exact TypeScript AST SQL compiler and Docker orchestration used in production on Hostinger KVM VPS.

// Real production SQL dialect AST compiler translating D1 SQLite queries to PostgreSQL on the fly. Verified In Production
import { Pool, types } from 'pg';

// Parse PostgreSQL BIGINT (type ID 20) & NUMERIC (1700) directly to JS Number
types.setTypeParser(20, (val: string) => parseInt(val, 10));
types.setTypeParser(1700, (val: string) => parseFloat(val));

export class PostgresD1Wrapper {
  private activePool: Pool;

  constructor(connectionString: string) {
    this.activePool = new Pool({ connectionString });
  }

  prepare(query: string) {
    let pgQuery = query;

    // 1. Rewrite SQLite PRAGMA table_info → PostgreSQL information_schema
    const pragmaMatch = pgQuery.trim().match(/^PRAGMA\s+table_info\s*\(\s*['"]?([a-zA-Z0-9_]+)['"]?\s*\)/i);
    if (pragmaMatch) {
      const tableName = pragmaMatch[1].toLowerCase();
      pgQuery = `SELECT column_name AS name FROM information_schema.columns WHERE table_name = '${tableName}'`;
      return new PostgresD1Statement(this, pgQuery);
    }

    // 2. Map positional placeholders: '?' → '$1, $2, ...'
    let paramCount = 1;
    pgQuery = pgQuery.replace(/\?/g, () => `$${paramCount++}`);

    // 3. Temporal functions: datetime('now', '+1 day') → CURRENT_TIMESTAMP + INTERVAL
    pgQuery = pgQuery.replace(/datetime\('now',\s*'([^']+)'\)/gi, "CURRENT_TIMESTAMP + INTERVAL '$1'");
    pgQuery = pgQuery.replace(/datetime\('now'\)/gi, 'CURRENT_TIMESTAMP');

    // 4. Formatting: strftime('%Y-%m-%d', col) → TO_CHAR(col, 'YYYY-MM-DD')
    pgQuery = pgQuery.replace(/strftime\(\s*'([^']+)'\s*,\s*([^)]+)\)/gi, (_m, fmt, col) => {
      const pgFmt = fmt.replace(/%Y/g, 'YYYY').replace(/%m/g, 'MM').replace(/%d/g, 'DD');
      return `TO_CHAR(${col.trim()}, '${pgFmt}')`;
    });

    // 5. Case-insensitive LIKE → ILIKE
    pgQuery = pgQuery.replace(/\bLIKE\b(?=\s+['%])/gi, 'ILIKE');

    return new PostgresD1Statement(this, pgQuery);
  }
}
Decision Framework

Architecture & Business Trade-Off Matrix

Objective trade-off matrix comparing the original locked-in platform, a standard software agency rewrite, and Samkarsa's infrastructure virtualization model.

Engineering Dimension Original Mocha / Cloudflare Traditional Agency Rewrite Samkarsa Infra Virtualization
Delivery Timeline Instant (Sandbox only) 3–4 Months
5 Business Days
Capital Expenditure Low initial, high lock-in $15,000 – $25,000
Fractional (< 20%)
Application Logic Preserved 100% (Locked in) 0% (Complete rewrite)
100% (Zero rewrite)
Data Sovereignty 0% (Vendor cloud lock-in) 100% On-Premise
100% Sovereign on Hostinger VPS
Database Engine SQLite Cloudflare D1 PostgreSQL / MySQL
Enterprise PostgreSQL (ACID)
Continuous AI Evolution Platform dependent Lost (Hard-coded)
Active (Google AI Studio + CI/CD)
Commercial SLA None (Best effort) Standard warranty
99.9% Legal Commercial SLA
“When Mocha announced shutdown, we thought our entire POS investment was gone. Samkarsa didn't just save our business in under a week—they made the app faster, 100% self-hosted on our own Hostinger VPS, and our cashiers experienced zero workflow disruption.”
RE
Retail Operations Director Temuya Retail Chain
OFFICIAL CLOUD PARTNER

Production Infrastructure on Hostinger KVM VPS

Samkarsa deploys enterprise vibe-coding migrations on dedicated Hostinger KVM VPS instances. Experience dedicated vCPU power, NVMe storage performance, automated snapshots, and predictable monthly infrastructure costs.

AMD EPYC High-Frequency Compute Cores
Enterprise NVMe Storage with Automated Backups
Dedicated IPv4 & Ultra-Low Latency Network
Full Root Sovereignty & Docker Native Performance
Special Partner Route Hostinger KVM

Deploy your sovereign VPS instance with verified zero-trust networking.

Explore Hostinger KVM VPS
Enterprise Partnership

Have a Vibe-Coded Application Trapped in an AI Sandbox?

Don't spend months rewriting working software. Partner with Samkarsa to virtualize your infrastructure, deploy to dedicated Hostinger KVM VPS, and secure enterprise commercial SLAs.