shapeshift-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shapeshift
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # shapeshift-sdk
2
+
3
+ Connect your product to Shapeshift so your customers can build their own features inside it.
4
+
5
+ ```
6
+ npm install shapeshift-sdk
7
+ ```
8
+
9
+ ## 1. Settings
10
+
11
+ Create a project at https://shapeshift-flame.vercel.app/signup to get these. Keep the secret on your server.
12
+
13
+ ```
14
+ SHAPESHIFT_PROJECT=your-project # your project id
15
+ SHAPESHIFT_SECRET=... # signs every request between you and Shapeshift
16
+ # SHAPESHIFT_URL=... # only if you use a different Shapeshift address
17
+ ```
18
+
19
+ ## 2. Describe your app and connect (server)
20
+
21
+ ```ts
22
+ import { createShapeshift } from "shapeshift-sdk/server";
23
+
24
+ export const shapeshift = createShapeshift({
25
+ // What add-ons may see and do. Only the actions listed here can ever be called.
26
+ manifest: {
27
+ app: "YourApp",
28
+ description: "What your app is for.",
29
+ types: "type Lead = { id: string; name: string; ... }",
30
+ ops: [{ name: "leads.list", args: "", returns: "Lead[]", description: "All leads." }],
31
+ spots: { column: { description: "An extra column in the leads table.", rowsName: "leads", rowsOp: "leads.list" } },
32
+ },
33
+ // How to run each action, always for one customer company and one of its users.
34
+ actions: { "leads.list": ({ tenantId }) => db.leads.forCompany(tenantId) },
35
+ // Shapeshift can only act as people who really belong to that company.
36
+ isMember: (tenantId, userId) => db.users.isIn(tenantId, userId),
37
+ // Who is signed in, with your own login.
38
+ getViewer: async () => {
39
+ const me = await currentUser();
40
+ return me && { tenant: { id: me.companyId, name: me.companyName }, user: { id: me.id, name: me.name } };
41
+ },
42
+ });
43
+ ```
44
+
45
+ ```ts
46
+ // app/api/shapeshift/[...path]/route.ts
47
+ export const { GET, POST, PATCH, DELETE } = shapeshift.handler;
48
+ ```
49
+
50
+ ## 3. Show add-ons and the Customize chat (browser)
51
+
52
+ ```tsx
53
+ import { useActivity, useAddons, useAddonList, useCustomize } from "shapeshift-sdk/react";
54
+
55
+ const { data } = useAddons(rowsOnScreen); // data.columns[i].cells[row.id], data.panels, data.buttons
56
+ const chat = useCustomize(); // chat.send(text), chat.result, chat.turnOn(draft)
57
+ const list = useAddonList(); // list.addons, setEnabled, remove, fix, undo, recheck
58
+ const log = useActivity(); // log.entries: what each add-on did, log.more() for older
59
+ ```
60
+
61
+ Or from server code: `shapeshift.client(viewer).render(rows)`.
62
+
63
+ ## Safety
64
+
65
+ Add-ons run in a sandbox on Shapeshift's side. They can only call the actions in your manifest, always for one
66
+ customer company and one signed-in person, and every call to your app is signed with your project secret. You can
67
+ block any action, and turn off any add-on, from the Shapeshift dashboard.
@@ -0,0 +1,54 @@
1
+ import { type ActivityEntry, type AddonInfo, type BuildResult, type Draft, type Rendered, type Turn } from "./types.ts";
2
+ export * from "./types.ts";
3
+ export declare function useAddons(rows: unknown[], { basePath }?: {
4
+ basePath?: string;
5
+ }): {
6
+ data: Rendered | null;
7
+ error: string;
8
+ refresh: () => Promise<void>;
9
+ run: (addonId: string) => Promise<{
10
+ ok: boolean;
11
+ message: string;
12
+ }>;
13
+ };
14
+ export declare function useCustomize({ basePath }?: {
15
+ basePath?: string;
16
+ }): {
17
+ turns: Turn[];
18
+ result: BuildResult | null;
19
+ saved: string | null;
20
+ building: boolean;
21
+ saving: boolean;
22
+ send: (text: string) => Promise<void>;
23
+ turnOn: (draft: Draft) => Promise<boolean>;
24
+ reset: () => void;
25
+ BUILT_PREFIX: string;
26
+ };
27
+ export declare function useAddonList({ basePath }?: {
28
+ basePath?: string;
29
+ }): {
30
+ addons: AddonInfo[];
31
+ checking: boolean;
32
+ error: string;
33
+ refresh: () => Promise<void>;
34
+ setEnabled: (addonId: string, enabled: boolean) => Promise<void>;
35
+ remove: (addonId: string) => Promise<void>;
36
+ fix: (addonId: string) => Promise<void>;
37
+ undo: (addonId: string) => Promise<void>;
38
+ recheck: () => Promise<{
39
+ checked: number;
40
+ ok: number;
41
+ fixed: number;
42
+ paused: number;
43
+ }>;
44
+ };
45
+ export declare function useActivity({ basePath, limit }?: {
46
+ basePath?: string;
47
+ limit?: number;
48
+ }): {
49
+ entries: ActivityEntry[];
50
+ error: string;
51
+ done: boolean;
52
+ refresh: () => Promise<void>;
53
+ more: () => Promise<void>;
54
+ };
package/dist/react.js ADDED
@@ -0,0 +1,174 @@
1
+ "use client";
2
+ import { useCallback, useEffect, useState } from "react";
3
+ import { BUILT_PREFIX } from "./types.js";
4
+ export * from "./types.js";
5
+ // Hooks for a product's own screens. They talk to the product's own route
6
+ // (app/api/shapeshift/[...path], from createShapeshift().handler), which signs the user in with the
7
+ // product's login and passes the request on to Shapeshift. Style the results however you like.
8
+ const DEFAULT_BASE = "/api/shapeshift";
9
+ async function req(base, path, init = {}) {
10
+ const res = await fetch(`${base}${path}`, {
11
+ method: init.method ?? (init.body === undefined ? "GET" : "POST"),
12
+ headers: { "Content-Type": "application/json" },
13
+ body: init.body === undefined ? undefined : JSON.stringify(init.body),
14
+ });
15
+ const data = (await res.json().catch(() => ({})));
16
+ if (!res.ok)
17
+ throw new Error(data.error ?? `Request failed (HTTP ${res.status}).`);
18
+ return data;
19
+ }
20
+ // The add-ons for a screen showing `rows`: columns (one cell per row id), panels and buttons.
21
+ export function useAddons(rows, { basePath = DEFAULT_BASE } = {}) {
22
+ const [data, setData] = useState(null);
23
+ const [error, setError] = useState("");
24
+ const key = JSON.stringify(rows);
25
+ const refresh = useCallback(async () => {
26
+ try {
27
+ setData(await req(basePath, "/render", { body: { rows: JSON.parse(key) } }));
28
+ setError("");
29
+ }
30
+ catch (e) {
31
+ setError(e.message);
32
+ }
33
+ }, [basePath, key]);
34
+ useEffect(() => {
35
+ const t = setTimeout(refresh, 0);
36
+ return () => clearTimeout(t);
37
+ }, [refresh]);
38
+ const run = useCallback(async (addonId) => {
39
+ const res = await req(basePath, `/addons/${encodeURIComponent(addonId)}/run`, {
40
+ body: { rows: JSON.parse(key) },
41
+ });
42
+ await refresh();
43
+ return res;
44
+ }, [basePath, key, refresh]);
45
+ return { data, error, refresh, run };
46
+ }
47
+ // The Customize chat: send a request, get a question or a tested draft back, turn it on.
48
+ // After a draft, the next message is a change request, so the AI sees what it built.
49
+ export function useCustomize({ basePath = DEFAULT_BASE } = {}) {
50
+ const [turns, setTurns] = useState([]);
51
+ const [result, setResult] = useState(null);
52
+ const [saved, setSaved] = useState(null);
53
+ const [building, setBuilding] = useState(false);
54
+ const [saving, setSaving] = useState(false);
55
+ const send = useCallback(async (text) => {
56
+ const t = text.trim();
57
+ if (!t || building)
58
+ return;
59
+ const base = result?.kind === "draft"
60
+ ? [...turns, { role: "assistant", text: BUILT_PREFIX + JSON.stringify(result.draft) }]
61
+ : result?.kind === "error" || saved
62
+ ? []
63
+ : turns;
64
+ const next = [...base, { role: "user", text: t }];
65
+ setTurns(next);
66
+ setResult(null);
67
+ setSaved(null);
68
+ setBuilding(true);
69
+ try {
70
+ const res = await req(basePath, "/build", { body: { conversation: next } });
71
+ if (res.kind === "question")
72
+ setTurns([...next, { role: "assistant", text: res.question }]);
73
+ setResult(res);
74
+ }
75
+ catch (e) {
76
+ setResult({ kind: "error", message: e.message });
77
+ }
78
+ finally {
79
+ setBuilding(false);
80
+ }
81
+ }, [basePath, building, result, saved, turns]);
82
+ const turnOn = useCallback(async (draft) => {
83
+ setSaving(true);
84
+ try {
85
+ await req(basePath, "/addons", { body: { draft } });
86
+ setSaved(draft.label);
87
+ setResult(null);
88
+ return true;
89
+ }
90
+ catch (e) {
91
+ setResult({ kind: "error", message: e.message });
92
+ return false;
93
+ }
94
+ finally {
95
+ setSaving(false);
96
+ }
97
+ }, [basePath]);
98
+ const reset = useCallback(() => {
99
+ setTurns([]);
100
+ setResult(null);
101
+ setSaved(null);
102
+ }, []);
103
+ return { turns, result, saved, building, saving, send, turnOn, reset, BUILT_PREFIX };
104
+ }
105
+ // The company's add-ons, for a management page: list, on/off, delete, fix, undo, check all.
106
+ export function useAddonList({ basePath = DEFAULT_BASE } = {}) {
107
+ const [addons, setAddons] = useState([]);
108
+ const [checking, setChecking] = useState(false);
109
+ const [error, setError] = useState("");
110
+ const refresh = useCallback(async () => {
111
+ try {
112
+ const res = await req(basePath, "/addons");
113
+ setAddons(res.addons);
114
+ setChecking(res.checking);
115
+ setError("");
116
+ }
117
+ catch (e) {
118
+ setError(e.message);
119
+ }
120
+ }, [basePath]);
121
+ useEffect(() => {
122
+ const t = setTimeout(refresh, 0);
123
+ return () => clearTimeout(t);
124
+ }, [refresh]);
125
+ const act = (fn) => async () => {
126
+ await fn();
127
+ await refresh();
128
+ };
129
+ const id = encodeURIComponent;
130
+ return {
131
+ addons,
132
+ checking,
133
+ error,
134
+ refresh,
135
+ setEnabled: (addonId, enabled) => act(() => req(basePath, `/addons/${id(addonId)}`, { method: "PATCH", body: { enabled } }))(),
136
+ remove: (addonId) => act(() => req(basePath, `/addons/${id(addonId)}`, { method: "DELETE" }))(),
137
+ fix: (addonId) => act(() => req(basePath, `/addons/${id(addonId)}/fix`, { body: {} }))(),
138
+ undo: (addonId) => act(() => req(basePath, `/addons/${id(addonId)}/undo`, { body: {} }))(),
139
+ recheck: async () => {
140
+ const summary = await req(basePath, "/recheck", { body: {} });
141
+ await refresh();
142
+ return summary;
143
+ },
144
+ };
145
+ }
146
+ // This company's activity log, newest first. `more()` loads older entries.
147
+ export function useActivity({ basePath = DEFAULT_BASE, limit = 50 } = {}) {
148
+ const [entries, setEntries] = useState([]);
149
+ const [done, setDone] = useState(false);
150
+ const [error, setError] = useState("");
151
+ const load = useCallback(async (before) => {
152
+ try {
153
+ const q = new URLSearchParams({ limit: String(limit), ...(before ? { before } : {}) });
154
+ const res = await req(basePath, `/activity?${q}`);
155
+ setEntries((old) => (before ? [...old, ...res.entries] : res.entries));
156
+ setDone(res.entries.length < limit);
157
+ setError("");
158
+ }
159
+ catch (e) {
160
+ setError(e.message);
161
+ }
162
+ }, [basePath, limit]);
163
+ useEffect(() => {
164
+ const t = setTimeout(() => load(), 0);
165
+ return () => clearTimeout(t);
166
+ }, [load]);
167
+ return {
168
+ entries,
169
+ error,
170
+ done,
171
+ refresh: () => load(),
172
+ more: () => (entries.length ? load(entries[entries.length - 1].at) : load()),
173
+ };
174
+ }
@@ -0,0 +1,75 @@
1
+ import type { ActivityEntry, AddonInfo, BuildResult, Draft, Manifest, Rendered, Turn, Viewer } from "./types.ts";
2
+ export * from "./types.ts";
3
+ export type ActionContext = {
4
+ tenantId: string;
5
+ userId: string;
6
+ };
7
+ export type Action = (ctx: ActionContext, ...args: unknown[]) => Promise<unknown> | unknown;
8
+ export type ShapeshiftOptions = {
9
+ manifest: Manifest;
10
+ actions: Record<string, Action>;
11
+ isMember: (tenantId: string, userId: string) => Promise<boolean> | boolean;
12
+ getViewer?: (req: Request) => Promise<Viewer | null> | Viewer | null;
13
+ url?: string;
14
+ project?: string;
15
+ secret?: string;
16
+ };
17
+ export declare class ShapeshiftError extends Error {
18
+ }
19
+ export declare function createShapeshift(opts: ShapeshiftOptions): {
20
+ client: (viewer: Viewer) => {
21
+ render: (rows: unknown[]) => Promise<Rendered>;
22
+ list: () => Promise<{
23
+ checking: boolean;
24
+ addons: AddonInfo[];
25
+ }>;
26
+ build: (conversation: Turn[]) => Promise<BuildResult>;
27
+ turnOn: (draft: Draft) => Promise<{
28
+ id: string;
29
+ }>;
30
+ setEnabled: (addonId: string, enabled: boolean) => Promise<unknown>;
31
+ remove: (addonId: string) => Promise<unknown>;
32
+ run: (addonId: string, rows: unknown[]) => Promise<{
33
+ ok: boolean;
34
+ message: string;
35
+ }>;
36
+ fix: (addonId: string) => Promise<{
37
+ fixed: boolean;
38
+ }>;
39
+ undo: (addonId: string) => Promise<unknown>;
40
+ activity: (opts?: {
41
+ before?: string;
42
+ limit?: number;
43
+ }) => Promise<{
44
+ entries: ActivityEntry[];
45
+ }>;
46
+ recheck: () => Promise<{
47
+ checked: number;
48
+ ok: number;
49
+ fixed: number;
50
+ paused: number;
51
+ }>;
52
+ };
53
+ handler: {
54
+ GET: (req: Request, ctx: {
55
+ params: Promise<{
56
+ path?: string[];
57
+ }>;
58
+ }) => Promise<Response>;
59
+ POST: (req: Request, ctx: {
60
+ params: Promise<{
61
+ path?: string[];
62
+ }>;
63
+ }) => Promise<Response>;
64
+ PATCH: (req: Request, ctx: {
65
+ params: Promise<{
66
+ path?: string[];
67
+ }>;
68
+ }) => Promise<Response>;
69
+ DELETE: (req: Request, ctx: {
70
+ params: Promise<{
71
+ path?: string[];
72
+ }>;
73
+ }) => Promise<Response>;
74
+ };
75
+ };
package/dist/server.js ADDED
@@ -0,0 +1,175 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ export * from "./types.js";
3
+ export class ShapeshiftError extends Error {
4
+ }
5
+ const MAX_AGE_MS = 5 * 60_000;
6
+ // Shapeshift's address, unless SHAPESHIFT_URL or the url option says otherwise.
7
+ const DEFAULT_URL = "https://shapeshift-flame.vercel.app";
8
+ const json = (data, status = 200) => new Response(JSON.stringify(data), { status, headers: { "Content-Type": "application/json" } });
9
+ export function createShapeshift(opts) {
10
+ const url = (opts.url ?? process.env.SHAPESHIFT_URL ?? DEFAULT_URL).replace(/\/+$/, "");
11
+ const project = opts.project ?? process.env.SHAPESHIFT_PROJECT ?? "";
12
+ const secret = opts.secret ?? process.env.SHAPESHIFT_SECRET ?? "";
13
+ /* ---- Calling Shapeshift for one signed-in user ---- */
14
+ // One session per user, reused until 5 minutes before Shapeshift says it expires.
15
+ const sessions = new Map();
16
+ const sessionKey = (viewer) => `${viewer.tenant.id}:${viewer.user.id}`;
17
+ async function session(viewer) {
18
+ const key = sessionKey(viewer);
19
+ const hit = sessions.get(key);
20
+ if (hit && hit.until > Date.now())
21
+ return hit.token;
22
+ const res = await fetch(`${url}/api/v1/sessions`, {
23
+ method: "POST",
24
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${secret}`, "X-Shapeshift-Project": project },
25
+ body: JSON.stringify(viewer),
26
+ cache: "no-store",
27
+ }).catch(() => null);
28
+ if (!res)
29
+ throw new ShapeshiftError("Shapeshift is not reachable.");
30
+ const data = (await res.json().catch(() => ({})));
31
+ if (!res.ok || !data.token)
32
+ throw new ShapeshiftError(data.error ?? `Shapeshift is not reachable (HTTP ${res.status}).`);
33
+ const until = (typeof data.expiresAt === "number" ? data.expiresAt : Date.now() + 3_600_000) - 5 * 60_000;
34
+ sessions.set(key, { token: data.token, until });
35
+ return data.token;
36
+ }
37
+ async function call(viewer, path, init = {}, retried = false) {
38
+ const token = await session(viewer);
39
+ const res = await fetch(`${url}/api/v1${path}`, {
40
+ method: init.method ?? (init.body === undefined ? "GET" : "POST"),
41
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
42
+ body: init.body === undefined ? undefined : JSON.stringify(init.body),
43
+ cache: "no-store",
44
+ }).catch(() => null);
45
+ if (!res)
46
+ throw new ShapeshiftError("Shapeshift is not reachable.");
47
+ // A session Shapeshift no longer accepts: forget it and try once more with a new one.
48
+ if (res.status === 401 && !retried) {
49
+ sessions.delete(sessionKey(viewer));
50
+ return call(viewer, path, init, true);
51
+ }
52
+ const data = (await res.json().catch(() => ({})));
53
+ if (!res.ok)
54
+ throw new ShapeshiftError(data.error ?? `Shapeshift error (HTTP ${res.status}).`);
55
+ return data;
56
+ }
57
+ const id = (s) => encodeURIComponent(s);
58
+ // Rows go over the wire as plain JSON (dates become ISO strings).
59
+ const plain = (rows) => JSON.parse(JSON.stringify(rows ?? []));
60
+ function client(viewer) {
61
+ return {
62
+ render: (rows) => call(viewer, "/render", { body: { rows: plain(rows) } }),
63
+ list: () => call(viewer, "/addons"),
64
+ build: (conversation) => call(viewer, "/build", { body: { conversation } }),
65
+ turnOn: (draft) => call(viewer, "/addons", { body: { draft } }),
66
+ setEnabled: (addonId, enabled) => call(viewer, `/addons/${id(addonId)}`, { method: "PATCH", body: { enabled } }),
67
+ remove: (addonId) => call(viewer, `/addons/${id(addonId)}`, { method: "DELETE" }),
68
+ run: (addonId, rows) => call(viewer, `/addons/${id(addonId)}/run`, { body: { rows: plain(rows) } }),
69
+ fix: (addonId) => call(viewer, `/addons/${id(addonId)}/fix`, { body: {} }),
70
+ undo: (addonId) => call(viewer, `/addons/${id(addonId)}/undo`, { body: {} }),
71
+ activity: (opts = {}) => {
72
+ const q = new URLSearchParams();
73
+ if (opts.before)
74
+ q.set("before", opts.before);
75
+ if (opts.limit)
76
+ q.set("limit", String(opts.limit));
77
+ return call(viewer, `/activity${q.size ? `?${q}` : ""}`);
78
+ },
79
+ recheck: () => call(viewer, "/recheck", { body: {} }),
80
+ };
81
+ }
82
+ /* ---- Answering Shapeshift, and the browser ---- */
83
+ function verified(req, body) {
84
+ const ts = req.headers.get("x-shapeshift-timestamp") ?? "";
85
+ const sig = req.headers.get("x-shapeshift-signature") ?? "";
86
+ if (!secret || !ts || !sig || Math.abs(Date.now() - Number(ts)) > MAX_AGE_MS)
87
+ return false;
88
+ const expected = createHmac("sha256", secret).update(`${ts}.${body}`).digest("hex");
89
+ const a = Buffer.from(sig);
90
+ const b = Buffer.from(expected);
91
+ return a.length === b.length && timingSafeEqual(a, b);
92
+ }
93
+ // Shapeshift runs one of the product's actions for one company and one of its users.
94
+ async function handleCall(req) {
95
+ const raw = await req.text();
96
+ if (!verified(req, raw))
97
+ return json({ ok: false, error: "Bad signature." }, 401);
98
+ let input;
99
+ try {
100
+ input = JSON.parse(raw);
101
+ }
102
+ catch {
103
+ return json({ ok: false, error: "Bad request." }, 400);
104
+ }
105
+ const { tenantId = "", userId = "", op = "", args = [] } = input;
106
+ if (!(await opts.isMember(tenantId, userId)))
107
+ return json({ ok: false, error: "That user isn't part of that company." }, 403);
108
+ const action = opts.actions[op];
109
+ if (!action)
110
+ return json({ ok: false, error: `Unknown action: ${op}` }, 400);
111
+ try {
112
+ const result = await action({ tenantId, userId }, ...(Array.isArray(args) ? args : []));
113
+ return json({ ok: true, result: JSON.parse(JSON.stringify(result ?? null)) });
114
+ }
115
+ catch (e) {
116
+ return json({ ok: false, error: e.message }, 400);
117
+ }
118
+ }
119
+ // Browser routes: the product's own screens, signed in with the product's own login.
120
+ async function handleBrowser(req, path, method) {
121
+ const viewer = opts.getViewer ? await opts.getViewer(req) : null;
122
+ if (!viewer)
123
+ return json({ error: "Not signed in." }, 401);
124
+ const c = client(viewer);
125
+ const b = method === "GET" || method === "DELETE" ? {} : (await req.json().catch(() => ({})));
126
+ const [first, addonId, action] = path;
127
+ try {
128
+ if (method === "POST" && first === "render")
129
+ return json(await c.render(b.rows ?? []));
130
+ if (method === "POST" && first === "build")
131
+ return json(await c.build(b.conversation ?? []));
132
+ if (method === "POST" && first === "recheck")
133
+ return json(await c.recheck());
134
+ if (method === "GET" && first === "activity") {
135
+ const q = new URL(req.url).searchParams;
136
+ return json(await c.activity({ before: q.get("before") ?? undefined, limit: Number(q.get("limit")) || undefined }));
137
+ }
138
+ if (first === "addons" && !addonId) {
139
+ if (method === "GET")
140
+ return json(await c.list());
141
+ if (method === "POST")
142
+ return json(await c.turnOn(b.draft));
143
+ }
144
+ if (first === "addons" && addonId) {
145
+ if (method === "PATCH" && !action)
146
+ return json(await c.setEnabled(addonId, Boolean(b.enabled)));
147
+ if (method === "DELETE" && !action)
148
+ return json(await c.remove(addonId));
149
+ if (method === "POST" && action === "run")
150
+ return json(await c.run(addonId, b.rows ?? []));
151
+ if (method === "POST" && action === "fix")
152
+ return json(await c.fix(addonId));
153
+ if (method === "POST" && action === "undo")
154
+ return json(await c.undo(addonId));
155
+ }
156
+ return json({ error: "Not found." }, 404);
157
+ }
158
+ catch (e) {
159
+ return json({ error: e.message }, e instanceof ShapeshiftError ? 502 : 500);
160
+ }
161
+ }
162
+ const route = (method) => async (req, ctx) => {
163
+ const path = (await ctx.params).path ?? [];
164
+ if (method === "GET" && path[0] === "manifest" && path.length === 1) {
165
+ return verified(req, "") ? json(opts.manifest) : json({ error: "Bad signature." }, 401);
166
+ }
167
+ if (method === "POST" && path[0] === "call" && path.length === 1)
168
+ return handleCall(req);
169
+ return handleBrowser(req, path, method);
170
+ };
171
+ return {
172
+ client,
173
+ handler: { GET: route("GET"), POST: route("POST"), PATCH: route("PATCH"), DELETE: route("DELETE") },
174
+ };
175
+ }
@@ -0,0 +1,165 @@
1
+ export type Tone = "good" | "warn" | "bad" | "info" | "neutral";
2
+ export type CellValue = {
3
+ text: string;
4
+ tone: Tone;
5
+ };
6
+ export type Block = {
7
+ type: "heading";
8
+ text: string;
9
+ } | {
10
+ type: "text";
11
+ text: string;
12
+ } | {
13
+ type: "stat";
14
+ label: string;
15
+ value: string;
16
+ tone?: Tone;
17
+ } | {
18
+ type: "list";
19
+ items: {
20
+ title: string;
21
+ subtitle?: string;
22
+ badge?: string;
23
+ tone?: Tone;
24
+ rowId?: string;
25
+ }[];
26
+ } | {
27
+ type: "bars";
28
+ items: {
29
+ label: string;
30
+ value: number;
31
+ }[];
32
+ };
33
+ export type Spot = "column" | "panel" | "button";
34
+ export type Draft = {
35
+ name: string;
36
+ description: string;
37
+ spot: Spot;
38
+ label: string;
39
+ code: string;
40
+ };
41
+ export type Preview = {
42
+ spot: "column";
43
+ rows: {
44
+ name: string;
45
+ sub: string;
46
+ cell: CellValue;
47
+ }[];
48
+ filled: number;
49
+ total: number;
50
+ } | {
51
+ spot: "panel";
52
+ blocks: Block[];
53
+ } | {
54
+ spot: "button";
55
+ message: string;
56
+ writes: string[];
57
+ writeCount: number;
58
+ };
59
+ export type BuildResult = {
60
+ kind: "question";
61
+ question: string;
62
+ } | {
63
+ kind: "draft";
64
+ draft: Draft;
65
+ preview: Preview;
66
+ tries: number;
67
+ } | {
68
+ kind: "error";
69
+ message: string;
70
+ };
71
+ export type Rendered = {
72
+ columns: {
73
+ id: string;
74
+ label: string;
75
+ description: string;
76
+ ok: boolean;
77
+ error?: string;
78
+ cells: Record<string, CellValue>;
79
+ }[];
80
+ panels: {
81
+ id: string;
82
+ label: string;
83
+ ok: boolean;
84
+ error?: string;
85
+ blocks: Block[];
86
+ }[];
87
+ buttons: {
88
+ id: string;
89
+ label: string;
90
+ }[];
91
+ paused: {
92
+ id: string;
93
+ name: string;
94
+ }[];
95
+ };
96
+ export type AddonHealth = {
97
+ status: "ok" | "fixed" | "paused";
98
+ note?: string;
99
+ previousCode?: string;
100
+ };
101
+ export type AddonInfo = {
102
+ id: string;
103
+ name: string;
104
+ description: string;
105
+ spot: Spot;
106
+ label: string;
107
+ code: string;
108
+ enabled: boolean;
109
+ createdByName: string | null;
110
+ createdAt: string;
111
+ health: AddonHealth | null;
112
+ };
113
+ export type Viewer = {
114
+ tenant: {
115
+ id: string;
116
+ name: string;
117
+ };
118
+ user: {
119
+ id: string;
120
+ name: string;
121
+ title?: string | null;
122
+ };
123
+ };
124
+ export type Manifest = {
125
+ app: string;
126
+ description: string;
127
+ types: string;
128
+ ops: {
129
+ name: string;
130
+ description: string;
131
+ args: string;
132
+ returns: string;
133
+ writes?: boolean;
134
+ }[];
135
+ snapshotOp?: string;
136
+ spots: Partial<Record<Spot, {
137
+ description: string;
138
+ rowsName: string;
139
+ rowsOp: string;
140
+ }>>;
141
+ };
142
+ export type Turn = {
143
+ role: "user" | "assistant";
144
+ text: string;
145
+ };
146
+ export type ActivityEntry = {
147
+ id: string;
148
+ at: string;
149
+ tenant: {
150
+ id: string;
151
+ name: string;
152
+ };
153
+ addon: {
154
+ id: string | null;
155
+ name: string;
156
+ spot: Spot | null;
157
+ };
158
+ who: string;
159
+ event: "ran" | "made" | "turned_on" | "turned_off" | "deleted" | "fixed" | "paused" | "undone";
160
+ ok: boolean;
161
+ summary: string;
162
+ changes: string[];
163
+ ms: number | null;
164
+ };
165
+ export declare const BUILT_PREFIX = "Built this add-on: ";
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ // Types Shapeshift sends back. Safe to use in the browser and on the server.
2
+ // The chat sends back earlier versions as assistant turns starting with this, so change requests have context.
3
+ export const BUILT_PREFIX = "Built this add-on: ";
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "shapeshift-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Connect your product to Shapeshift: your customers build their own features inside it.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ "./server": {
9
+ "types": "./dist/server.d.ts",
10
+ "default": "./dist/server.js"
11
+ },
12
+ "./react": {
13
+ "types": "./dist/react.d.ts",
14
+ "default": "./dist/react.js"
15
+ },
16
+ "./types": {
17
+ "types": "./dist/types.d.ts",
18
+ "default": "./dist/types.js"
19
+ }
20
+ },
21
+ "files": ["dist", "README.md", "LICENSE"],
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.json",
24
+ "prepublishOnly": "npm run build"
25
+ },
26
+ "engines": {
27
+ "node": ">=18"
28
+ },
29
+ "peerDependencies": {
30
+ "react": ">=18"
31
+ },
32
+ "peerDependenciesMeta": {
33
+ "react": {
34
+ "optional": true
35
+ }
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^20",
39
+ "@types/react": "^19",
40
+ "typescript": "^5"
41
+ }
42
+ }