import { verifyZamRequest } from "zam-verify";
// --- Configuration ---
const SERVICE_NAME = "My Translation Service";
const SERVICE_DESCRIPTION = "Translates text between languages.";
const PRICE_AMOUNT_CENTS = 50;
const INPUT_SCHEMA = {
type: "object",
properties: {
text: { type: "string" },
targetLanguage: { type: "string" },
},
required: ["text", "targetLanguage"],
};
const OUTPUT_SCHEMA = {
type: "object",
properties: {
translated: { type: "string" },
},
};
// --- Contract ---
function buildContract(baseUrl: string) {
return {
provider: {
title: SERVICE_NAME,
description: SERVICE_DESCRIPTION,
category: "data",
tags: ["translation", "language"],
price: { currency: "USD", amountCents: PRICE_AMOUNT_CENTS, unit: "call" },
runContract: {
method: "POST",
endpointPath: `${baseUrl}/run`,
healthEndpoint: `${baseUrl}/health`,
inputSchema: INPUT_SCHEMA,
outputSchema: OUTPUT_SCHEMA,
},
},
};
}
// --- Business logic ---
async function handleRun(body: unknown): Promise<object> {
const { text, targetLanguage } = body as { text: string; targetLanguage: string };
// Your implementation here
return { translated: `[${targetLanguage}] ${text}` };
}
// --- Worker ---
interface Env {
ZAM_SIGNING_SECRET?: string;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
const baseUrl = `${url.protocol}//${url.host}`;
const headers = {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
};
if (url.pathname === "/" && request.method === "GET") {
return new Response(
JSON.stringify({ name: SERVICE_NAME, description: SERVICE_DESCRIPTION }),
{ headers }
);
}
if (url.pathname === "/contract" && request.method === "GET") {
return new Response(JSON.stringify(buildContract(baseUrl)), { headers });
}
if (url.pathname === "/health" && request.method === "GET") {
return new Response(JSON.stringify({ status: "healthy" }), { headers });
}
if (url.pathname === "/run") {
// HEAD/GET must return 200 — ZAM checks endpoint reachability during review
if (request.method === "HEAD" || request.method === "GET") {
return new Response(null, { status: 200, headers });
}
// Verify the request came from ZAM (skip in local dev if no secret is set)
const body = await request.text();
if (env.ZAM_SIGNING_SECRET) {
const signature = request.headers.get("X-ZAM-Signature");
const payload = request.headers.get("X-ZAM-Payload");
if (!signature || !payload) {
return new Response(JSON.stringify({ error: "Missing ZAM headers" }), {
status: 401, headers,
});
}
const result = verifyZamRequest({
signature,
payload,
body,
signingSecret: env.ZAM_SIGNING_SECRET,
});
if (!result.valid) {
return new Response(JSON.stringify({ error: result.error }), {
status: 401, headers,
});
}
}
const input = JSON.parse(body);
const result = await handleRun(input);
return new Response(JSON.stringify(result), { headers });
}
return new Response(JSON.stringify({ error: "Not found" }), {
status: 404,
headers,
});
},
} satisfies ExportedHandler<Env>;