@indent-com/nexus-sdk 0.0.0-stage → 0.1.1
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/dist/analyze.d.ts +26 -0
- package/dist/analyze.js +190 -0
- package/dist/build.d.ts +32 -0
- package/dist/build.js +141 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +21 -0
- package/dist/client.d.ts +18 -0
- package/dist/client.js +4 -0
- package/dist/contract.d.ts +7 -0
- package/dist/contract.js +1 -0
- package/dist/errors.d.ts +10 -0
- package/dist/errors.js +20 -0
- package/dist/helpers.d.ts +3 -0
- package/dist/helpers.js +43 -0
- package/dist/index.d.ts +199 -0
- package/dist/index.js +117 -0
- package/dist/manifest.d.ts +34 -0
- package/dist/react.d.ts +10 -0
- package/dist/react.js +7 -0
- package/dist/schema.d.ts +6 -0
- package/dist/schema.js +75 -0
- package/dist/store.d.ts +9 -0
- package/dist/store.js +118 -0
- package/dist/stubs.d.ts +1 -0
- package/dist/stubs.js +1 -0
- package/dist/vite.d.ts +7 -0
- package/dist/vite.js +56 -0
- package/package.json +68 -4
- package/template/.agents/skills/building-nexus-apps/SKILL.md +66 -0
- package/template/.agents/skills/building-nexus-apps/gotchas.md +40 -0
- package/template/.agents/skills/building-nexus-apps/local-testing.md +88 -0
- package/template/AGENTS.md +16 -0
- package/template/README.md +25 -0
- package/template/_gitignore +4 -0
- package/template/migrations/0001_notes.sql +5 -0
- package/template/package.json +24 -0
- package/template/pnpm-workspace.yaml +2 -0
- package/template/server/notes.ts +19 -0
- package/template/tsconfig.json +15 -0
- package/template/ui/index.html +12 -0
- package/template/ui/src/App.tsx +84 -0
- package/template/ui/src/components.tsx +44 -0
- package/template/ui/src/main.tsx +4 -0
- package/template/ui/src/style.css +5 -0
- package/template/ui/vite.config.mjs +4 -0
- package/README.md +0 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/** A read: GET, with stored results. */
|
|
2
|
+
export function query<I extends object, O>(
|
|
3
|
+
fn: (input: I, context: Context) => Promise<O>,
|
|
4
|
+
): Query<I, O>;
|
|
5
|
+
|
|
6
|
+
/** A change: POST, always live. */
|
|
7
|
+
export function mutation<I extends object, O>(
|
|
8
|
+
fn: (input: I, context: Context) => Promise<O>,
|
|
9
|
+
): Mutation<I, O>;
|
|
10
|
+
|
|
11
|
+
/** What the UI imports: callable with the input alone, and branded by kind. */
|
|
12
|
+
export type Query<I, O> = ((input: I) => Promise<O>) & {
|
|
13
|
+
readonly kind: "query";
|
|
14
|
+
};
|
|
15
|
+
/** What the UI imports for a mutation: callable with the input alone. */
|
|
16
|
+
export type Mutation<I, O> = ((input: I) => Promise<O>) & {
|
|
17
|
+
readonly kind: "mutation";
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** Who the call is for, and the app's cache. */
|
|
21
|
+
export type Context = { auth: Auth; cache: Cache };
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The app's cache. Nothing is cached unless a handler asks. Entries are shared by
|
|
25
|
+
* everyone who calls the app unless the handler scopes them with `forViewer()`.
|
|
26
|
+
*/
|
|
27
|
+
export type Cache = {
|
|
28
|
+
/**
|
|
29
|
+
* The value stored under `key` while it is younger than `freshFor`; otherwise what
|
|
30
|
+
* `load` returns, stored. Gets of one key in a call share one `load`, and when
|
|
31
|
+
* `load` throws, an older stored value is returned instead.
|
|
32
|
+
*/
|
|
33
|
+
get<T extends Json>(options: {
|
|
34
|
+
key: CacheKey;
|
|
35
|
+
freshFor: Duration;
|
|
36
|
+
load: () => Promise<T>;
|
|
37
|
+
}): Promise<T>;
|
|
38
|
+
/** Drops `key`, so the next `get` loads it. */
|
|
39
|
+
invalidate(key: CacheKey): Promise<void>;
|
|
40
|
+
/** The same cache, with entries only the caller sees. */
|
|
41
|
+
forViewer(): Cache;
|
|
42
|
+
};
|
|
43
|
+
/** Any JSON value; equal values name the same entry. */
|
|
44
|
+
export type CacheKey =
|
|
45
|
+
string | number | boolean | null | CacheKey[] | { [key: string]: CacheKey };
|
|
46
|
+
/** A value that comes back the same from JSON; `undefined` properties drop out. */
|
|
47
|
+
export type Json =
|
|
48
|
+
| string
|
|
49
|
+
| number
|
|
50
|
+
| boolean
|
|
51
|
+
| null
|
|
52
|
+
| readonly Json[]
|
|
53
|
+
| { readonly [key: string]: Json | undefined };
|
|
54
|
+
/** How long, as in `"1 minute"` or `"30 seconds"`. */
|
|
55
|
+
export type Duration = `${number} ${DurationUnit}`;
|
|
56
|
+
type DurationUnit =
|
|
57
|
+
| "second"
|
|
58
|
+
| "seconds"
|
|
59
|
+
| "minute"
|
|
60
|
+
| "minutes"
|
|
61
|
+
| "hour"
|
|
62
|
+
| "hours"
|
|
63
|
+
| "day"
|
|
64
|
+
| "days";
|
|
65
|
+
|
|
66
|
+
/** The actor a call or run is for. */
|
|
67
|
+
export type Auth = { actor: Actor };
|
|
68
|
+
|
|
69
|
+
/** A person, a bot, or Indent itself. */
|
|
70
|
+
export type Actor =
|
|
71
|
+
| { kind: "user"; id: string; name: string; email: string } // a person
|
|
72
|
+
| { kind: "bot"; id: string; name: string } // a program with its own credential
|
|
73
|
+
| { kind: "indent" }; // Indent itself, with no person or bot behind the call
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* What a call that cannot be made throws, and what the UI's calls reject with.
|
|
77
|
+
* `instanceof` matches every `ToolError`, including the ones the runtime throws.
|
|
78
|
+
*/
|
|
79
|
+
export class ToolError extends Error {
|
|
80
|
+
constructor(code: string, message: string, options?: ToolErrorOptions);
|
|
81
|
+
readonly name: "ToolError";
|
|
82
|
+
readonly code: string; // such as "invalid_arguments", "not_allowed" or "timeout"
|
|
83
|
+
readonly retryable: boolean; // the same call may work if tried again
|
|
84
|
+
readonly data: unknown; // details, such as the error body a provider sent
|
|
85
|
+
readonly link: string | undefined; // where the person connects or chooses
|
|
86
|
+
}
|
|
87
|
+
/** What a `ToolError` carries besides its code and message. */
|
|
88
|
+
export type ToolErrorOptions = {
|
|
89
|
+
retryable?: boolean;
|
|
90
|
+
data?: unknown;
|
|
91
|
+
link?: string;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** Every item of a paged list, following each page's cursor to the end. */
|
|
95
|
+
export function paginate<P, I>(options: {
|
|
96
|
+
page: (cursor: string | undefined) => Promise<P>; // the first has no cursor
|
|
97
|
+
items: (page: P) => readonly I[];
|
|
98
|
+
next: (page: P) => string | null | undefined; // the next cursor; none at the end
|
|
99
|
+
limit?: number; // stop at this many items, with a warning if more remain
|
|
100
|
+
}): Promise<I[]>;
|
|
101
|
+
|
|
102
|
+
/** `fn` on each item, a few at a time, with results in the items' order. */
|
|
103
|
+
export function map<T, R>(
|
|
104
|
+
items: readonly T[],
|
|
105
|
+
fn: (item: T, index: number) => Promise<R>,
|
|
106
|
+
options?: { concurrency?: number }, // at most this many at once; default 5
|
|
107
|
+
): Promise<R[]>;
|
|
108
|
+
|
|
109
|
+
/** The app's SQLite database. */
|
|
110
|
+
export const db: {
|
|
111
|
+
/** One statement, or several in one transaction; results come back in order. */
|
|
112
|
+
execute<S extends Statement<unknown>[]>(
|
|
113
|
+
...statements: S
|
|
114
|
+
): Promise<Results<S>>;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* A statement. Each `${value}` is a bound parameter, never spliced into the SQL.
|
|
119
|
+
*/
|
|
120
|
+
export function sql<Row = never>(
|
|
121
|
+
strings: TemplateStringsArray,
|
|
122
|
+
...values: Value[]
|
|
123
|
+
): Statement<Row>;
|
|
124
|
+
|
|
125
|
+
/** SQL and its parameters. `Row` types its rows. */
|
|
126
|
+
export type Statement<Row> = { sql: string; params: Value[] };
|
|
127
|
+
/** The rows a statement returns, and how many rows it changed. */
|
|
128
|
+
export type Result<Row> = { rows: Row[]; changes: number };
|
|
129
|
+
/** One result per statement, in order. */
|
|
130
|
+
export type Results<S> = {
|
|
131
|
+
[K in keyof S]: S[K] extends Statement<infer Row> ? Result<Row> : never;
|
|
132
|
+
};
|
|
133
|
+
/** A value a statement binds. */
|
|
134
|
+
export type Value = string | number | boolean | null;
|
|
135
|
+
|
|
136
|
+
/** An event handler: called with each batch of the named event. */
|
|
137
|
+
export function onEvent<K extends keyof Events>(
|
|
138
|
+
name: K, // such as "linear.issue.updated"
|
|
139
|
+
fn: (events: Events[K][], context: HandlerContext) => Promise<void>,
|
|
140
|
+
): EventHandler;
|
|
141
|
+
|
|
142
|
+
/** A schedule handler: called on each tick of a cron schedule. */
|
|
143
|
+
export function onSchedule(
|
|
144
|
+
cron: string, // such as "0 3 * * *"; UTC unless it starts with CRON_TZ=
|
|
145
|
+
fn: (context: HandlerContext) => Promise<void>,
|
|
146
|
+
): ScheduleHandler;
|
|
147
|
+
|
|
148
|
+
/** Opaque: only Indent calls a handler. */
|
|
149
|
+
export interface EventHandler {}
|
|
150
|
+
/** Opaque: only Indent calls a handler. */
|
|
151
|
+
export interface ScheduleHandler {}
|
|
152
|
+
|
|
153
|
+
/** What a handler is called with. */
|
|
154
|
+
export type HandlerContext = {
|
|
155
|
+
auth: Auth; // always the indent actor
|
|
156
|
+
key: string; // the same on every delivery of one batch or tick
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
/** Starts a session, waits for it to finish, and returns its final reply. */
|
|
160
|
+
export function session(input: SessionInput<string>): Promise<string>;
|
|
161
|
+
/** Starts a session, waits for it to finish, and returns its result as a `T`. */
|
|
162
|
+
export function session<T extends object>(input: SessionInput<T>): Promise<T>;
|
|
163
|
+
|
|
164
|
+
/** What a session works on, what it can call, and how its result is checked. */
|
|
165
|
+
export type SessionInput<T> = {
|
|
166
|
+
prompt: string;
|
|
167
|
+
allow?: readonly Allowed[]; // default: every installation the app names
|
|
168
|
+
check?: (result: T) => string | readonly string[] | undefined;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
/** `MCP_Linear["acme"]`, one of its operations, or one of the app's functions. */
|
|
172
|
+
export type Allowed = { readonly [operation: string]: Operation } | Operation;
|
|
173
|
+
/** An operation, or one of the app's functions. */
|
|
174
|
+
export type Operation = (...args: never[]) => Promise<unknown>;
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* What `session()` throws when a session fails, is stopped, or fails its checks.
|
|
178
|
+
*/
|
|
179
|
+
export class SessionError extends Error {
|
|
180
|
+
readonly name: "SessionError";
|
|
181
|
+
readonly sessionId: string; // to find the session's transcript
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Defines a workflow from its `run` function. */
|
|
185
|
+
export function workflow<I>(definition: {
|
|
186
|
+
oneAtATime?: (input: I) => string;
|
|
187
|
+
run(input: I, auth: Auth): Promise<void>;
|
|
188
|
+
}): Workflow<I>;
|
|
189
|
+
|
|
190
|
+
/** Opaque. `I` is the input it is started with. */
|
|
191
|
+
export interface Workflow<I> {}
|
|
192
|
+
|
|
193
|
+
/** Starts a run of a workflow with an input, a key, and the `auth` it acts for. */
|
|
194
|
+
export function start<I>(
|
|
195
|
+
workflow: Workflow<I>,
|
|
196
|
+
input: I,
|
|
197
|
+
key: string,
|
|
198
|
+
auth: Auth, // who the run is for
|
|
199
|
+
): Promise<void>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
function tag(kind) {
|
|
2
|
+
return (fn) => Object.assign((async (input, context) => fn(input, {
|
|
3
|
+
...context,
|
|
4
|
+
cache: appCache(context.auth.actor, null, new Map()),
|
|
5
|
+
})), { kind });
|
|
6
|
+
}
|
|
7
|
+
export { ToolError } from "./errors.js";
|
|
8
|
+
export { map, paginate } from "./helpers.js";
|
|
9
|
+
export const query = tag("query");
|
|
10
|
+
export const mutation = tag("mutation");
|
|
11
|
+
export const sql = (strings, ...values) => ({
|
|
12
|
+
sql: strings.join("?"),
|
|
13
|
+
params: values,
|
|
14
|
+
});
|
|
15
|
+
const onIndentOnly = (name) => async (..._args) => {
|
|
16
|
+
throw new Error(`${name} runs only on Indent`);
|
|
17
|
+
};
|
|
18
|
+
export const onEvent = () => ({});
|
|
19
|
+
export const onSchedule = () => ({});
|
|
20
|
+
export const workflow = () => ({});
|
|
21
|
+
export const session = onIndentOnly("session");
|
|
22
|
+
export const start = onIndentOnly("start");
|
|
23
|
+
function database() {
|
|
24
|
+
const bridge = globalThis.__nexusDb;
|
|
25
|
+
if (bridge === undefined)
|
|
26
|
+
throw new Error("db.execute runs only in an app's runtime");
|
|
27
|
+
return bridge;
|
|
28
|
+
}
|
|
29
|
+
export const db = {
|
|
30
|
+
async execute(...statements) {
|
|
31
|
+
const results = await database()(statements.map(({ sql, params }) => ({ sql, params })));
|
|
32
|
+
return results;
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
// The cache lives in the app's own database, so it is wherever the app's data is.
|
|
36
|
+
const CACHE_TABLE = "_indent_cache";
|
|
37
|
+
const CREATE_CACHE = {
|
|
38
|
+
sql: `CREATE TABLE IF NOT EXISTS ${CACHE_TABLE} (key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL, stored_at INTEGER NOT NULL)`,
|
|
39
|
+
params: [],
|
|
40
|
+
};
|
|
41
|
+
const UNIT_MS = { day: 86_400_000, hour: 3_600_000, minute: 60_000, second: 1000 };
|
|
42
|
+
/** Entries nobody has stored for a week go, so the cache can't fill the database. */
|
|
43
|
+
const RETENTION_MS = 7 * UNIT_MS.day;
|
|
44
|
+
function milliseconds(duration) {
|
|
45
|
+
const [count, unit = ""] = duration.split(" ");
|
|
46
|
+
const ms = UNIT_MS[unit.replace(/s$/u, "")];
|
|
47
|
+
if (ms === undefined || !Number.isFinite(Number(count)))
|
|
48
|
+
throw new Error(`Not a duration: ${duration}`);
|
|
49
|
+
return Number(count) * ms;
|
|
50
|
+
}
|
|
51
|
+
/** Runs cache statements, creating the table the first time one finds it missing. */
|
|
52
|
+
async function cacheDb(statements) {
|
|
53
|
+
try {
|
|
54
|
+
return await database()(statements);
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
if (!(error instanceof Error && /no such table/iu.test(error.message)))
|
|
58
|
+
throw error;
|
|
59
|
+
const [, ...results] = await database()([CREATE_CACHE, ...statements]);
|
|
60
|
+
return results;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function appCache(actor, viewer, loading) {
|
|
64
|
+
const name = (key) => JSON.stringify([viewer, key]);
|
|
65
|
+
async function lookup(id, options) {
|
|
66
|
+
const { key, freshFor, load } = options;
|
|
67
|
+
const [{ rows }] = (await cacheDb([
|
|
68
|
+
{ sql: `SELECT value, stored_at FROM ${CACHE_TABLE} WHERE key = ?`, params: [id] },
|
|
69
|
+
]));
|
|
70
|
+
const [hit] = rows;
|
|
71
|
+
if (hit !== undefined && Date.now() - hit.stored_at < milliseconds(freshFor))
|
|
72
|
+
return JSON.parse(hit.value);
|
|
73
|
+
let value;
|
|
74
|
+
try {
|
|
75
|
+
value = await load();
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (hit === undefined)
|
|
79
|
+
throw error;
|
|
80
|
+
const at = new Date(hit.stored_at).toISOString();
|
|
81
|
+
console.warn(`cache: loading ${JSON.stringify(key)} failed, so it returned the value stored ` +
|
|
82
|
+
`at ${at}: ${error instanceof Error ? error.message : String(error)}`);
|
|
83
|
+
return JSON.parse(hit.value);
|
|
84
|
+
}
|
|
85
|
+
const storedAt = Date.now();
|
|
86
|
+
await cacheDb([
|
|
87
|
+
{
|
|
88
|
+
sql: `INSERT OR REPLACE INTO ${CACHE_TABLE} (key, value, stored_at) VALUES (?, ?, ?)`,
|
|
89
|
+
params: [id, JSON.stringify(value) ?? "null", storedAt],
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
sql: `DELETE FROM ${CACHE_TABLE} WHERE stored_at < ?`,
|
|
93
|
+
params: [storedAt - RETENTION_MS],
|
|
94
|
+
},
|
|
95
|
+
]);
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
get(options) {
|
|
100
|
+
const id = name(options.key);
|
|
101
|
+
const running = loading.get(id);
|
|
102
|
+
if (running !== undefined)
|
|
103
|
+
return running;
|
|
104
|
+
const started = lookup(id, options).finally(() => loading.delete(id));
|
|
105
|
+
loading.set(id, started);
|
|
106
|
+
return started;
|
|
107
|
+
},
|
|
108
|
+
async invalidate(key) {
|
|
109
|
+
await cacheDb([{ sql: `DELETE FROM ${CACHE_TABLE} WHERE key = ?`, params: [name(key)] }]);
|
|
110
|
+
},
|
|
111
|
+
forViewer() {
|
|
112
|
+
if (actor.kind !== "user")
|
|
113
|
+
throw new Error("forViewer needs a person behind the call");
|
|
114
|
+
return appCache(actor, actor.id, loading);
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** `dist/app_manifest.json`: what the build found in the code. */
|
|
2
|
+
export type BuiltManifest = {
|
|
3
|
+
app: string; // the repository's name
|
|
4
|
+
commit: string; // the commit it was built from
|
|
5
|
+
dirty: boolean; // true when the working tree had uncommitted changes
|
|
6
|
+
sdk: string; // the @indent-com/nexus-sdk version
|
|
7
|
+
installations: { service: string; alias: string }[]; // such as MCP_Linear, "acme"
|
|
8
|
+
me: string[]; // services it calls through me, such as "MCP_Linear"
|
|
9
|
+
env: string[]; // every environment variable the code reads
|
|
10
|
+
entrypoints: {
|
|
11
|
+
name: string; // file and export, such as "issues/assign"
|
|
12
|
+
kind: "query" | "mutation" | "event" | "schedule";
|
|
13
|
+
event?: string; // an event handler's event, such as "linear.issue.updated"
|
|
14
|
+
cron?: string; // a schedule handler's cron string
|
|
15
|
+
input: JsonSchema;
|
|
16
|
+
output: JsonSchema;
|
|
17
|
+
description: string; // the doc comment
|
|
18
|
+
perViewer: boolean; // a query that declares context or calls me
|
|
19
|
+
me: string[]; // services it calls through me
|
|
20
|
+
env: string[]; // variables it reads
|
|
21
|
+
error?: string; // why the build could not make it; calling it fails with this
|
|
22
|
+
}[];
|
|
23
|
+
workflows: { name: string; input: JsonSchema }[];
|
|
24
|
+
functions: {
|
|
25
|
+
name: string; // a query, mutation or function that a session allows
|
|
26
|
+
description: string; // the doc comment
|
|
27
|
+
input: JsonSchema;
|
|
28
|
+
result: JsonSchema;
|
|
29
|
+
}[];
|
|
30
|
+
files: { path: string; sha256: string; bytes: number }[]; // every file in dist/
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** A JSON Schema the build made from a TypeScript type. */
|
|
34
|
+
export type JsonSchema = { readonly [keyword: string]: unknown };
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Query } from "@indent-com/nexus-sdk";
|
|
2
|
+
import type { Reading } from "@indent-com/nexus-sdk/client";
|
|
3
|
+
|
|
4
|
+
export type { Reading };
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Reads a query in a component, as in `useCall(issues, { team: "ENG" })`.
|
|
8
|
+
* Passing a mutation is a type error.
|
|
9
|
+
*/
|
|
10
|
+
export function useCall<I, O>(query: Query<I, O>, input?: I): Reading<O>;
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { useCallback, useSyncExternalStore } from "react";
|
|
2
|
+
import { read, watch } from "./store.js";
|
|
3
|
+
export const useCall = (query, input) => {
|
|
4
|
+
const key = JSON.stringify(input ?? {});
|
|
5
|
+
const subscribe = useCallback((notify) => watch(query, input, notify), [query, key]);
|
|
6
|
+
return useSyncExternalStore(subscribe, () => read(query, input));
|
|
7
|
+
};
|
package/dist/schema.d.ts
ADDED
package/dist/schema.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
export class BuildError extends Error {
|
|
3
|
+
name = "BuildError";
|
|
4
|
+
}
|
|
5
|
+
export function toSchema(checker, type, path) {
|
|
6
|
+
const convert = (type, path, seen) => {
|
|
7
|
+
const fail = (reason) => {
|
|
8
|
+
throw new BuildError(`${path} is ${checker.typeToString(type)}, ${reason}`);
|
|
9
|
+
};
|
|
10
|
+
if (type.flags & ts.TypeFlags.Boolean)
|
|
11
|
+
return { type: "boolean" };
|
|
12
|
+
if (type.flags & ts.TypeFlags.String)
|
|
13
|
+
return { type: "string" };
|
|
14
|
+
if (type.flags & ts.TypeFlags.Number)
|
|
15
|
+
return { type: "number" };
|
|
16
|
+
if (type.flags & ts.TypeFlags.Null)
|
|
17
|
+
return { type: "null" };
|
|
18
|
+
if (type.isStringLiteral() || type.isNumberLiteral())
|
|
19
|
+
return { const: type.value };
|
|
20
|
+
if (type.flags & ts.TypeFlags.BooleanLiteral) {
|
|
21
|
+
return { const: checker.typeToString(type) === "true" };
|
|
22
|
+
}
|
|
23
|
+
if (type.isUnion())
|
|
24
|
+
return union(type, path, seen);
|
|
25
|
+
if (!(type.flags & (ts.TypeFlags.Object | ts.TypeFlags.Intersection))) {
|
|
26
|
+
return fail("which is not a JSON type");
|
|
27
|
+
}
|
|
28
|
+
if (seen.includes(type))
|
|
29
|
+
return fail("which is recursive");
|
|
30
|
+
const inner = [...seen, type];
|
|
31
|
+
if (checker.isArrayType(type)) {
|
|
32
|
+
const [item] = checker.getTypeArguments(type);
|
|
33
|
+
return { type: "array", items: convert(item, `${path}[]`, inner) };
|
|
34
|
+
}
|
|
35
|
+
const callable = type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0;
|
|
36
|
+
const isClass = (type.getSymbol()?.flags ?? 0) & ts.SymbolFlags.Class;
|
|
37
|
+
if (callable || isClass || checker.isTupleType(type)) {
|
|
38
|
+
return fail("which is not a JSON type");
|
|
39
|
+
}
|
|
40
|
+
const index = checker.getIndexInfoOfType(type, ts.IndexKind.String);
|
|
41
|
+
const properties = checker.getPropertiesOfType(type);
|
|
42
|
+
const required = properties
|
|
43
|
+
.filter((property) => !(property.flags & ts.SymbolFlags.Optional))
|
|
44
|
+
.map((property) => property.name);
|
|
45
|
+
const entries = properties.map((property) => {
|
|
46
|
+
const schema = convert(checker.getTypeOfSymbol(property), `${path}.${property.name}`, inner);
|
|
47
|
+
const description = ts.displayPartsToString(property.getDocumentationComment(checker));
|
|
48
|
+
return [property.name, description ? { ...schema, description } : schema];
|
|
49
|
+
});
|
|
50
|
+
return {
|
|
51
|
+
type: "object",
|
|
52
|
+
properties: Object.fromEntries(entries),
|
|
53
|
+
...(required.length > 0 ? { required } : {}),
|
|
54
|
+
additionalProperties: index ? convert(index.type, `${path}[string]`, inner) : false,
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
const union = (type, path, seen) => {
|
|
58
|
+
const schemas = type.types
|
|
59
|
+
.filter((member) => !(member.flags & ts.TypeFlags.Undefined))
|
|
60
|
+
.map((member) => member.flags & ts.TypeFlags.BooleanLiteral
|
|
61
|
+
? { type: "boolean" }
|
|
62
|
+
: convert(member, path, seen));
|
|
63
|
+
const unique = [...new Map(schemas.map((s) => [JSON.stringify(s), s])).values()];
|
|
64
|
+
if (unique.length === 1)
|
|
65
|
+
return unique[0];
|
|
66
|
+
if (unique.every((schema) => "const" in schema)) {
|
|
67
|
+
return { enum: unique.map((schema) => schema.const) };
|
|
68
|
+
}
|
|
69
|
+
if (unique.every((schema) => Object.keys(schema).join() === "type")) {
|
|
70
|
+
return { type: unique.map((schema) => schema.type) };
|
|
71
|
+
}
|
|
72
|
+
return { anyOf: unique };
|
|
73
|
+
};
|
|
74
|
+
return convert(type, path, []);
|
|
75
|
+
}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Query } from "@indent-com/nexus-sdk";
|
|
2
|
+
import type { Reading } from "@indent-com/nexus-sdk/client";
|
|
3
|
+
import type { Kind } from "./contract.ts";
|
|
4
|
+
export type Stub = ((input: unknown) => Promise<unknown>) & {
|
|
5
|
+
readonly kind: Kind;
|
|
6
|
+
};
|
|
7
|
+
export declare function stub(kind: Kind, path: string): Stub;
|
|
8
|
+
export declare function read<O>(query: Query<never, O>, input: unknown): Reading<O>;
|
|
9
|
+
export declare function watch<O>(query: Query<never, O>, input: unknown, listener: (reading: Reading<O>) => void): () => void;
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { ToolError } from "./errors.js";
|
|
2
|
+
const refreshEvery = 5 * 60_000;
|
|
3
|
+
const paths = new WeakMap();
|
|
4
|
+
const entries = new Map();
|
|
5
|
+
export function stub(kind, path) {
|
|
6
|
+
const call = async (input) => {
|
|
7
|
+
if (kind === "query")
|
|
8
|
+
return request("GET", path, input);
|
|
9
|
+
try {
|
|
10
|
+
return await request("POST", path, input);
|
|
11
|
+
}
|
|
12
|
+
finally {
|
|
13
|
+
for (const entry of entries.values()) {
|
|
14
|
+
if (entry.listeners.size > 0)
|
|
15
|
+
void refresh(entry, true);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const fn = Object.assign(call, { kind });
|
|
20
|
+
paths.set(fn, path);
|
|
21
|
+
return fn;
|
|
22
|
+
}
|
|
23
|
+
export function read(query, input) {
|
|
24
|
+
return entryFor(query, input).reading;
|
|
25
|
+
}
|
|
26
|
+
export function watch(query, input, listener) {
|
|
27
|
+
const entry = entryFor(query, input);
|
|
28
|
+
entry.listeners.add(listener);
|
|
29
|
+
if (entry.listeners.size === 1) {
|
|
30
|
+
const timer = setInterval(() => void refresh(entry), refreshEvery);
|
|
31
|
+
entry.stop = () => clearInterval(timer);
|
|
32
|
+
}
|
|
33
|
+
listener(entry.reading);
|
|
34
|
+
void refresh(entry);
|
|
35
|
+
return () => {
|
|
36
|
+
entry.listeners.delete(listener);
|
|
37
|
+
if (entry.listeners.size === 0)
|
|
38
|
+
entry.stop?.();
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function entryFor(query, input) {
|
|
42
|
+
const path = paths.get(query);
|
|
43
|
+
if (path === undefined)
|
|
44
|
+
throw new Error("Read only queries imported from server/");
|
|
45
|
+
const key = `${path}?${JSON.stringify(input ?? {})}`;
|
|
46
|
+
const found = entries.get(key);
|
|
47
|
+
if (found !== undefined)
|
|
48
|
+
return found;
|
|
49
|
+
const entry = {
|
|
50
|
+
path,
|
|
51
|
+
input,
|
|
52
|
+
reading: { data: undefined, at: null, refreshing: false, error: undefined },
|
|
53
|
+
listeners: new Set(),
|
|
54
|
+
running: false,
|
|
55
|
+
again: false,
|
|
56
|
+
};
|
|
57
|
+
entries.set(key, entry);
|
|
58
|
+
return entry;
|
|
59
|
+
}
|
|
60
|
+
async function refresh(entry, again = false) {
|
|
61
|
+
if (entry.running) {
|
|
62
|
+
entry.again ||= again;
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
entry.running = true;
|
|
66
|
+
update(entry, { ...entry.reading, refreshing: true });
|
|
67
|
+
try {
|
|
68
|
+
const data = await request("GET", entry.path, entry.input);
|
|
69
|
+
update(entry, { data, at: new Date().toISOString(), refreshing: false, error: undefined });
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
update(entry, { ...entry.reading, refreshing: false, error: toolError(error) });
|
|
73
|
+
}
|
|
74
|
+
entry.running = false;
|
|
75
|
+
if (entry.again) {
|
|
76
|
+
entry.again = false;
|
|
77
|
+
await refresh(entry);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function update(entry, reading) {
|
|
81
|
+
entry.reading = reading;
|
|
82
|
+
for (const listener of entry.listeners)
|
|
83
|
+
listener(reading);
|
|
84
|
+
}
|
|
85
|
+
async function request(method, path, input) {
|
|
86
|
+
const body = JSON.stringify(input ?? {});
|
|
87
|
+
let response;
|
|
88
|
+
try {
|
|
89
|
+
response =
|
|
90
|
+
method === "GET"
|
|
91
|
+
? await fetch(`/api/${path}?input=${encodeURIComponent(body)}`)
|
|
92
|
+
: await fetch(`/api/${path}`, {
|
|
93
|
+
method,
|
|
94
|
+
headers: { "content-type": "application/json" },
|
|
95
|
+
body,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
throw toolError(error);
|
|
100
|
+
}
|
|
101
|
+
if (response.ok)
|
|
102
|
+
return (await response.json());
|
|
103
|
+
const failed = await response.json().catch(() => ({}));
|
|
104
|
+
const { error } = failed;
|
|
105
|
+
const message = error?.message ?? `${response.status} ${response.statusText}`;
|
|
106
|
+
throw new ToolError(error?.code ?? "call_failed", message, {
|
|
107
|
+
retryable: error?.retryable,
|
|
108
|
+
data: error?.data,
|
|
109
|
+
link: error?.link,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
/** A failure that never reached the app, such as a dropped connection. */
|
|
113
|
+
function toolError(error) {
|
|
114
|
+
if (error instanceof ToolError)
|
|
115
|
+
return error;
|
|
116
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
117
|
+
return new ToolError("network", message, { retryable: true });
|
|
118
|
+
}
|
package/dist/stubs.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const stubPrefix = "\0nexus-server:";
|
package/dist/stubs.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const stubPrefix = "\0nexus-server:";
|
package/dist/vite.d.ts
ADDED
package/dist/vite.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { join, relative } from "node:path";
|
|
3
|
+
import { parseSync } from "vite";
|
|
4
|
+
import { stubPrefix } from "./stubs.js";
|
|
5
|
+
export function nexus({ root: dir, entrypoints }) {
|
|
6
|
+
const root = realpathSync(dir);
|
|
7
|
+
const server = join(root, "server");
|
|
8
|
+
const module = (name) => name.slice(0, name.lastIndexOf("/"));
|
|
9
|
+
const exported = (name) => name.slice(name.lastIndexOf("/") + 1);
|
|
10
|
+
return {
|
|
11
|
+
name: "nexus-sdk",
|
|
12
|
+
resolveId: {
|
|
13
|
+
order: "pre",
|
|
14
|
+
async handler(source, importer, options) {
|
|
15
|
+
const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
|
|
16
|
+
if (!resolved?.id.startsWith(`${server}/`))
|
|
17
|
+
return resolved;
|
|
18
|
+
return stubPrefix + relative(server, resolved.id).replace(/\.[^./]+$/, "");
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
load(id) {
|
|
22
|
+
if (!id.startsWith(stubPrefix))
|
|
23
|
+
return null;
|
|
24
|
+
const file = id.slice(stubPrefix.length);
|
|
25
|
+
const stubs = entrypoints()
|
|
26
|
+
.filter(({ name }) => module(name) === file)
|
|
27
|
+
.map(({ name, kind }) => {
|
|
28
|
+
const call = `stub(${JSON.stringify(kind)}, ${JSON.stringify(name)})`;
|
|
29
|
+
return `export const ${exported(name)} = ${call};`;
|
|
30
|
+
});
|
|
31
|
+
return [`import { stub } from "@indent-com/nexus-sdk/client";`, ...stubs].join("\n");
|
|
32
|
+
},
|
|
33
|
+
transform: {
|
|
34
|
+
filter: { id: { include: /\.[cm]?[jt]sx?$/, exclude: /\/node_modules\// } },
|
|
35
|
+
async handler(code, id) {
|
|
36
|
+
const { staticImports } = parseSync(id, code, { lang: "js" }).module;
|
|
37
|
+
for (const { moduleRequest, entries } of staticImports) {
|
|
38
|
+
const resolved = await this.resolve(moduleRequest.value, id, { skipSelf: false });
|
|
39
|
+
if (!resolved?.id.startsWith(stubPrefix))
|
|
40
|
+
continue;
|
|
41
|
+
const file = resolved.id.slice(stubPrefix.length);
|
|
42
|
+
const names = new Set(entrypoints().map(({ name }) => name));
|
|
43
|
+
for (const { importName } of entries) {
|
|
44
|
+
const imported = importName.name ?? "default";
|
|
45
|
+
if (importName.kind === "NamespaceObject" || names.has(`${file}/${imported}`)) {
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
this.error(`${relative(root, id)} imports ${imported} from server/${file}, which is not ` +
|
|
49
|
+
"a query or mutation. The UI imports only queries, mutations and types.");
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|