@midsummer-ai/sdk 0.1.0-staging.3121 → 0.1.0-staging.3127

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.
Files changed (47) hide show
  1. package/ai/contract.mjs +39 -0
  2. package/ai/index.d.mts +70 -12
  3. package/ai/index.mjs +74 -5
  4. package/ai/stand-in.mjs +26 -4
  5. package/client.d.mts +1 -1
  6. package/client.mjs +1 -105
  7. package/{connection-Cu2GSOaR.mjs → connection-C_JSWUrt.mjs} +7 -6
  8. package/contract.d.mts +1 -1
  9. package/contract.mjs +1 -1
  10. package/database/client.d.mts +20 -1
  11. package/database/client.mjs +31 -8
  12. package/database/stand-in.d.mts +2 -2
  13. package/database/stand-in.mjs +1 -1
  14. package/email/client.mjs +1 -130
  15. package/email/contract.mjs +1 -1
  16. package/email/index.d.mts +9 -7
  17. package/email/index.mjs +1 -58
  18. package/email/smtp.mjs +1 -2
  19. package/email/stand-in.mjs +1 -1
  20. package/email-DXtpr7pT.mjs +214 -0
  21. package/here-CeqGJW21.mjs +28 -0
  22. package/{index-DNNXNny7.d.mts → index-B9zs0wIp.d.mts} +6 -1
  23. package/{index-sgdyoA2P.d.mts → index-Ci6mGXqz.d.mts} +7 -1
  24. package/index.d.mts +2 -2
  25. package/index.mjs +3 -137
  26. package/package.json +1 -1
  27. package/queues/index.d.mts +17 -5
  28. package/queues/index.mjs +71 -1
  29. package/s3.d.mts +1 -1
  30. package/s3.mjs +1 -1
  31. package/socket.d.mts +1 -1
  32. package/socket.mjs +1 -262
  33. package/src-BKrQAqJN.mjs +519 -0
  34. package/stand-in.d.mts +1 -1
  35. package/{store-lIZ5GxVv.mjs → store-CsBhnabU.mjs} +1 -1
  36. package/{tabs-zCh8kceo.mjs → tabs-gHJHkhm2.mjs} +1 -1
  37. package/vector/contract.d.mts +1 -1
  38. package/vector/contract.mjs +1 -1
  39. package/vector/index.d.mts +2 -2
  40. package/vector/index.mjs +18 -7
  41. package/vector/stand-in.d.mts +1 -1
  42. package/vector/stand-in.mjs +1 -1
  43. package/vector/wire.d.mts +1 -1
  44. package/vector/wire.mjs +1 -339
  45. package/wire-BdNDzlIN.mjs +554 -0
  46. package/wire.d.mts +1 -1
  47. package/schema-CTHQMRsW.mjs +0 -217
package/ai/contract.mjs CHANGED
@@ -38,6 +38,45 @@ const aiContract = [
38
38
  check((await stream.done).outputTokens > 0, "done counts the answer's tokens");
39
39
  }
40
40
  },
41
+ {
42
+ name: "a call made to use a tool gets the tool's call back whole, its arguments as JSON text, and answers once given its result",
43
+ async run(ai) {
44
+ const tools = [{
45
+ name: "lookup",
46
+ description: "Looks a word up.",
47
+ parameters: {
48
+ type: "object",
49
+ properties: { word: { type: "string" } }
50
+ }
51
+ }];
52
+ const [made] = (await ai.complete({
53
+ prompt: "Look up 'river'.",
54
+ tools,
55
+ toolChoice: { name: "lookup" }
56
+ })).toolCalls ?? [];
57
+ check(made !== void 0 && made.name === "lookup" && made.id.length > 0, "the tool's call comes back with an id and the tool's name");
58
+ check(typeof JSON.parse(made.arguments) === "object", "its arguments are JSON text");
59
+ check((await ai.complete({
60
+ messages: [
61
+ {
62
+ role: "user",
63
+ content: "Look up 'river'."
64
+ },
65
+ {
66
+ role: "assistant",
67
+ content: "",
68
+ toolCalls: [made]
69
+ },
70
+ {
71
+ role: "tool",
72
+ toolCallId: made.id,
73
+ content: "A large natural stream of water."
74
+ }
75
+ ],
76
+ tools
77
+ })).text.length > 0, "the Model answers once it has the tool's result");
78
+ }
79
+ },
41
80
  {
42
81
  name: "a Model that is not offered is refused as invalid",
43
82
  async run(ai) {
package/ai/index.d.mts CHANGED
@@ -1,16 +1,22 @@
1
1
  //#region src/ai/index.d.ts
2
2
  /**
3
- * AI: Model calls from a Project's code, through one AI key, streamed or whole, each with the tokens
4
- * and credits it spent.
3
+ * AI: Model calls from a Project's code, streamed or whole, each with the tokens and credits it spent.
4
+ * In a deployment, in any framework, `ai()` calls the team's AI Gateway with no key:
5
5
  *
6
- * const models = ai(aiClient("https://api.midsummer.new", { key: process.env.MIDSUMMER_AI_KEY! }))
6
+ * import { ai } from "@midsummer-ai/sdk/ai"
7
+ *
8
+ * const models = ai()
7
9
  * const answer = await models.complete({ prompt: "Name three rivers" })
8
10
  * const stream = models.stream({ model: "claude-sonnet-5-5", messages: [{ role: "user", content: "Hi" }] })
9
11
  * for await (const text of stream) write(text)
10
12
  * const { credits } = await stream.done
11
13
  *
12
- * The engine is where calls go: the Stand-in (`@midsummer-ai/sdk/ai/stand-in`) for `midsummer dev`,
13
- * or the platform (`aiClient`). Every engine is held to the cases in `@midsummer-ai/sdk/ai/contract`.
14
+ * A call can pass tools (its calls come back as `toolCalls`), ask for JSON to a schema
15
+ * (`responseFormat`), send images in a user message, set a reasoning effort, and name `fallback`
16
+ * Models asked in turn when one can't answer; `model` in what it spent is the one that replied.
17
+ *
18
+ * Given an engine, calls go there instead: the Stand-in (`@midsummer-ai/sdk/ai/stand-in`) in tests, or,
19
+ * from code outside Midsummer, the platform with an AI key (`ai(aiClient(origin, { key }))`). Every engine is held to the cases in `@midsummer-ai/sdk/ai/contract`.
14
20
  * A Model is named as `midsummer ai model list` lists it; leaving it out picks the default.
15
21
  *
16
22
  * Every failure is an `AiError`; its `code` tells you which kind: `invalid` (no such Model, nothing
@@ -22,9 +28,32 @@ declare class AiError extends Error {
22
28
  readonly code: AiErrorCode;
23
29
  constructor(code: AiErrorCode, why: string);
24
30
  }
31
+ /** A piece of a user message: text, or an image by its `https:` or `data:` address. */
32
+ type Part = {
33
+ readonly type: "text";
34
+ readonly text: string;
35
+ } | {
36
+ readonly type: "image";
37
+ readonly url: string;
38
+ };
39
+ /** A tool the Model called: the id its result refers to, the tool's name and its arguments as JSON text. */
40
+ interface ToolCall {
41
+ readonly id: string;
42
+ readonly name: string;
43
+ readonly arguments: string;
44
+ }
45
+ /** One message: an assistant's may carry the tool calls it made, and a `tool` message is the result of the call `toolCallId` refers to. */
25
46
  interface Message {
26
- readonly role: "system" | "user" | "assistant";
27
- readonly content: string;
47
+ readonly role: "system" | "user" | "assistant" | "tool";
48
+ readonly content: string | ReadonlyArray<Part>;
49
+ readonly toolCalls?: ReadonlyArray<ToolCall>;
50
+ readonly toolCallId?: string;
51
+ }
52
+ /** A tool the Model may call: its name, what it does and its arguments as a JSON schema. */
53
+ interface Tool {
54
+ readonly name: string;
55
+ readonly description?: string;
56
+ readonly parameters?: Readonly<Record<string, unknown>>;
28
57
  }
29
58
  /** What to ask: a `prompt` (after an optional `system` prompt) or a conversation of `messages`. */
30
59
  interface Ask {
@@ -36,6 +65,20 @@ interface Ask {
36
65
  readonly maxTokens?: number;
37
66
  /** 0 to 2. */
38
67
  readonly temperature?: number;
68
+ readonly tools?: ReadonlyArray<Tool>;
69
+ /** Whether the Model may call tools (`auto`), must not (`none`), must call one (`required`) or the one named. */
70
+ readonly toolChoice?: "auto" | "none" | "required" | {
71
+ readonly name: string;
72
+ };
73
+ /** An answer as JSON: to `schema` when given, else any JSON object. */
74
+ readonly responseFormat?: {
75
+ readonly type: "json";
76
+ readonly schema?: Readonly<Record<string, unknown>>;
77
+ readonly name?: string;
78
+ };
79
+ readonly reasoningEffort?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
80
+ /** Up to three Models asked in turn when the one before can't answer. */
81
+ readonly fallback?: ReadonlyArray<string>;
39
82
  /**
40
83
  * Names this call for a day. A retry with it after a lost answer gets the first call's answer and
41
84
  * is not charged again; while the first still runs, it fails as `conflict`.
@@ -44,15 +87,27 @@ interface Ask {
44
87
  }
45
88
  /** What a call spent: its tokens, and their price in credits under the catalogue version `catalogue`. */
46
89
  interface Spent {
90
+ /** The Model that replied: the one asked, or a fallback. */
47
91
  readonly model: string;
48
92
  readonly inputTokens: number;
93
+ /** Of `inputTokens`, those read from the provider's cache, priced as it prices them. */
94
+ readonly cachedTokens?: number;
49
95
  readonly outputTokens: number;
50
96
  readonly credits: number;
51
97
  readonly catalogue: string;
52
98
  }
53
- /** A piece of the answer, or, last, what the call spent. */
99
+ /** A piece of a tool call: `index` tells calls apart, `id` and `name` come with its first piece, `arguments` add up. */
100
+ interface ToolCallPiece {
101
+ readonly index: number;
102
+ readonly id?: string;
103
+ readonly name?: string;
104
+ readonly arguments: string;
105
+ }
106
+ /** A piece of the answer or of a tool call, or, last, what the call spent. */
54
107
  type AiEvent = {
55
108
  readonly text: string;
109
+ } | {
110
+ readonly toolCall: ToolCallPiece;
56
111
  } | {
57
112
  readonly done: Spent;
58
113
  };
@@ -62,16 +117,19 @@ interface AiEngine {
62
117
  }
63
118
  interface Answer extends Spent {
64
119
  readonly text: string;
120
+ readonly toolCalls?: ReadonlyArray<ToolCall>;
65
121
  }
66
- /** An answer's text as it arrives; `done` settles with what it spent once it has all arrived. */
122
+ /** An answer's text as it arrives; `done` settles with what it spent, and the tools it called, once it has all arrived. */
67
123
  interface AnswerStream extends AsyncIterable<string> {
68
- readonly done: Promise<Spent>;
124
+ readonly done: Promise<Spent & {
125
+ readonly toolCalls?: ReadonlyArray<ToolCall>;
126
+ }>;
69
127
  }
70
128
  interface Ai {
71
129
  complete(input: Ask): Promise<Answer>;
72
130
  stream(input: Ask): AnswerStream;
73
131
  }
74
- declare function ai(engine: AiEngine): Ai;
132
+ declare function ai(given?: AiEngine): Ai;
75
133
  type Fetch = (url: string, init: RequestInit) => Promise<Response>;
76
134
  /**
77
135
  * The platform's AI Gateway at `origin` (the API's), for the AI key `key`: each call is one POST to
@@ -91,4 +149,4 @@ declare function boundAi(handle: {
91
149
  ask(input: Ask): Promise<ReadableStream<Uint8Array>>;
92
150
  }): AiEngine;
93
151
  //#endregion
94
- export { Ai, AiEngine, AiError, AiErrorCode, AiEvent, Answer, AnswerStream, Ask, Message, Spent, ai, aiClient, boundAi };
152
+ export { Ai, AiEngine, AiError, AiErrorCode, AiEvent, Answer, AnswerStream, Ask, Message, Part, Spent, Tool, ToolCall, ToolCallPiece, ai, aiClient, boundAi };
package/ai/index.mjs CHANGED
@@ -1,4 +1,29 @@
1
+ import { n as late, t as here } from "../here-CeqGJW21.mjs";
1
2
  //#region src/ai/index.ts
3
+ /**
4
+ * AI: Model calls from a Project's code, streamed or whole, each with the tokens and credits it spent.
5
+ * In a deployment, in any framework, `ai()` calls the team's AI Gateway with no key:
6
+ *
7
+ * import { ai } from "@midsummer-ai/sdk/ai"
8
+ *
9
+ * const models = ai()
10
+ * const answer = await models.complete({ prompt: "Name three rivers" })
11
+ * const stream = models.stream({ model: "claude-sonnet-5-5", messages: [{ role: "user", content: "Hi" }] })
12
+ * for await (const text of stream) write(text)
13
+ * const { credits } = await stream.done
14
+ *
15
+ * A call can pass tools (its calls come back as `toolCalls`), ask for JSON to a schema
16
+ * (`responseFormat`), send images in a user message, set a reasoning effort, and name `fallback`
17
+ * Models asked in turn when one can't answer; `model` in what it spent is the one that replied.
18
+ *
19
+ * Given an engine, calls go there instead: the Stand-in (`@midsummer-ai/sdk/ai/stand-in`) in tests, or,
20
+ * from code outside Midsummer, the platform with an AI key (`ai(aiClient(origin, { key }))`). Every engine is held to the cases in `@midsummer-ai/sdk/ai/contract`.
21
+ * A Model is named as `midsummer ai model list` lists it; leaving it out picks the default.
22
+ *
23
+ * Every failure is an `AiError`; its `code` tells you which kind: `invalid` (no such Model, nothing
24
+ * asked), `forbidden` (the key is not valid), `quota` (the Team's usage is holding back its calls),
25
+ * `conflict` (a retry by `idempotencyKey` of a call still under way) or `unavailable` (try again).
26
+ */
2
27
  var AiError = class extends Error {
3
28
  code;
4
29
  constructor(code, why) {
@@ -7,22 +32,50 @@ var AiError = class extends Error {
7
32
  this.name = "AiError";
8
33
  }
9
34
  };
35
+ /** Tool call pieces, added up into whole calls in order. */
36
+ function toolCalls() {
37
+ const calls = /* @__PURE__ */ new Map();
38
+ return {
39
+ add({ index, id, name, arguments: more }) {
40
+ const made = calls.get(index) ?? {
41
+ id: "",
42
+ name: "",
43
+ arguments: ""
44
+ };
45
+ calls.set(index, {
46
+ id: id ?? made.id,
47
+ name: name ?? made.name,
48
+ arguments: made.arguments + more
49
+ });
50
+ },
51
+ whole: () => calls.size ? { toolCalls: [...calls.entries()].sort(([a], [b]) => a - b).map(([, made]) => made) } : {}
52
+ };
53
+ }
10
54
  /** Checks a question before it leaves the caller. */
11
55
  function checked(input) {
12
56
  if (Boolean(input.prompt) === Boolean(input.messages)) throw new AiError("invalid", "Give a prompt or messages.");
13
57
  if (input.messages && !input.messages.length) throw new AiError("invalid", "Give at least one message.");
14
58
  if (input.maxTokens !== void 0 && !(Number.isInteger(input.maxTokens) && input.maxTokens >= 1 && input.maxTokens <= 32e3)) throw new AiError("invalid", "maxTokens is a whole number from 1 to 32,000.");
15
59
  if (input.temperature !== void 0 && !(input.temperature >= 0 && input.temperature <= 2)) throw new AiError("invalid", "temperature is from 0 to 2.");
60
+ if ((input.fallback?.length ?? 0) > 3) throw new AiError("invalid", "Name at most 3 fallback models.");
16
61
  return input;
17
62
  }
18
- function ai(engine) {
63
+ function ai(given) {
64
+ const engine = given ?? late(() => {
65
+ const handle = here()?.ai;
66
+ if (handle) return boundAi(handle);
67
+ throw new AiError("forbidden", "This code runs outside a deployment, so it calls models with an AI key: ai(aiClient(origin, { key })).");
68
+ });
19
69
  return {
20
70
  async complete(input) {
21
71
  let text = "";
72
+ const calls = toolCalls();
22
73
  for await (const event of engine.ask(checked(input))) if ("text" in event) text += event.text;
74
+ else if ("toolCall" in event) calls.add(event.toolCall);
23
75
  else return {
24
76
  ...event.done,
25
- text
77
+ text,
78
+ ...calls.whole()
26
79
  };
27
80
  throw new AiError("unavailable", "The answer ended early. Try again.");
28
81
  },
@@ -45,8 +98,13 @@ function ai(engine) {
45
98
  }
46
99
  async function* texts() {
47
100
  try {
101
+ const calls = toolCalls();
48
102
  for await (const event of engine.ask(asked)) if ("text" in event) yield event.text;
49
- else return settle(event.done);
103
+ else if ("toolCall" in event) calls.add(event.toolCall);
104
+ else return settle({
105
+ ...event.done,
106
+ ...calls.whole()
107
+ });
50
108
  throw new AiError("unavailable", "The answer ended early. Try again.");
51
109
  } catch (error) {
52
110
  fail(error);
@@ -75,12 +133,23 @@ function parsed(line) {
75
133
  const count = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
76
134
  if (!object(event)) throw broken();
77
135
  if (typeof event.text === "string") return { text: event.text };
136
+ const call = event.toolCall;
137
+ if (object(call)) {
138
+ if (!count(call.index) || typeof call.arguments !== "string" || call.id !== void 0 && typeof call.id !== "string" || call.name !== void 0 && typeof call.name !== "string") throw broken();
139
+ return { toolCall: {
140
+ index: call.index,
141
+ ...typeof call.id === "string" ? { id: call.id } : {},
142
+ ...typeof call.name === "string" ? { name: call.name } : {},
143
+ arguments: call.arguments
144
+ } };
145
+ }
78
146
  const done = event.done;
79
147
  if (object(done)) {
80
- if (typeof done.model !== "string" || !count(done.inputTokens) || !count(done.outputTokens) || typeof done.credits !== "number" || !(done.credits >= 0) || typeof done.catalogue !== "string") throw broken();
148
+ if (typeof done.model !== "string" || !count(done.inputTokens) || !count(done.outputTokens) || typeof done.credits !== "number" || !(done.credits >= 0) || typeof done.catalogue !== "string" || done.cachedTokens !== void 0 && !count(done.cachedTokens)) throw broken();
81
149
  return { done: {
82
150
  model: done.model,
83
151
  inputTokens: done.inputTokens,
152
+ ...done.cachedTokens ? { cachedTokens: done.cachedTokens } : {},
84
153
  outputTokens: done.outputTokens,
85
154
  credits: done.credits,
86
155
  catalogue: done.catalogue
@@ -133,7 +202,7 @@ function aiClient(origin, options) {
133
202
  }
134
203
  if (!response.ok || !response.body) {
135
204
  const why = await response.json().then((body) => typeof body.error === "string" ? body.error : void 0, () => void 0);
136
- throw new AiError(CODES[response.status] ?? "unavailable", why ?? `The AI Gateway answered ${response.status}.`);
205
+ throw new AiError(CODES[response.status] ?? "unavailable", why ?? `The AI Gateway returned ${response.status}.`);
137
206
  }
138
207
  try {
139
208
  yield* eventsOf(response.body);
package/ai/stand-in.mjs CHANGED
@@ -9,8 +9,11 @@ import { AiError } from "./index.mjs";
9
9
  * await models.complete({ prompt: "Hi" }) // { text: "You asked: Hi", model: "stand-in", credits: 0, … }
10
10
  *
11
11
  * It offers the Models it is given (`stand-in` unless told), the first the default. Tokens are
12
- * counted at about four characters a token, and cost nothing.
12
+ * counted at about four characters a token, and cost nothing. Made to call a tool (`toolChoice`
13
+ * `required` or a name), it calls it with no arguments; a fallback is never needed.
13
14
  */
15
+ /** A message's text, without its images. */
16
+ const textOf = (content) => typeof content === "string" ? content : content.map((part) => part.type === "text" ? part.text : "").join("");
14
17
  function aiStandIn(options = {}) {
15
18
  const models = options.models?.length ? options.models : ["stand-in"];
16
19
  const tokens = (text) => Math.ceil(text.length / 4);
@@ -25,12 +28,31 @@ function aiStandIn(options = {}) {
25
28
  content: input.prompt ?? ""
26
29
  }]];
27
30
  const last = messages.filter((message) => message.role !== "system").at(-1);
28
- if (last?.role !== "user" || !last.content.trim()) throw new AiError("invalid", "End with a user message that asks something.");
29
- const answer = `You asked: ${last.content}`.slice(0, (input.maxTokens ?? 1024) * 4);
31
+ if (!(last?.role === "tool" || last?.role === "user" && textOf(last.content).trim())) throw new AiError("invalid", "End with a user message that asks something, or with the results of the tools the model called.");
32
+ const inputTokens = tokens(messages.map((message) => textOf(message.content)).join(""));
33
+ const tool = typeof input.toolChoice === "object" ? input.toolChoice.name : input.toolChoice === "required" ? input.tools?.[0]?.name : void 0;
34
+ if (tool && last.role === "user") {
35
+ if (!input.tools?.some((given) => given.name === tool)) throw new AiError("invalid", `toolChoice names ${tool}, which isn't one of the tools given.`);
36
+ yield { toolCall: {
37
+ index: 0,
38
+ id: "call_stand_in_1",
39
+ name: tool,
40
+ arguments: "{}"
41
+ } };
42
+ yield { done: {
43
+ model,
44
+ inputTokens,
45
+ outputTokens: 1,
46
+ credits: 0,
47
+ catalogue: "stand-in"
48
+ } };
49
+ return;
50
+ }
51
+ const answer = `You asked: ${textOf(last.content)}`.slice(0, (input.maxTokens ?? 1024) * 4);
30
52
  for (const piece of answer.match(/\S+\s*/g) ?? []) yield { text: piece };
31
53
  yield { done: {
32
54
  model,
33
- inputTokens: tokens(messages.map((message) => message.content).join("")),
55
+ inputTokens,
34
56
  outputTokens: tokens(answer),
35
57
  credits: 0,
36
58
  catalogue: "stand-in"
package/client.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { m as StorageEngine } from "./index-sgdyoA2P.mjs";
1
+ import { m as StorageEngine } from "./index-Ci6mGXqz.mjs";
2
2
  import { S3Credential } from "./s3.mjs";
3
3
  import { Transport } from "./wire.mjs";
4
4
  import { socket } from "./socket.mjs";
package/client.mjs CHANGED
@@ -1,106 +1,2 @@
1
- import { h as StorageError } from "./names-DfCBKupJ.mjs";
2
- import { bucketsOf, remote, repeatable, serve } from "./wire.mjs";
3
- import { keyed, sameHex, sign, socket } from "./socket.mjs";
4
- //#region src/client.ts
5
- /**
6
- * Storage from code holding a Storage Key, as an app reaches it: calls are written as usual and travel
7
- * over one WebSocket, so a client pays for one request when it connects, not one a call. Where a
8
- * connection cannot open, they travel as batched HTTP, signed with the same key.
9
- *
10
- * const files = storage(client("https://api.<site>", { key, secret }))
11
- * await files.bucket("avatars").put("ada.png", bytes)
12
- *
13
- * The calls made in the same turn travel as one batch frame either way. A call whose connection drops
14
- * before it gets a reply (a server going away on deploy) is sent again on a new connection when the wire
15
- * says repeating it is safe (`repeatable` in `@midsummer-ai/sdk/wire`), and is otherwise `unavailable`.
16
- *
17
- * Signed HTTP is one POST of a frame to `<origin>/storage/frames`, with
18
- * `authorization: Midsummer-Key key=<id>, time=<ms>, signature=<hex>`: the HMAC-SHA256, under the key's
19
- * secret, of the time and the frame's SHA-256 (`<time>\n<hex>`). The secret never travels, and a server
20
- * (`serveSigned`) refuses a signature more than five minutes from its own clock.
21
- */
22
- const SOCKET_PATH = "/storage/socket";
23
- const FRAMES_PATH = "/storage/frames";
24
- const SKEW_MS = 3e5;
25
- /**
26
- * Storage's engine at `origin` (the API's, `https://api.<site>`) for the Storage Key `key`: one socket,
27
- * batched HTTP where it cannot open. `close` ends the connection; the next call opens another.
28
- */
29
- function client(origin, options) {
30
- const base = origin.replace(/\/+$/, "");
31
- const http = signedHttp(`${base}${FRAMES_PATH}`, options);
32
- const transport = socket(`${base.replace(/^http/, "ws")}${SOCKET_PATH}`, {
33
- ...options,
34
- connections: 1,
35
- fallback: http
36
- });
37
- return {
38
- ...remote(transport, { batch: true }),
39
- close: () => transport.close()
40
- };
41
- }
42
- async function sha256(bytes) {
43
- return [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((b) => b.toString(16).padStart(2, "0")).join("");
44
- }
45
- /**
46
- * A transport over HTTP signed with a Storage Key: each frame is one POST to `url`, replied to by
47
- * `serveSigned`, and sent once more when the request or its answer's body fails and the frame is
48
- * `repeatable`. A refused key is `forbidden`; a server that cannot be reached, or replies with anything but
49
- * a frame, is `unavailable`.
50
- */
51
- function signedHttp(url, options) {
52
- const send = options.fetch ?? ((to, init) => fetch(to, init));
53
- const clock = options.clock ?? Date.now;
54
- return { async send(frame) {
55
- const time = clock();
56
- const signature = await sign(options.secret, `${time}\n${await sha256(frame)}`);
57
- for (let sends = 1;; sends += 1) {
58
- const lost = () => {
59
- if (sends === 2 || !repeatable(frame)) throw new StorageError("unavailable", "Storage could not be reached");
60
- };
61
- let response;
62
- try {
63
- response = await send(url, {
64
- method: "POST",
65
- headers: {
66
- authorization: `Midsummer-Key key=${options.key}, time=${time}, signature=${signature}`,
67
- "content-type": "application/octet-stream"
68
- },
69
- body: frame
70
- });
71
- } catch {
72
- lost();
73
- continue;
74
- }
75
- if (response.status === 401 || response.status === 403) throw new StorageError("forbidden", "Storage refused the key");
76
- if (response.status !== 200) throw new StorageError("unavailable", `Storage answered ${response.status}`);
77
- try {
78
- return new Uint8Array(await response.arrayBuffer());
79
- } catch {
80
- lost();
81
- }
82
- }
83
- } };
84
- }
85
- /**
86
- * Serves `signedHttp` transports: a POST of one frame, signed by a key `credentials` knows, gets one
87
- * answer frame from `engine` as that key reaches it (`keyed`). Anything else is 405 or 401.
88
- */
89
- function serveSigned(options) {
90
- const clock = options.clock ?? Date.now;
91
- return async (request) => {
92
- if (request.method !== "POST") return new Response(null, { status: 405 });
93
- const said = /^Midsummer-Key key=([^,\s]+), time=(\d+), signature=([0-9a-f]{64})$/.exec(request.headers.get("authorization") ?? "");
94
- const frame = new Uint8Array(await request.arrayBuffer());
95
- if (!said || Math.abs(clock() - Number(said[2])) > SKEW_MS) return new Response(null, { status: 401 });
96
- const credential = await options.credentials(said[1], bucketsOf(frame));
97
- if (!credential || !sameHex(await sign(credential.secret, `${said[2]}\n${await sha256(frame)}`), said[3])) return new Response(null, { status: 401 });
98
- const answer = await serve(keyed(options.engine, credential))(frame);
99
- return new Response(answer, {
100
- status: 200,
101
- headers: { "content-type": "application/octet-stream" }
102
- });
103
- };
104
- }
105
- //#endregion
1
+ import { a as SOCKET_PATH, c as signedHttp, i as FRAMES_PATH, o as client, s as serveSigned } from "./src-BKrQAqJN.mjs";
106
2
  export { FRAMES_PATH, SOCKET_PATH, client, serveSigned, signedHttp };
@@ -270,14 +270,15 @@ const SHARED = /* @__PURE__ */ new Map();
270
270
  * a missed key: it returns the keys that left the cache (possibly the one leaving the window). */
271
271
  /**
272
272
  * Where a request to `url` goes, and the headers that name it. A `*.localhost` name is loopback (RFC 6761)
273
- * whatever the system's resolver says, and a Debian container's says nothing: outside a browser, which
274
- * resolves it itself and never lets a page set Host, it goes to 127.0.0.1 with the name as its Host
275
- * (and, over TLS, as the name the certificate is checked for). Anything else goes as it is.
273
+ * whatever the system's resolver says, and a Debian container's says nothing: outside a browser or a
274
+ * Worker, which resolve it themselves (and whose WebSocket takes no headers), it goes to 127.0.0.1 with
275
+ * the name as its Host (and, over TLS, as the name the certificate is checked for). Anything else goes
276
+ * as it is.
276
277
  * const { url, init } = loopback("http://db-a.localhost:8792/ws"); fetch(url, init)
277
278
  */
278
279
  function loopback(url, g = globalThis) {
279
280
  const at = new URL(url);
280
- if (g.document !== void 0 || !at.hostname.endsWith(".localhost")) return {
281
+ if (g.document !== void 0 || g.WebSocketPair !== void 0 || !at.hostname.endsWith(".localhost")) return {
281
282
  url: String(url),
282
283
  init: {}
283
284
  };
@@ -408,8 +409,8 @@ var Connection = class Connection {
408
409
  ...options,
409
410
  shape
410
411
  };
411
- if (o.store === void 0 && typeof indexedDB !== "undefined" && typeof document !== "undefined") o.store = (await import("./store-lIZ5GxVv.mjs")).idbStore(new URL(url).host);
412
- if (o.tabs !== false && typeof document !== "undefined") return (await import("./tabs-zCh8kceo.mjs")).ConnectionTabs.connect(url, o);
412
+ if (o.store === void 0 && typeof indexedDB !== "undefined" && typeof document !== "undefined") o.store = (await import("./store-CsBhnabU.mjs")).idbStore(new URL(url).host);
413
+ if (o.tabs !== false && typeof document !== "undefined") return (await import("./tabs-gHJHkhm2.mjs")).ConnectionTabs.connect(url, o);
413
414
  return Connection.open(url, o);
414
415
  }
415
416
  /** A Connection over one socket, of the shape given (default "browser"), no detection (tabs.mjs opens its own so). */
package/contract.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { p as Storage } from "./index-sgdyoA2P.mjs";
1
+ import { p as Storage } from "./index-Ci6mGXqz.mjs";
2
2
  //#region src/contract.d.ts
3
3
  interface ContractCase {
4
4
  /** A line of the specification. */
package/contract.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { h as StorageError } from "./names-DfCBKupJ.mjs";
2
- import "./index.mjs";
2
+ import "./src-BKrQAqJN.mjs";
3
3
  //#region src/contract.ts
4
4
  /**
5
5
  * Storage's contract: what every engine promises, as cases any test runner can run. The Stand-in
@@ -7,6 +7,7 @@ interface Reference<Kind extends "query" | "mutation" | "action", Args = any, Re
7
7
  readonly __args?: Args;
8
8
  readonly __returns?: Returns;
9
9
  }
10
+ /** The arguments a function's reference takes, and what it returns. */
10
11
  type ArgsOf<F> = F extends Reference<any, infer A, any> ? A : never;
11
12
  type ReturnsOf<F> = F extends Reference<any, any, infer R> ? R : never;
12
13
  /** A function's arguments, which may be left out when it takes none or only optional ones. */
@@ -61,6 +62,24 @@ interface BoundDatabases {
61
62
  readonly expiresAt: number;
62
63
  }>;
63
64
  }
65
+ /**
66
+ * A token for one signed-in user of your app, for your server to hand to that user's browser, which connects with
67
+ * it (`@midsummer-ai/sdk/react`'s `DatabaseProvider`, or `connect({ url, token, refresh })`). Your server keeps the
68
+ * database key and identifies the user by your own id for them; your functions see that id as `ctx.auth.subject`. The
69
+ * token runs public functions only, and only queries for a `read` key. It lasts ten minutes: the browser asks your
70
+ * server again before then.
71
+ *
72
+ * app.get("/db-token", async (c) => c.json(await userToken({ key: process.env.DATABASE_KEY!, as: session.userId })))
73
+ */
74
+ declare function userToken(options: {
75
+ readonly key: string;
76
+ readonly as: string;
77
+ readonly api?: string;
78
+ }): Promise<{
79
+ readonly token: string;
80
+ readonly url: string;
81
+ readonly expiresAt: number;
82
+ }>;
64
83
  declare function connect(options: ConnectOptions): Promise<Database>;
65
84
  /**
66
85
  * What `setAuth` is given: the signed-in user's token from their sign-in provider, or null when no one is
@@ -133,4 +152,4 @@ declare function clerk(getToken: (options: {
133
152
  */
134
153
  declare function oidc(getToken: (forceRefresh: boolean) => Promise<string | null | undefined> | string | null | undefined): FetchToken;
135
154
  //#endregion
136
- export { AuthState, BoundDatabases, ConnectOptions, Database, DatabaseClient, DatabaseError, type DatabaseErrorCode, FetchToken, Reference, auth0, clerk, connect, oidc };
155
+ export { ArgsOf, AuthState, BoundDatabases, ConnectOptions, Database, DatabaseClient, DatabaseError, type DatabaseErrorCode, FetchToken, Reference, ReturnsOf, auth0, clerk, connect, oidc, userToken };
@@ -1,6 +1,6 @@
1
1
  import { n as bytesTagged, r as bytesUntagged } from "../bytes-C2pcyl9u.mjs";
2
2
  import { DatabaseError } from "./errors.mjs";
3
- import { i as payloadOf, r as fetchAt, t as Connection } from "../connection-Cu2GSOaR.mjs";
3
+ import { i as payloadOf, r as fetchAt, t as Connection } from "../connection-C_JSWUrt.mjs";
4
4
  import { t as callKey } from "../key-BrRdFY-n.mjs";
5
5
  //#region src/database/client.ts
6
6
  /**
@@ -44,7 +44,7 @@ import { t as callKey } from "../key-BrRdFY-n.mjs";
44
44
  * db.clearAuth() // signed out
45
45
  */
46
46
  const API = "https://api.midsummer.new";
47
- /** A token and the Database's address, from the platform, for a key or for a run's binding. */
47
+ /** A token and the Database's address, from the platform, for a key (as one of the app's users with `as`) or for a run's binding. */
48
48
  async function exchange(api, proof) {
49
49
  const response = await fetch(`${api}/v1/db/tokens`, {
50
50
  method: "POST",
@@ -52,10 +52,31 @@ async function exchange(api, proof) {
52
52
  body: JSON.stringify(typeof proof === "string" ? { key: proof } : proof)
53
53
  });
54
54
  const answer = await response.json().catch(() => ({}));
55
- if (!response.ok || !answer.token || !answer.url) throw new DatabaseError("denied", answer.error ?? `The Database Key was refused (${response.status}).`);
55
+ if (!response.ok || !answer.token || !answer.url) throw new DatabaseError("denied", answer.error ?? `The database key was refused (${response.status}).`);
56
56
  return {
57
57
  token: answer.token,
58
- url: answer.url
58
+ url: answer.url,
59
+ ...typeof answer.expiresAt === "number" ? { expiresAt: answer.expiresAt } : {}
60
+ };
61
+ }
62
+ /**
63
+ * A token for one signed-in user of your app, for your server to hand to that user's browser, which connects with
64
+ * it (`@midsummer-ai/sdk/react`'s `DatabaseProvider`, or `connect({ url, token, refresh })`). Your server keeps the
65
+ * database key and identifies the user by your own id for them; your functions see that id as `ctx.auth.subject`. The
66
+ * token runs public functions only, and only queries for a `read` key. It lasts ten minutes: the browser asks your
67
+ * server again before then.
68
+ *
69
+ * app.get("/db-token", async (c) => c.json(await userToken({ key: process.env.DATABASE_KEY!, as: session.userId })))
70
+ */
71
+ async function userToken(options) {
72
+ const given = await exchange(options.api ?? API, {
73
+ key: options.key,
74
+ as: options.as
75
+ });
76
+ return {
77
+ token: given.token,
78
+ url: given.url,
79
+ expiresAt: given.expiresAt ?? expiryOf(given.token)
59
80
  };
60
81
  }
61
82
  /**
@@ -164,7 +185,7 @@ async function isolation(url, key, token) {
164
185
  return {
165
186
  ...own,
166
187
  name,
167
- store: (await import("../store-lIZ5GxVv.mjs")).idbStore(name)
188
+ store: (await import("../store-CsBhnabU.mjs")).idbStore(name)
168
189
  };
169
190
  }
170
191
  const inPage = () => typeof globalThis.document !== "undefined";
@@ -179,7 +200,9 @@ async function connect(options) {
179
200
  } else if ("binding" in options) {
180
201
  const env = globalThis.process?.env ?? {};
181
202
  const here = globalThis[Symbol.for("midsummer.context")];
182
- const bound = here?.()?.database;
203
+ const request = here?.();
204
+ const bound = request?.database;
205
+ if (request && !bound && !env.MIDSUMMER_DATABASE_URL) throw new DatabaseError("denied", `This address serves no environment, so no database is bound to it as ${options.binding}. A deployment's own address reaches no database: open the site at its environment's address, such as production's.`);
183
206
  if (bound) {
184
207
  const first = await bound.token(options.binding);
185
208
  url = first.url;
@@ -190,7 +213,7 @@ async function connect(options) {
190
213
  token = env.MIDSUMMER_DATABASE_TOKEN;
191
214
  } else {
192
215
  const workload = env.MIDSUMMER_IDENTITY_REQUEST_TOKEN, tokenUrl = env.MIDSUMMER_IDENTITY_TOKEN_URL;
193
- if (!workload || !tokenUrl) throw new DatabaseError("denied", "This code runs outside Midsummer, so no Environment binds a Database for it. Connect with a Database Key: connect({ key }).");
216
+ if (!workload || !tokenUrl) throw new DatabaseError("denied", "This code runs outside Midsummer, so no environment binds a database for it. Connect with a database key, connect({ key }), or run it under midsummer dev.");
194
217
  const api = options.api ?? new URL(tokenUrl).origin;
195
218
  const proof = {
196
219
  binding: options.binding,
@@ -641,4 +664,4 @@ function oidc(getToken) {
641
664
  return async ({ forceRefreshToken }) => await getToken(forceRefreshToken) || null;
642
665
  }
643
666
  //#endregion
644
- export { DatabaseClient, DatabaseError, auth0, clerk, connect, oidc };
667
+ export { DatabaseClient, DatabaseError, auth0, clerk, connect, oidc, userToken };