tands 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 Tabs & Spaces
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,26 @@
1
- # Temporary Holding Version
1
+ # tands
2
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.
3
+ Developer tools for [Tabs & Spaces](https://tabsandspaces.dev) apps. Node 22 or later.
4
+
5
+ ```sh
6
+ npx tands new team-notes # a small, working app to start from
7
+ cd team-notes && npm start # your app, on http://localhost:5480
8
+ npx tands dev # a local workspace for it, on http://localhost:5470
9
+ ```
10
+
11
+ - **`tands new <folder>`** makes an app with a Custom tab, data, an action and an event. No
12
+ dependencies and no build step: the SDK comes built, in plain JavaScript.
13
+ - **`tands check [manifest]`** checks a manifest (a file, or its address) as a workspace would.
14
+ - **`tands dev [manifest address]`** stands in for a workspace: your tab as someone you choose,
15
+ real tokens signed with its own keys, your data in memory, your events and your actions.
16
+
17
+ For your own build, the SDK is [`@tabs-and-spaces/sdk`](https://www.npmjs.com/package/@tabs-and-spaces/sdk).
18
+
19
+ Docs: **https://developer.tabsandspaces.dev/tools/**
20
+
21
+ MIT licensed.
22
+
23
+ ---
24
+
25
+ In the Tabs & Spaces repository (`packages/cli`), run it as `yarn tands`. `build.mjs` bundles it
26
+ into `dist/tands.js` and builds the SDK into `dist/sdk/` for `tands new` to copy into apps.
@@ -0,0 +1,137 @@
1
+ // ../sdk/src/server.ts
2
+ var TokenError = class extends Error {
3
+ };
4
+ async function fetchKeys(deploymentUrl, fetcher = fetch) {
5
+ const response = await fetcher(new URL("/api/apps/keys", deploymentUrl));
6
+ if (!response.ok) throw new TokenError(`Couldn't fetch the keys (${response.status}).`);
7
+ const body = await response.json();
8
+ return body.keys ?? [];
9
+ }
10
+ var decode = (part) => {
11
+ const base64 = part.replace(/-/g, "+").replace(/_/g, "/");
12
+ const binary = atob(base64 + "=".repeat((4 - base64.length % 4) % 4));
13
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
14
+ };
15
+ var json = (part) => {
16
+ try {
17
+ return JSON.parse(new TextDecoder().decode(decode(part)));
18
+ } catch {
19
+ throw new TokenError("That isn't a token.");
20
+ }
21
+ };
22
+ async function verifyToken(token, {
23
+ keys,
24
+ audience,
25
+ issuer,
26
+ now = Date.now()
27
+ }) {
28
+ const parts = token.split(".");
29
+ if (parts.length !== 3) throw new TokenError("That isn't a token.");
30
+ const [headerPart, payloadPart, signaturePart] = parts;
31
+ const header = json(headerPart);
32
+ if (header.alg !== "EdDSA") throw new TokenError("Unexpected signing algorithm.");
33
+ const jwk = keys.find((key2) => key2.kid === header.kid && key2.crv === "Ed25519");
34
+ if (!jwk) throw new TokenError("Signed with a key we don't know.");
35
+ const key = await crypto.subtle.importKey(
36
+ "jwk",
37
+ { kty: jwk.kty, crv: jwk.crv, x: jwk.x },
38
+ { name: "Ed25519" },
39
+ false,
40
+ ["verify"]
41
+ );
42
+ const valid = await crypto.subtle.verify(
43
+ { name: "Ed25519" },
44
+ key,
45
+ decode(signaturePart),
46
+ new TextEncoder().encode(`${headerPart}.${payloadPart}`)
47
+ );
48
+ if (!valid) throw new TokenError("The signature doesn't match.");
49
+ const payload = json(payloadPart);
50
+ if (payload.aud !== audience) throw new TokenError("It's meant for another app.");
51
+ if (issuer !== void 0 && payload.iss !== issuer) {
52
+ throw new TokenError("It's from another deployment.");
53
+ }
54
+ if (typeof payload.exp !== "number" || payload.exp * 1e3 <= now) {
55
+ throw new TokenError("It has expired.");
56
+ }
57
+ return {
58
+ context: payload.ctx,
59
+ issuer: String(payload.iss),
60
+ expiresAt: new Date(payload.exp * 1e3),
61
+ action: typeof payload.act === "string" ? payload.act : null
62
+ };
63
+ }
64
+ function dataClient({ dataKey, dataUrl }, fetcher = fetch) {
65
+ async function data(request) {
66
+ const response = await fetcher(dataUrl, {
67
+ method: "POST",
68
+ headers: { "content-type": "application/json", authorization: `Bearer ${dataKey}` },
69
+ body: JSON.stringify(request)
70
+ });
71
+ const body = await response.json().catch(() => null);
72
+ if (!response.ok) {
73
+ throw new DataError(
74
+ body?.error?.message ?? `It answered ${response.status}.`,
75
+ body?.error?.code ?? null
76
+ );
77
+ }
78
+ return body?.result;
79
+ }
80
+ return {
81
+ data,
82
+ /**
83
+ * Reports something that happened in your app (M9 slice 5), as your
84
+ * manifest's `events` declare it, for the person and place of the action.
85
+ * One from an agent's action starts no trigger (no loops).
86
+ */
87
+ async emit(name, fields = {}) {
88
+ const response = await fetcher(dataUrl.replace(/\/data$/, "/events"), {
89
+ method: "POST",
90
+ headers: { "content-type": "application/json", authorization: `Bearer ${dataKey}` },
91
+ body: JSON.stringify({ name, data: fields })
92
+ });
93
+ if (!response.ok) {
94
+ const body = await response.json().catch(() => null);
95
+ throw new DataError(
96
+ body?.error?.message ?? `It answered ${response.status}.`,
97
+ body?.error?.code ?? null
98
+ );
99
+ }
100
+ },
101
+ values(scope) {
102
+ return {
103
+ get: async (key) => (await data({ op: "values.get", scope, key })).value,
104
+ set: async (key, value) => {
105
+ await data({ op: "values.set", scope, key, value });
106
+ },
107
+ delete: async (key) => (await data({ op: "values.delete", scope, key })).deleted,
108
+ list: async () => (await data({ op: "values.list", scope })).values
109
+ };
110
+ },
111
+ collection(name) {
112
+ return {
113
+ list: async (options = {}) => await data({ op: "records.list", collection: name, ...options }),
114
+ get: async (id) => (await data({ op: "records.get", collection: name, id })).record,
115
+ create: async (fields) => (await data({ op: "records.create", collection: name, data: fields })).record,
116
+ update: async (id, fields) => (await data({ op: "records.update", collection: name, id, data: fields })).record,
117
+ delete: async (id) => {
118
+ await data({ op: "records.delete", collection: name, id });
119
+ }
120
+ };
121
+ }
122
+ };
123
+ }
124
+ var DataError = class extends Error {
125
+ constructor(message, code) {
126
+ super(message);
127
+ this.code = code;
128
+ }
129
+ code;
130
+ };
131
+ export {
132
+ DataError,
133
+ TokenError,
134
+ dataClient,
135
+ fetchKeys,
136
+ verifyToken
137
+ };
@@ -0,0 +1,203 @@
1
+ // ../sdk/src/protocol.ts
2
+ var PROTOCOL_VERSION = 1;
3
+ var isRecord = (value) => typeof value === "object" && value !== null;
4
+ function readAppMessage(data) {
5
+ if (!isRecord(data) || data.tands !== PROTOCOL_VERSION) return null;
6
+ if (data.type === "hello") return { tands: 1, type: "hello" };
7
+ if (data.type === "token" && typeof data.id === "string" && data.id.length <= 64) {
8
+ return { tands: 1, type: "token", id: data.id };
9
+ }
10
+ if (data.type === "data" && typeof data.id === "string" && data.id.length <= 64 && isRecord(data.request) && typeof data.request.op === "string") {
11
+ return { tands: 1, type: "data", id: data.id, request: data.request };
12
+ }
13
+ if (data.type === "event" && typeof data.id === "string" && data.id.length <= 64 && typeof data.name === "string" && data.name.length <= 40 && (data.data === void 0 || isRecord(data.data))) {
14
+ return {
15
+ tands: 1,
16
+ type: "event",
17
+ id: data.id,
18
+ name: data.name,
19
+ data: data.data ?? {}
20
+ };
21
+ }
22
+ return null;
23
+ }
24
+ function readHostMessage(data) {
25
+ if (!isRecord(data) || data.tands !== PROTOCOL_VERSION) return null;
26
+ const theme = data.theme === "dark" ? "dark" : "light";
27
+ switch (data.type) {
28
+ case "context":
29
+ return isRecord(data.context) && typeof data.token === "string" && typeof data.expiresAt === "string" ? {
30
+ tands: 1,
31
+ type: "context",
32
+ context: data.context,
33
+ token: data.token,
34
+ expiresAt: data.expiresAt,
35
+ theme
36
+ } : null;
37
+ case "token":
38
+ return typeof data.id === "string" && typeof data.token === "string" && typeof data.expiresAt === "string" ? { tands: 1, type: "token", id: data.id, token: data.token, expiresAt: data.expiresAt } : null;
39
+ case "data":
40
+ return typeof data.id === "string" ? { tands: 1, type: "data", id: data.id, result: data.result } : null;
41
+ case "error":
42
+ return typeof data.message === "string" ? {
43
+ tands: 1,
44
+ type: "error",
45
+ message: data.message,
46
+ ...typeof data.id === "string" ? { id: data.id } : {},
47
+ ...typeof data.code === "string" ? { code: data.code } : {}
48
+ } : null;
49
+ case "theme":
50
+ return { tands: 1, type: "theme", theme };
51
+ default:
52
+ return null;
53
+ }
54
+ }
55
+
56
+ // ../sdk/src/client.ts
57
+ var WorkspaceError = class extends Error {
58
+ constructor(message, code) {
59
+ super(message);
60
+ this.code = code;
61
+ }
62
+ code;
63
+ };
64
+ var REFRESH_MS = 6e4;
65
+ function connect({ timeoutMs = 1e4, window: win = window } = {}) {
66
+ return new Promise((resolve, reject) => {
67
+ const parent = win.parent;
68
+ if (!parent || parent === win) {
69
+ reject(new Error("This page isn't open in a Tabs & Spaces workspace."));
70
+ return;
71
+ }
72
+ let hostOrigin = null;
73
+ let context = null;
74
+ let current = { token: "", expiresAt: 0 };
75
+ let theme = "light";
76
+ let counter = 0;
77
+ const themeListeners = /* @__PURE__ */ new Set();
78
+ const waiting = /* @__PURE__ */ new Map();
79
+ let pending = null;
80
+ const send = (message) => parent.postMessage(message, hostOrigin ?? "*");
81
+ const timer = setTimeout(() => {
82
+ win.removeEventListener("message", listen);
83
+ reject(new Error("The workspace didn't answer."));
84
+ }, timeoutMs);
85
+ function listen(event) {
86
+ if (event.source !== parent) return;
87
+ if (hostOrigin && event.origin !== hostOrigin) return;
88
+ const message = readHostMessage(event.data);
89
+ if (!message) return;
90
+ switch (message.type) {
91
+ case "context":
92
+ if (context) return;
93
+ hostOrigin = event.origin;
94
+ context = message.context;
95
+ theme = message.theme;
96
+ current = { token: message.token, expiresAt: Date.parse(message.expiresAt) };
97
+ clearTimeout(timer);
98
+ resolve(connection);
99
+ return;
100
+ case "token": {
101
+ const waiter = waiting.get(message.id);
102
+ if (!waiter) return;
103
+ waiting.delete(message.id);
104
+ current = { token: message.token, expiresAt: Date.parse(message.expiresAt) };
105
+ waiter.resolve(message.token);
106
+ return;
107
+ }
108
+ case "data": {
109
+ const waiter = waiting.get(message.id);
110
+ if (!waiter) return;
111
+ waiting.delete(message.id);
112
+ waiter.resolve(message.result);
113
+ return;
114
+ }
115
+ case "error": {
116
+ const waiter = message.id ? waiting.get(message.id) : void 0;
117
+ if (!waiter || !message.id) return;
118
+ waiting.delete(message.id);
119
+ waiter.reject(new WorkspaceError(message.message, message.code ?? null));
120
+ return;
121
+ }
122
+ case "theme":
123
+ theme = message.theme;
124
+ for (const listener of themeListeners) listener(theme);
125
+ return;
126
+ }
127
+ }
128
+ function ask(message) {
129
+ return new Promise((ok, fail) => {
130
+ const id = `r${++counter}`;
131
+ waiting.set(id, { resolve: ok, reject: fail });
132
+ send(message(id));
133
+ });
134
+ }
135
+ const data = (request) => ask((id) => ({ tands: 1, type: "data", id, request }));
136
+ const connection = {
137
+ get context() {
138
+ return context;
139
+ },
140
+ get theme() {
141
+ return theme;
142
+ },
143
+ token() {
144
+ if (current.expiresAt - Date.now() > REFRESH_MS) return Promise.resolve(current.token);
145
+ pending ??= new Promise((ok, fail) => {
146
+ const id = `t${++counter}`;
147
+ waiting.set(id, { resolve: ok, reject: fail });
148
+ send({ tands: 1, type: "token", id });
149
+ }).finally(() => {
150
+ pending = null;
151
+ });
152
+ return pending;
153
+ },
154
+ data,
155
+ async emit(name, fields = {}) {
156
+ await ask((id) => ({ tands: 1, type: "event", id, name, data: fields }));
157
+ },
158
+ values(scope) {
159
+ return {
160
+ get: async (key) => (await data({ op: "values.get", scope, key })).value,
161
+ set: async (key, value) => {
162
+ await data({ op: "values.set", scope, key, value });
163
+ },
164
+ delete: async (key) => (await data({ op: "values.delete", scope, key })).deleted,
165
+ list: async () => (await data({ op: "values.list", scope })).values
166
+ };
167
+ },
168
+ collection(name) {
169
+ return {
170
+ list: async (options = {}) => await data({
171
+ op: "records.list",
172
+ collection: name,
173
+ ...options
174
+ }),
175
+ get: async (id) => (await data({ op: "records.get", collection: name, id })).record,
176
+ create: async (fields) => (await data({ op: "records.create", collection: name, data: fields })).record,
177
+ update: async (id, fields) => (await data({ op: "records.update", collection: name, id, data: fields })).record,
178
+ delete: async (id) => {
179
+ await data({ op: "records.delete", collection: name, id });
180
+ }
181
+ };
182
+ },
183
+ onTheme(listener) {
184
+ themeListeners.add(listener);
185
+ return () => themeListeners.delete(listener);
186
+ },
187
+ close() {
188
+ win.removeEventListener("message", listen);
189
+ for (const waiter of waiting.values()) waiter.reject(new Error("Closed."));
190
+ waiting.clear();
191
+ }
192
+ };
193
+ win.addEventListener("message", listen);
194
+ send({ tands: 1, type: "hello" });
195
+ });
196
+ }
197
+ export {
198
+ PROTOCOL_VERSION,
199
+ WorkspaceError,
200
+ connect,
201
+ readAppMessage,
202
+ readHostMessage
203
+ };