Restomenum eklenti platformu için resmi TypeScript SDK'sı. Webhook imza doğrulama, OAuth token exchange, tipli Callback API istemcisi, event/scope katalogu ve tipler — tek pakette. Node 20+ (global fetch), sıfır runtime bağımlılığı (yalnız node:crypto).
npm install @restomenum/plugin-sdk
SDK; manuel imza/HTTP yazımını ortadan kaldırır ve OAuth Connect, token exchange, webhook ve Data API sözleşmelerini tipli olarak sunar.
İmza ham gövde üzerinden doğrulanır (JSON.parse edilmiş değil), ±5 dk replay penceresi, timing-safe. Geçersizse 401 dön.
import { verifyWebhookSignature } from '@restomenum/plugin-sdk';
// Express (ham gövdeyi sakla: app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf } })))
const ok = verifyWebhookSignature(req.rawBody.toString('utf8'), req.headers['x-restomenum-signature'], webhookSecret);
if (!ok) return res.status(401).json({ error: 'invalid_signature' });Hazır Express middleware — imza + şekil doğrulamayı otomatik yapar:
import { expressWebhook } from '@restomenum/plugin-sdk';
app.post('/webhook', express.json({ verify: (req, _r, buf) => { (req as any).rawBody = buf; } }),
expressWebhook(
{ getSecret: (tenantId) => store.webhookSecretFor(tenantId) }, // senkron/async
async (envelope) => {
// imza + şekil doğrulandı; envelope = { id, type, version, environment, tenantId, occurredAt, data }
if (envelope.type === 'table.created') await handle(envelope.data);
// yanıt yazmazsan otomatik 200 { ok:true }
},
),
);Ayrıntı: İmza Şeması (HMAC) · /webhook Alıcı.
import { exchangeCode } from '@restomenum/plugin-sdk';
const cred = await exchangeCode(
{ code, clientId, clientSecret },
{ environment: 'sandbox' }, // veya { baseUrl }
);
// cred = { tenantId, apiKey, webhookSecret, scopes } → tenant başına SAKLAcred tenant başına saklanır (apiKey + webhookSecret). Akış: OAuth Connect → Token Exchange.
import { RestomenumClient } from '@restomenum/plugin-sdk';
const client = new RestomenumClient({ apiKey: cred.apiKey, environment: 'production' });
const packets = await client.packets.open();
const packet = await client.packets.get('packetId');
const products = await client.products.list(); // { data, truncated?, total? }
const customer = await client.customers.get('custId'); // PII consent kuralı sunucuda uygulanır
// Müşteri listesi — cursor pagination (offset YOK):
for await (const c of client.customers.listAll(200)) {
// tüm müşteriler, sayfa sayfa otomatik
}Kaynak grupları: packets, tables, products, categories, paymentMethods, ingredients, users, customers. Tümü: Data API.
addLines · setLineQuantity · removeLines — client.packets.* ve client.tables.* aynı sözleşme. Kurallar: Satır işlemleri. Kuru çalıştırma packets.validate / tables.validate; masanın not ve kişi sayısı tables.update.
import { randomUUID } from 'node:crypto';
const table = await client.tables.get('masa-12'); // revision + uuid buradan
const added = await client.tables.addLines({
id: table.tableId,
idempotencyKey: randomUUID(), // ZORUNLU — ağ hatasında AYNI anahtarla tekrar dene
expectedRevision: table.revision, // arada başka yazım olduysa 409 revision_conflict
expectedUuid: table.uuid ?? undefined,
items: [{ product: 'urun-abc123', quantity: 3 }],
}); // → { id, uuid, revision, total, paid, lines[], replayed }
// Tartısız üründe azaltma iki adımda: 3 → 0.5 tek çağrıda 400; 3 → 1 → 0.5 geçer.
const lineId = added.lines[0].lineId!;
const r1 = await client.tables.setLineQuantity({ id: table.tableId, idempotencyKey: randomUUID(), expectedRevision: added.revision, lineId, quantity: 1 });
await client.tables.setLineQuantity({ id: table.tableId, idempotencyKey: randomUUID(), expectedRevision: r1.revision, lineId, quantity: 0.5 });REST hata kodları ApiError'a çevrilir; OAuth hataları OAuthError; imza SignatureError.
import { ApiError } from '@restomenum/plugin-sdk';
try {
await client.packets.get('yok');
} catch (e) {
if (e instanceof ApiError) {
console.log(e.status, e.code); // 404, "plugin.packets.notFound"
if (e.code === 'plugin.rateLimited') wait(e.retryAfterSec); // hız sınırı; Retry-After (sn), başlık yoksa undefined
else if (e.code === 'internal' && e.retryable === true) retryLater(); // sunucu kararı (errorClass: e.errorClass)
}
}
// SDK 4.1.0+ (errorClass / retryable alanları ve 429'da gövde kodunun korunması 4.1.0 ile geldi).
// 429 her zaman hız sınırı değildir: internal + errorClass 'quota' da 429 döner.
// Dallanmayı status'a değil code'a göre yap; internal yanıtında yalnız retryable: true ise yeniden dene.
// code === 'invalid_response_body' (2xx ama gövde okunamadı) → sonuç BELİRSİZ, yazım olmuş olabilir:
// ağ hatası gibi AYNI idempotency anahtarıyla yeniden dene.Satır işlemleri kararlı makine kodunu errorCode'da verir (code eski uçlarla uyum için gövdedeki message'dır); sürüm çakışmasında currentRevision da gelir.
import { ApiError, isSaleLineErrorCode } from '@restomenum/plugin-sdk';
try {
await client.packets.setLineQuantity({ id, idempotencyKey, expectedRevision, lineId, quantity: 1 });
} catch (e) {
if (e instanceof ApiError && isSaleLineErrorCode(e.errorCode)) {
if (e.errorCode === 'revision_conflict') reload(e.currentRevision); // yeniden oku, YENİ anahtarla dene
if (e.errorCode === 'packet_not_open') stop(); // hesap kapalı — açılmaz
}
}import { actionResponse } from '@restomenum/plugin-sdk';
res.json(actionResponse(true, 'İşlem tamam', { level: 'success', display: 'toast' }));Sözleşme: Action Ucu · Aksiyon Butonları.
Teslim sıralı değildir: zarftaki sequence + sequenceScope ile bayat (geç gelen eski) snapshot'ı ele. Defterini (tenantId, sequenceScope) ile anahtarla ve terminal olaydan sonra ≥ 7 gün sakla.
import { sequenceKey, sequenceVerdict, advanceSequenceCursor, isSaleSequenceEvent } from '@restomenum/plugin-sdk';
if (isSaleSequenceEvent(envelope.type)) {
const key = sequenceKey(envelope.tenantId, envelope); // (tenantId, sequenceScope) — TEK SLOT YASAK
const cursor = key ? await ledger.get(key) : null;
switch (sequenceVerdict(envelope, cursor)) {
case 'stale': return; // daha küçük numara → bayat
case 'terminal': return; // satış sonlanmış; *.updated onu diriltmez
default: break; // 'apply' | 'unsequenced' → işle
}
if (key) await ledger.set(key, advanceSequenceCursor(cursor, envelope)); // ≥7 gün sakla
}Beş kuralın tamamı ve hat (scope) değişim tablosu: Olay sırası.
sequence / sequenceScope okumak için ≥ 3.0.0 gerekir. Daha eski sürümlerde parseEnvelope zarfı sabit bir alan listesinden kuruyordu ve bu alanlar (ayrıca actor / origin) düşüyordu. 3.0.0'dan itibaren eşleyici tanımadığı üst-seviye alanları taşır — platform zarfa yeni bir alan eklediğinde yeni SDK sürümü beklemezsin (envelope['yeniAlan'] → unknown). Aynı kural parseCapabilityRequest için de geçerlidir.amounts = satır tutarının tamsayı minor unit bileşen kırılımı; para birimi belge kökünde (currency + amountExponent). ⚠️ Üs yalnız amounts.* içindir — lineTotalDecimal/total/paid ondalıktır.
import { minorToDecimal, sumLineAmounts, vatBreakdown } from '@restomenum/plugin-sdk';
const { currency, amountExponent, orders } = envelope.data; // ör. "TRY", 2
const totals = sumLineAmounts(orders); // null → ondalık `total`'a geri düş
if (totals && amountExponent !== undefined) {
console.log(minorToDecimal(totals.gross, amountExponent), currency); // 129 TRY
}
const buckets = vatBreakdown(orders); // [{ rate: 19, gross, vat, net }, …] — yüksek oran önceGarantiler, karışık KDV kovaları (perVat) ve geri düşüş kuralları: Tutarlar (amounts).
import { EVENT_TYPES, SCOPES, PII_SCOPES, isPiiScope, isEventType } from '@restomenum/plugin-sdk';
import type { EventType, Scope, WebhookEnvelope, Customer, Packet, ActionRequest } from '@restomenum/plugin-sdk';Geçerli değerler: Event Kataloğu · Scope Referansı.