Skip to content

Latest commit

 

History

History
471 lines (377 loc) · 18.9 KB

PACKAGE_SPEC.md

File metadata and controls

471 lines (377 loc) · 18.9 KB

@stackverify/ui SDK package spec

Status: phase 1 foundation and phase 2/3 wiring are implemented in this SDK repository. The platform API is additive and is implemented separately.

1. Goal

@stackverify/ui is a standalone SDK and CLI that lets a seller define a storefront design in JSON, download approved UI blocks from StackVerify, and run that storefront anywhere while StackVerify remains the backend for store context, search and checkout.

The package lives in /home/jackal/stackverify-ui. The platform remains in /home/jackal/stack-verify.v2 and is treated as read-only for this phase.

The public command names are:

npx @stackverify/ui init
npx stackverify dev
npx stackverify build
npx stackverify start

The stackverify binary is exposed by @stackverify/ui, so after local install, npx stackverify dev works inside a generated storefront project.

2. Current platform facts

The SDK must not assume endpoints that do not exist.

  • The current storefront is server-rendered from loadStorefront in apps/web/src/server/commerce/storefront.ts:106. The public shape is Storefront and StoreProduct in the same file at :27 and :43.
  • Checkout is a Next.js server action at apps/web/src/app/[slug]/actions.ts:37. It prices the order on the server and returns a one-order HMAC token.
  • Dashboard APIs under apps/web/src/app/api/dashboard/** use Better Auth cookies and active organization membership, guarded by apps/web/src/app/api/dashboard/_guard.ts:21. They are not public SDK APIs and have no general CORS support.
  • MCP at apps/web/src/app/api/mcp/route.ts:60 only supports four skin tools. Its tools are listed in apps/web/src/server/ai-mcp/mcp.ts:99. It cannot read products, orders, customers, payments or files.
  • There is no public catalog API, no public checkout REST API, no block registry endpoint and no general API-key auth today.
  • The current composition contract maps sections to trusted React components in apps/web/src/components/storefront/composed-storefront.tsx:361. There is no portable block source registry yet.
  • The current skin contract is strict and versioned in packages/core/src/storefront-skin-contract.ts:4. It rejects raw HTML, CSS strings, scripts, iframes and arbitrary URLs.
  • Brand and storefront rules are in docs/brand.md:185. The public store belongs to the business, not StackVerify. Storefronts keep the report link and do not carry StackVerify legal footer copy.

Because of these facts, the SDK does not call legacy dashboard or server action endpoints. It targets the additive /api/sdk/v1 contract below. The platform implementation lives in the separate platform repository and is not owned by this SDK.

3. Non-negotiables

  1. Do not modify /home/jackal/stack-verify.v2 in phase 1.
  2. Do not change the existing skin contract, MCP tools, storefront renderer, checkout server action or dashboard APIs.
  3. Any future platform API is additive, versioned under /api/sdk/v1, tenant scoped and approved through an ADR before implementation.
  4. JSON contains descriptors and validated tokens only. It never contains raw HTML, CSS, JavaScript, scripts, iframes, unvalidated URLs or arbitrary imports.
  5. Blocks are platform-owned, versioned and reviewed. The SDK downloads only block ids present in the user's JSON and verifies locked hashes.
  6. The browser never receives the secret API key. Checkout and other write calls go through a server-side proxy generated by the SDK.
  7. Prices are never trusted from the generated frontend. The platform server prices every order from product ids and quantities.
  8. Demo stores must never trigger real WhatsApp sends, M-Pesa requests or customer emails. The platform continues to own that behavior.

4. Package layout

Target repository: /home/jackal/stackverify-ui

Recommended monorepo shape:

/home/jackal/stackverify-ui
  package.json
  pnpm-workspace.yaml
  tsconfig.base.json
  packages/
    cli/
      package.json
      src/
        bin.ts
        commands/
          init.ts
          dev.ts
          build.ts
          start.ts
          sync.ts
        config/
          manifest.ts
          lock.ts
          env.ts
        platform/
          client.ts
          blocks.ts
          context.ts
          checkout.ts
        generator/
          app.ts
          routes.ts
          imports.ts
      test/
    runtime/
      package.json
      src/
        context-client.ts
        checkout-client.ts
        tokens.ts
        types.ts
      test/
    adapters/
      package.json
      src/
        vite-react.ts
        next-app-router.ts
        node.ts
        vercel.ts
        render.ts
  templates/
    vite-react-ts/
      base files used by `init --target vite-react`
    next-app-router/
      base files used by `init --target next`
    node/
      Node.js server wrapper used by `init --target node`

Package boundaries:

  • @stackverify/ui is the published npm package name and CLI entry.
  • packages/cli is internal source bundled into the published package.
  • packages/runtime is bundled into the CLI and copied into generated frontends.
  • packages/adapters contains small server proxy implementations for Vite React, Next.js App Router, Vercel, Node.js and Render.com, bundled into the CLI.
  • The generated app imports runtime helpers, never CLI code.
  • A target describes the frontend framework. A host adapter describes where that target runs. Vite React and Next.js both run on Vercel. Node.js and Next.js both run on Render.com.

5. User JSON manifest

Initial file: store.json.

The manifest is a design descriptor. It is not a full application source file.

Recommended v1 shape:

{
  "version": 1,
  "store": {
    "slug": "zawadi"
  },
  "skin": {
    "version": 1,
    "tokens": {},
    "layout": {},
    "composition": {},
    "media": {},
    "visibility": {}
  },
  "blocks": [
    {
      "id": "header.simple",
      "version": "1.0.0",
      "slot": "top",
      "props": {},
      "data": {}
    },
    {
      "id": "product-grid.catalogue",
      "version": "1.0.0",
      "slot": "main",
      "props": {},
      "data": {
        "source": "products",
        "where": { "status": "active" },
        "limit": 12
      }
    },
    {
      "id": "checkout.sheet",
      "version": "1.0.0",
      "slot": "overlay",
      "props": {},
      "data": {}
    }
  ],
  "routing": {
    "home": "/",
    "product": "/product/:id",
    "search": "/search?q=:query"
  }
}

Manifest rules:

  • version must be 1.
  • store.slug identifies the platform store. No business id or tenant id is accepted.
  • skin uses the current public skin contract shape where applicable. The CLI revalidates it before any download.
  • blocks contains platform block ids and semver versions only. The user cannot provide file paths, package names, URLs or source text.
  • props are validated against the block schema returned by the platform registry.
  • data uses approved context queries only. It can ask for store details, products, categories, featured products or search results. It cannot ask for customers, orders, chats, payments, admin data or other tenants.
  • routing contains app paths only. It cannot set API endpoints or external URLs.

6. Lock file

stackverify.lock.json is generated by dev and sync and should be committed.

It pins:

  • Platform API contract version.
  • Skin contract version.
  • Every resolved block id, version, file list and SHA-256 digest.
  • Resolved context query schemas.
  • Generated app version.

Generated block source goes into .stackverify/blocks/ and is gitignored. start recreates it from the lock file when missing.

7. CLI commands

npx @stackverify/ui init [name]

  • Creates the project folder from templates/vite-react-ts.
  • Writes store.json with a valid starter manifest.
  • Writes .env.example only. Never writes a real key into tracked files.
  • Adds .gitignore entries for .env*, .stackverify/ and build output.
  • Does not call the platform unless the user passes --slug.

npx stackverify dev

  • Loads .env.local, then store.json.
  • Validates the manifest locally with strict zod schemas.
  • Fetches the public platform contract and block metadata using the CLI API key.
  • Downloads only blocks referenced by the manifest.
  • Verifies every block against stackverify.lock.json.
  • Generates React entry files, imports, token CSS and server proxy stubs.
  • Starts a local Vite dev server and a local proxy for context and checkout calls.
  • Watches the manifest. On change it validates, resolves new blocks and hot reloads.

npx stackverify build

  • Runs the same validation and generation as dev.
  • Builds static assets.
  • Never embeds the secret API key in client bundles.
  • Emits host adapter files according to stackverify.config.json.

npx stackverify start

  • Checks lock file integrity.
  • Downloads missing blocks if allowed by env.
  • Starts the generated frontend plus its server proxy.
  • Fails clearly if a secret key is missing for endpoints that require it.

npx stackverify sync

  • Refreshes the contract and block metadata.
  • Updates stackverify.lock.json.
  • Reports breaking changes instead of silently rewriting user JSON.

8. Additive platform API

These endpoints are the phase 2 platform contract. Phase 3 SDK wiring uses them exactly.

Auth

  • Publishable keys start with svsdk_pub_ and secret keys start with svsdk_sec_.
  • Keys are store scoped and scope limited:
    • blocks:read
    • storefront:read
    • checkout:write
    • payments:write later if needed
  • Store only the SHA-256 hash of each key.
  • Rate limit by key hash and store id.
  • No key creation by the CLI. Owners create keys in the dashboard after the dashboard feature is built.
  • Local development may use a short-lived development key issued by an explicit dev-only script.

Block registry

GET /api/sdk/v1/contract
GET /api/sdk/v1/blocks
GET /api/sdk/v1/blocks/:id@:version

A block response contains:

{
  "id": "product-grid.catalogue",
  "version": "1.0.0",
  "entry": "index.tsx",
  "files": [
    { "path": "index.tsx", "sha256": "...", "content": "..." }
  ],
  "propsSchema": {},
  "requiredContext": ["products"],
  "capabilities": ["products", "links", "themeTokens"],
  "sha256": "..."
}

Registry rules:

  • Blocks are authored and reviewed on the platform side.
  • The SDK never downloads arbitrary source paths.
  • Block source uses only generated imports and platform runtime helpers.
  • A block cannot import server code, env, database helpers, admin helpers or another tenant's data.
  • A block cannot render raw HTML strings or inline script.

Storefront context

GET /api/sdk/v1/storefronts/:slug/context
GET /api/sdk/v1/storefronts/:slug/search?q=...

Response data is the public storefront subset:

  • Store name, slug, logo, cover, theme color, pickup and delivery settings.
  • Active categories.
  • Active products with server-authored display fields.
  • Featured products.
  • Search results by product name and category name.
  • Available block metadata for design tools.
  • Safe payment method flags.

No prices are trusted for checkout from these reads. Display prices may be returned for UI only, and checkout recalculates them.

Checkout

POST /api/sdk/v1/storefronts/:slug/checkout

The request mirrors checkoutInputSchema in packages/core/src/commerce.ts:54:

  • Items as { productId, quantity } with quantity from 1 to 99.
  • Customer name and phone.
  • fulfillment as pickup or delivery, with address required for delivery.
  • paymentChoice as pay_now or on_delivery, default pay_now.
  • Optional note, booking, visitor, session and source fields.
  • Required Idempotency-Key header. The CLI and generated runtime generate one when absent.

The platform returns { ok, orderId, token, orderNumber, totalMinor, depositMinor, scheduledFor, whatsappUrl, message } on success. Failures return { ok: false, message, fieldErrors? }. The SDK validates every response with zod and maps field errors through the server proxy.

The platform:

  • Validates with zod.
  • Enforces rate limits.
  • Prices on the server.
  • Creates the order through existing tenant-scoped services.
  • Returns the one-order token and next payment instructions.
  • Uses fake adapters for demo businesses.

Payment claim and M-Pesa prompt endpoints are phase 3 and must reuse the existing guards in apps/web/src/app/[slug]/actions.ts:77 and :126.

9. Generated frontend runtime

Supported frontend targets:

  • vite-react: Vite + React + TypeScript. Small generated app, fast local dev, static assets plus a small Node API server for production.
  • next: Next.js App Router + React + TypeScript. Route handlers provide the same-origin API proxy.
  • node: Vite React frontend plus a plain Node.js HTTP server. This target is for Render.com and other Node hosts that want explicit control of the server.

All targets use the same manifest, lock file, downloaded blocks, runtime helpers and token CSS. The target only changes the app shell, build command and server proxy files.

The generated app has this shared shape:

src/
  generated/
    App.tsx                 generated from JSON
    blocks/                 downloaded from lock file
    context.json            generated initial store context
    runtime.ts              context and checkout helpers
    server/
      platform.mjs          server-only platform proxy helper
      platform.d.mts        proxy helper types
    tokens.css              generated from validated skin tokens
  main.tsx                  vite-react and node targets
server/
  index.mjs                 node and vite-react production API server
api/
  context.mjs               Vercel function
  checkout.mjs              Vercel function
app/
  page.tsx                  next target
  api/stackverify/context/route.ts
  api/stackverify/checkout/route.ts
.env.example

Browser behavior:

  • Loads safe context from same-origin proxy routes.
  • Renders only downloaded, locked, trusted blocks.
  • Sends checkout input to same-origin proxy routes.
  • Uses the skin token CSS variables.
  • Keeps the report link and business-owned footer rules.

Server proxy behavior:

  • src/generated/server/platform.mjs reads the store slug from store.json.
  • It reads env from process.env with .env.local fallback.
  • It uses fixtures when STACKVERIFY_FIXTURES is on or keys are missing.
  • It injects the secret API key only in the checkout call.
  • It forwards only validated paths and bodies.
  • It adds timeouts and error mapping.
  • It never logs keys, raw customer phone numbers beyond normal platform logging rules, or full request bodies.
  • Generated browser code never imports this helper.

Hosting matrix:

  1. Vercel: vite-react target with generated api/ functions, or next target with App Router route handlers.
  2. Render.com: next target with npm start, or node target with the plain Node.js HTTP server.
  3. Any Node host: vite-react and node targets both include server/index.mjs.
  4. Static-only hosting: allowed only if the platform later provides a publishable read key and a host approved checkout proxy. Secret checkout key must never be bundled into static assets.

10. Data safety rules

  • The SDK never reads platform database tables directly.
  • The SDK never imports platform source files from /home/jackal/stack-verify.v2.
  • The generated frontend never receives cross-tenant data.
  • API errors are shown as short owner-friendly messages. Internal paths, SQL, env names and stack traces are never exposed.
  • Context queries cannot ask for admin data, chats, orders, customers, users, files or other businesses.
  • Block props cannot use dangerouslySetInnerHTML, raw style strings, remote CSS, arbitrary URLs or dynamic component construction.
  • Theme application uses tokens only. No hardcoded hex values in blocks.
  • Keep layouts light, phone first and readable. No dark pages, glass cards, frosted panels, heavy shadows or gradients.

11. Phase plan

Phase 0, current state

  • Write this spec only.
  • Do not touch the platform repo.
  • Do not scaffold code until the spec is approved.

Phase 1, standalone SDK foundation

  • Scaffold /home/jackal/stackverify-ui.
  • Build manifest validation, lock file handling, API client interfaces and fake platform fixtures.
  • Build init --target vite-react, init --target next and init --target node.
  • Build sync, dev, build and start against fixtures for each target.
  • Add Vercel function files for vite-react and next route handler files for next.
  • Add a plain Node.js server for node and vite-react production hosting, suitable for Render.com.
  • Add tests for validation, lock integrity, generated imports, all three targets and secret key isolation.
  • No platform API changes.

Phase 2, additive platform API

  • Write an ADR in the platform repo before code changes.
  • Add /api/sdk/v1 routes with zod validation, API-key auth, CORS only where needed and rate limits.
  • Add API key creation and revocation in the dashboard.
  • Add docs and database schema updates for API keys if a new table is needed.
  • Reuse existing tenant-scoped services. Do not duplicate business logic.
  • SDK status: the client targets the exact contract in section 8 and validates every response.

Phase 3, real SDK connection and checkout

  • Point the SDK at real block and context endpoints.
  • Add checkout through server proxy adapters.
  • Add payment claim and M-Pesa prompt calls only if approved and covered by tests.
  • Add end-to-end tests with a demo store.
  • SDK status: contract, blocks, context, search and checkout are wired. Fixtures remain a documented fallback. Idempotency and server-only keys are covered by tests.

Phase 4, hosting adapters

  • Add and verify Node, Vercel, Netlify and Cloudflare Workers examples.
  • Document static-only limits.
  • Add release workflow for npx @stackverify/ui.

12. Definition of done for phase 1

  • The repository exists only at /home/jackal/stackverify-ui.
  • git status in /home/jackal/stack-verify.v2 stays clean.
  • The CLI validates invalid manifests with clear errors.
  • The CLI resolves blocks from a fake registry and writes a deterministic lock file.
  • The generated app renders from JSON using downloaded fake blocks.
  • Generated vite-react, next and node projects each contain the correct app shell and server proxy files.
  • Generated projects include Vercel or Render.com deployment files where relevant.
  • No secret key appears in generated browser bundles.
  • Unit tests, typecheck and lint pass in the SDK repo.

13. Decisions applied to scaffolding

  1. First generated app targets are vite-react, next and node.
  2. Key types are a publishable read key and a secret checkout key.
  3. First block set is header, search bar, hero, category strip, featured grid, catalogue grid, product detail, about, footer and checkout sheet.
  4. Phase 1 started with fixtures. Phase 3 adds the real platform API with a fixtures fallback.
  5. Generated block source is gitignored, with the lock file committed.
  6. store.json remains the file users own. Generated files are rebuilt with stackverify sync.