@n-dream/builders-sdk 0.4.0 → 1.0.0-next.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/README.md +10 -41
- package/dist/app-info.d.ts +11 -0
- package/dist/app-info.js +44 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.js +12 -0
- package/dist/index.d.ts +2 -118
- package/dist/index.js +4 -449
- package/package.json +13 -31
- package/dist/chunks/chunk-RUOQMEEZ.js +0 -136
- package/dist/chunks/user-Dr8gM34m.d.ts +0 -20
- package/dist/next.d.ts +0 -6
- package/dist/next.js +0 -12
package/README.md
CHANGED
|
@@ -1,49 +1,18 @@
|
|
|
1
1
|
# @n-dream/builders-sdk
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
the signed-in user, AI, notifications and secrets.
|
|
5
|
-
|
|
6
|
-
This package is for apps that the platform made. It does not work on other
|
|
7
|
-
hosting. The platform sets the environment variables that it needs.
|
|
8
|
-
|
|
9
|
-
Since 0.4.0 the package has no database and no file storage. Apps use their
|
|
10
|
-
Firestore database and their bucket with `firebase-admin`, on the server.
|
|
11
|
-
|
|
12
|
-
## Install
|
|
13
|
-
|
|
14
|
-
Apps import the package as `@builders/sdk`. Use an npm alias in
|
|
15
|
-
`package.json`:
|
|
16
|
-
|
|
17
|
-
```json
|
|
18
|
-
"dependencies": {
|
|
19
|
-
"@builders/sdk": "npm:@n-dream/builders-sdk@^0.4.0"
|
|
20
|
-
}
|
|
21
|
-
```
|
|
22
|
-
|
|
23
|
-
Node.js 22 or later is necessary. `@builders/sdk/next` needs Next.js 15 or
|
|
24
|
-
later.
|
|
25
|
-
|
|
26
|
-
## Use
|
|
3
|
+
The SDK for apps on Builders (design 4.5). Apps import it from npm.
|
|
27
4
|
|
|
28
5
|
```ts
|
|
29
|
-
import {
|
|
30
|
-
import { ai, notify, secrets } from "@builders/sdk";
|
|
31
|
-
import { z } from "zod";
|
|
6
|
+
import { appInfo } from "@n-dream/builders-sdk";
|
|
32
7
|
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
await ai.ask("Summarise: ...", { model: "fast" }); // AI add-on
|
|
36
|
-
await ai.json("Sort: ...", { schema: z.object({ tag: z.string() }) }); // a checked object
|
|
37
|
-
await ai.image("A robot mascot"); // also ai.chat, ai.stream, ai.speak, ai.transcribe
|
|
38
|
-
await notify.slack("Done"); // notify add-on
|
|
39
|
-
await secrets.get("HUBSPOT_API_KEY"); // set in the portal
|
|
8
|
+
const info = await appInfo(); // { appId, slug, environment, version }
|
|
40
9
|
```
|
|
41
10
|
|
|
42
|
-
-
|
|
43
|
-
|
|
44
|
-
-
|
|
45
|
-
`
|
|
46
|
-
|
|
47
|
-
## License
|
|
11
|
+
- `appInfo()` reads `/_api/app.json` on the app's own host. `environment`
|
|
12
|
+
is `live`, `preview` or `version`. `version` is null on the preview.
|
|
13
|
+
- There is no local mode (D37). Without the platform, `appInfo()` throws a
|
|
14
|
+
`BuildersError`. Use it only for things that the page can do without.
|
|
15
|
+
- Later platform services add one named export each (design section 12).
|
|
48
16
|
|
|
49
|
-
|
|
17
|
+
Release: the owner publishes with the `next` dist-tag until the
|
|
18
|
+
switch-over (Q29). `npm pack` builds `dist/` first.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const APP_INFO_PATH = "/_api/app.json";
|
|
2
|
+
export type Environment = "live" | "preview" | "version";
|
|
3
|
+
export interface AppInfo {
|
|
4
|
+
appId: string;
|
|
5
|
+
slug: string;
|
|
6
|
+
environment: Environment;
|
|
7
|
+
version: number | null;
|
|
8
|
+
}
|
|
9
|
+
export declare function appInfo(opts?: {
|
|
10
|
+
fetch?: typeof fetch;
|
|
11
|
+
}): Promise<AppInfo>;
|
package/dist/app-info.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { BuildersError } from "./errors.js";
|
|
2
|
+
// The path of the app information on every app host (design 3.2, D42).
|
|
3
|
+
export const APP_INFO_PATH = "/_api/app.json";
|
|
4
|
+
const ENVIRONMENTS = ["live", "preview", "version"];
|
|
5
|
+
function parse(v) {
|
|
6
|
+
if (typeof v !== "object" || v === null)
|
|
7
|
+
return null;
|
|
8
|
+
const o = v;
|
|
9
|
+
if (typeof o.appId !== "string" || !o.appId)
|
|
10
|
+
return null;
|
|
11
|
+
if (typeof o.slug !== "string" || !o.slug)
|
|
12
|
+
return null;
|
|
13
|
+
if (typeof o.environment !== "string" || !ENVIRONMENTS.includes(o.environment))
|
|
14
|
+
return null;
|
|
15
|
+
const version = o.version ?? null;
|
|
16
|
+
if (version !== null && (typeof version !== "number" || !Number.isInteger(version) || version < 1))
|
|
17
|
+
return null;
|
|
18
|
+
return { appId: o.appId, slug: o.slug, environment: o.environment, version };
|
|
19
|
+
}
|
|
20
|
+
// Reads the app information from the platform. There is no local mode
|
|
21
|
+
// (D37): on a local server without the platform, this throws.
|
|
22
|
+
export async function appInfo(opts = {}) {
|
|
23
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
24
|
+
let res;
|
|
25
|
+
try {
|
|
26
|
+
res = await f(APP_INFO_PATH, { credentials: "same-origin", cache: "no-store", headers: { accept: "application/json" } });
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
throw new BuildersError("Could not reach Builders to read the app information.", 0);
|
|
30
|
+
}
|
|
31
|
+
if (!res.ok)
|
|
32
|
+
throw new BuildersError(`Builders did not give the app information (status ${res.status}).`, res.status);
|
|
33
|
+
let body;
|
|
34
|
+
try {
|
|
35
|
+
body = await res.json();
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
throw new BuildersError("The app information from Builders is not valid.", res.status);
|
|
39
|
+
}
|
|
40
|
+
const info = parse(body);
|
|
41
|
+
if (!info)
|
|
42
|
+
throw new BuildersError("The app information from Builders is not valid.", res.status);
|
|
43
|
+
return info;
|
|
44
|
+
}
|
package/dist/errors.d.ts
ADDED
package/dist/errors.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// The SDK error pattern (from Builders v1 packages/sdk/src/errors.ts).
|
|
2
|
+
// Each message is plain, so that Claude can give it to the person as it is.
|
|
3
|
+
export class BuildersError extends Error {
|
|
4
|
+
status;
|
|
5
|
+
constructor(message,
|
|
6
|
+
// The HTTP status of the platform's answer, or 0 when no answer came.
|
|
7
|
+
status = 500) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.status = status;
|
|
10
|
+
this.name = "BuildersError";
|
|
11
|
+
}
|
|
12
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,118 +1,2 @@
|
|
|
1
|
-
export {
|
|
2
|
-
|
|
3
|
-
import 'jose';
|
|
4
|
-
|
|
5
|
-
declare const ADDONS: readonly ["ai", "storage", "cron", "notify", "internet"];
|
|
6
|
-
type AddOn = (typeof ADDONS)[number];
|
|
7
|
-
|
|
8
|
-
declare const IDENTITY_HEADER = "x-builders-identity";
|
|
9
|
-
declare const SIGN_OUT_PATH = "/_builders/sign-out";
|
|
10
|
-
|
|
11
|
-
declare const CLAUDE_MODELS: {
|
|
12
|
-
readonly fast: "claude-haiku-5-5";
|
|
13
|
-
readonly balanced: "claude-sonnet-5-5";
|
|
14
|
-
readonly best: "claude-opus-5-5";
|
|
15
|
-
};
|
|
16
|
-
type AiModelChoice = keyof typeof CLAUDE_MODELS;
|
|
17
|
-
|
|
18
|
-
declare const ATTACHMENT_TYPES: readonly ["image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf"];
|
|
19
|
-
type AttachmentType = (typeof ATTACHMENT_TYPES)[number];
|
|
20
|
-
|
|
21
|
-
type AiModel = AiModelChoice;
|
|
22
|
-
type Attachment = {
|
|
23
|
-
data: Uint8Array | string;
|
|
24
|
-
mediaType: AttachmentType;
|
|
25
|
-
};
|
|
26
|
-
interface AskOptions {
|
|
27
|
-
system?: string;
|
|
28
|
-
model?: AiModel;
|
|
29
|
-
maxTokens?: number;
|
|
30
|
-
temperature?: number;
|
|
31
|
-
attachments?: Attachment[];
|
|
32
|
-
signal?: AbortSignal;
|
|
33
|
-
}
|
|
34
|
-
interface JsonOptions<T> extends AskOptions {
|
|
35
|
-
schema: z.ZodType<T>;
|
|
36
|
-
description?: string;
|
|
37
|
-
}
|
|
38
|
-
type Message = {
|
|
39
|
-
role: "user" | "assistant";
|
|
40
|
-
content: string;
|
|
41
|
-
attachments?: Attachment[];
|
|
42
|
-
};
|
|
43
|
-
interface ChatResult {
|
|
44
|
-
text: string;
|
|
45
|
-
stopReason: string | null;
|
|
46
|
-
usage: {
|
|
47
|
-
inputTokens: number;
|
|
48
|
-
outputTokens: number;
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
interface ImageOptions {
|
|
52
|
-
aspectRatio?: "1:1" | "3:2" | "2:3" | "3:4" | "4:3" | "4:5" | "5:4" | "9:16" | "16:9" | "21:9";
|
|
53
|
-
size?: "512" | "1K" | "2K";
|
|
54
|
-
images?: Attachment[];
|
|
55
|
-
signal?: AbortSignal;
|
|
56
|
-
}
|
|
57
|
-
interface GeneratedImage {
|
|
58
|
-
mediaType: string;
|
|
59
|
-
data: Buffer;
|
|
60
|
-
text: string;
|
|
61
|
-
}
|
|
62
|
-
interface SpeakOptions {
|
|
63
|
-
voice?: "Kore" | "Puck" | "Charon" | "Fenrir" | "Aoede" | "Leda" | "Orus" | "Zephyr";
|
|
64
|
-
style?: string;
|
|
65
|
-
signal?: AbortSignal;
|
|
66
|
-
}
|
|
67
|
-
interface TranscribeOptions {
|
|
68
|
-
mediaType: "audio/wav" | "audio/mpeg" | "audio/mp3" | "audio/flac" | "audio/ogg" | "audio/webm" | "audio/mp4" | "audio/m4a";
|
|
69
|
-
languages?: string[];
|
|
70
|
-
signal?: AbortSignal;
|
|
71
|
-
}
|
|
72
|
-
declare const ai: {
|
|
73
|
-
ask(prompt: string, opts?: AskOptions): Promise<string>;
|
|
74
|
-
chat(messages: Message[], opts?: AskOptions): Promise<ChatResult>;
|
|
75
|
-
json<T>(prompt: string, opts: JsonOptions<T>): Promise<T>;
|
|
76
|
-
stream(prompt: string | Message[], opts?: AskOptions): AsyncGenerator<string, ChatResult>;
|
|
77
|
-
image(prompt: string, opts?: ImageOptions): Promise<GeneratedImage>;
|
|
78
|
-
speak(text: string, opts?: SpeakOptions): Promise<{
|
|
79
|
-
mediaType: "audio/wav";
|
|
80
|
-
data: Buffer;
|
|
81
|
-
}>;
|
|
82
|
-
transcribe(audio: Uint8Array, opts: TranscribeOptions): Promise<{
|
|
83
|
-
text: string;
|
|
84
|
-
seconds: number;
|
|
85
|
-
}>;
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
declare const notify: {
|
|
89
|
-
email(to: string | string[], subject: string, text: string): Promise<void>;
|
|
90
|
-
slack(text: string): Promise<void>;
|
|
91
|
-
};
|
|
92
|
-
|
|
93
|
-
declare const secrets: {
|
|
94
|
-
get(name: string): Promise<string>;
|
|
95
|
-
clearCache(): void;
|
|
96
|
-
};
|
|
97
|
-
|
|
98
|
-
declare class BuildersError extends Error {
|
|
99
|
-
readonly status: number;
|
|
100
|
-
constructor(message: string, status?: number);
|
|
101
|
-
}
|
|
102
|
-
declare class NotSignedInError extends BuildersError {
|
|
103
|
-
constructor(message: string);
|
|
104
|
-
}
|
|
105
|
-
declare class NotFoundError extends BuildersError {
|
|
106
|
-
constructor(message: string);
|
|
107
|
-
}
|
|
108
|
-
declare class AddOnNotEnabledError extends BuildersError {
|
|
109
|
-
readonly addOn: AddOn;
|
|
110
|
-
constructor(addOn: AddOn);
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
declare class NotOnBuildersError extends BuildersError {
|
|
114
|
-
constructor(what: string);
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export { AddOnNotEnabledError, BuildersError, IDENTITY_HEADER, NotFoundError, NotOnBuildersError, NotSignedInError, SIGN_OUT_PATH, ai, notify, secrets };
|
|
118
|
-
export type { AiModel, AskOptions, Attachment, ChatResult, GeneratedImage, ImageOptions, JsonOptions, Message, SpeakOptions, TranscribeOptions };
|
|
1
|
+
export { appInfo, APP_INFO_PATH, type AppInfo, type Environment } from "./app-info.js";
|
|
2
|
+
export { BuildersError } from "./errors.js";
|
package/dist/index.js
CHANGED
|
@@ -1,449 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
NotFoundError,
|
|
6
|
-
NotSignedInError,
|
|
7
|
-
SIGN_OUT_PATH,
|
|
8
|
-
getUser,
|
|
9
|
-
nameFromEmail
|
|
10
|
-
} from "./chunks/chunk-RUOQMEEZ.js";
|
|
11
|
-
|
|
12
|
-
// ../core/src/ai.ts
|
|
13
|
-
var CLAUDE_MODELS = {
|
|
14
|
-
fast: "claude-haiku-5-5",
|
|
15
|
-
// simple, fast and cheap
|
|
16
|
-
balanced: "claude-sonnet-5-5",
|
|
17
|
-
// the default
|
|
18
|
-
best: "claude-opus-5-5"
|
|
19
|
-
// hard tasks only; it costs the most
|
|
20
|
-
};
|
|
21
|
-
var AI_MODEL_CHOICES = Object.keys(CLAUDE_MODELS);
|
|
22
|
-
var PLATFORM_MODEL = CLAUDE_MODELS.balanced;
|
|
23
|
-
|
|
24
|
-
// ../core/src/app-ai.ts
|
|
25
|
-
import { z } from "zod";
|
|
26
|
-
var APP_HEADER = "x-builders-app";
|
|
27
|
-
var APP_ENV = {
|
|
28
|
-
tenant: "BUILDERS_TENANT",
|
|
29
|
-
app: "BUILDERS_APP",
|
|
30
|
-
// The app's own GCP project (Secret Manager of `secrets`).
|
|
31
|
-
project: "BUILDERS_GCP_PROJECT",
|
|
32
|
-
aiGateway: "AI_GATEWAY_URL",
|
|
33
|
-
// ai add-on and notify add-on
|
|
34
|
-
bucket: "STORAGE_BUCKET",
|
|
35
|
-
// storage add-on
|
|
36
|
-
// "preview" (a v-<n> revision, no secrets) or "live" (core RevisionKind).
|
|
37
|
-
revision: "BUILDERS_REVISION"
|
|
38
|
-
};
|
|
39
|
-
var APP_AI_LIMITS = {
|
|
40
|
-
// The request body (attachments are base64 in it).
|
|
41
|
-
maxBodyBytes: 20 * 1024 * 1024,
|
|
42
|
-
maxMessages: 200,
|
|
43
|
-
maxTextChars: 4e5,
|
|
44
|
-
maxAttachments: 20,
|
|
45
|
-
maxOutputTokens: 16e3,
|
|
46
|
-
// JSON Schema of ai.json, as JSON text.
|
|
47
|
-
maxSchemaChars: 64e3,
|
|
48
|
-
maxImageInputs: 6,
|
|
49
|
-
maxSpeechChars: 5e3,
|
|
50
|
-
// Speech-to-Text "recognize" takes audio up to one minute.
|
|
51
|
-
maxAudioBytes: 10 * 1024 * 1024,
|
|
52
|
-
maxSlackChars: 3e3,
|
|
53
|
-
maxEmailRecipients: 20,
|
|
54
|
-
maxEmailChars: 2e4
|
|
55
|
-
};
|
|
56
|
-
var ATTACHMENT_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf"];
|
|
57
|
-
var Base64 = z.string().regex(/^[A-Za-z0-9+/]*={0,2}$/, "Not base64.");
|
|
58
|
-
var ContentPartSchema = z.discriminatedUnion("type", [
|
|
59
|
-
z.object({ type: z.literal("text"), text: z.string().min(1) }),
|
|
60
|
-
z.object({ type: z.literal("file"), mediaType: z.enum(ATTACHMENT_TYPES), data: Base64.min(1) })
|
|
61
|
-
]);
|
|
62
|
-
var ChatMessageSchema = z.object({
|
|
63
|
-
role: z.enum(["user", "assistant"]),
|
|
64
|
-
content: z.union([z.string().min(1), z.array(ContentPartSchema).min(1).max(APP_AI_LIMITS.maxAttachments + 10)])
|
|
65
|
-
});
|
|
66
|
-
var ModelChoice = z.enum(AI_MODEL_CHOICES);
|
|
67
|
-
var MessagesRequestSchema = z.object({
|
|
68
|
-
model: ModelChoice.default("balanced"),
|
|
69
|
-
system: z.string().max(APP_AI_LIMITS.maxTextChars).optional(),
|
|
70
|
-
messages: z.array(ChatMessageSchema).min(1).max(APP_AI_LIMITS.maxMessages),
|
|
71
|
-
maxTokens: z.number().int().min(1).max(APP_AI_LIMITS.maxOutputTokens).default(1024),
|
|
72
|
-
temperature: z.number().min(0).max(1).optional(),
|
|
73
|
-
// Structured output: Claude must answer with JSON for this JSON Schema
|
|
74
|
-
// (an object schema). The SDK checks the answer with the app's zod schema.
|
|
75
|
-
json: z.object({ schema: z.record(z.string(), z.unknown()), description: z.string().max(1e3).optional() }).optional(),
|
|
76
|
-
// Server-sent events: "text" deltas, then "done" (or "error").
|
|
77
|
-
stream: z.boolean().default(false)
|
|
78
|
-
}).strict().refine((r) => r.messages[0].role === "user", "The first message must be from the user.").refine((r) => !(r.json && r.stream), "A JSON answer cannot stream.");
|
|
79
|
-
var IMAGE_ASPECT_RATIOS = ["1:1", "3:2", "2:3", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"];
|
|
80
|
-
var IMAGE_SIZES = ["512", "1K", "2K"];
|
|
81
|
-
var ImageRequestSchema = z.object({
|
|
82
|
-
prompt: z.string().min(1).max(2e4),
|
|
83
|
-
aspectRatio: z.enum(IMAGE_ASPECT_RATIOS).default("1:1"),
|
|
84
|
-
size: z.enum(IMAGE_SIZES).default("1K"),
|
|
85
|
-
// Images to edit or to use as a reference.
|
|
86
|
-
images: z.array(z.object({ mediaType: z.enum(["image/png", "image/jpeg", "image/webp"]), data: Base64.min(1) })).max(APP_AI_LIMITS.maxImageInputs).default([])
|
|
87
|
-
}).strict();
|
|
88
|
-
var SPEECH_VOICES = [
|
|
89
|
-
"Kore",
|
|
90
|
-
"Puck",
|
|
91
|
-
"Charon",
|
|
92
|
-
"Fenrir",
|
|
93
|
-
"Aoede",
|
|
94
|
-
"Leda",
|
|
95
|
-
"Orus",
|
|
96
|
-
"Zephyr"
|
|
97
|
-
];
|
|
98
|
-
var SpeechRequestSchema = z.object({
|
|
99
|
-
text: z.string().min(1).max(APP_AI_LIMITS.maxSpeechChars),
|
|
100
|
-
voice: z.enum(SPEECH_VOICES).default("Kore"),
|
|
101
|
-
// How to speak, for example "Say cheerfully" (Gemini TTS follows it).
|
|
102
|
-
style: z.string().max(500).optional()
|
|
103
|
-
}).strict();
|
|
104
|
-
var AUDIO_TYPES = ["audio/wav", "audio/x-wav", "audio/mpeg", "audio/mp3", "audio/flac", "audio/ogg", "audio/webm", "audio/mp4", "audio/m4a"];
|
|
105
|
-
var TranscribeRequestSchema = z.object({
|
|
106
|
-
mediaType: z.enum(AUDIO_TYPES),
|
|
107
|
-
data: Base64.min(1),
|
|
108
|
-
// BCP-47 codes, for example ["de-CH", "en-US"]. Default: detect.
|
|
109
|
-
languages: z.array(z.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/)).min(1).max(3).optional()
|
|
110
|
-
}).strict();
|
|
111
|
-
var SlackRequestSchema = z.object({ text: z.string().min(1).max(APP_AI_LIMITS.maxSlackChars) }).strict();
|
|
112
|
-
var EmailRequestSchema = z.object({
|
|
113
|
-
to: z.array(z.string().email().max(254)).min(1).max(APP_AI_LIMITS.maxEmailRecipients),
|
|
114
|
-
subject: z.string().min(1).max(200).refine((s) => !/[\r\n]/.test(s), "One line."),
|
|
115
|
-
text: z.string().min(1).max(APP_AI_LIMITS.maxEmailChars)
|
|
116
|
-
}).strict();
|
|
117
|
-
var SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
118
|
-
var PLATFORM_SECRET_PREFIX = "BUILDERS_";
|
|
119
|
-
var MAX_SECRET_BYTES = 16 * 1024;
|
|
120
|
-
function secretNameError(name) {
|
|
121
|
-
if (!SECRET_NAME.test(name)) return "Use capital letters, digits and _, starting with a letter (for example HUBSPOT_API_KEY).";
|
|
122
|
-
if (name.startsWith(PLATFORM_SECRET_PREFIX)) return `Names that start with ${PLATFORM_SECRET_PREFIX} are for the platform.`;
|
|
123
|
-
return null;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// ../core/src/dev-data.ts
|
|
127
|
-
var DEV_ENV = {
|
|
128
|
-
url: "BUILDERS_DEV_URL",
|
|
129
|
-
tokenFile: "BUILDERS_TUNNEL_TOKEN_FILE"
|
|
130
|
-
};
|
|
131
|
-
|
|
132
|
-
// src/ai.ts
|
|
133
|
-
import { z as z2 } from "zod";
|
|
134
|
-
|
|
135
|
-
// src/platform.ts
|
|
136
|
-
import { readFileSync, statSync } from "node:fs";
|
|
137
|
-
var METADATA = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default";
|
|
138
|
-
var idTokens = /* @__PURE__ */ new Map();
|
|
139
|
-
var accessToken;
|
|
140
|
-
function jwtExp(token) {
|
|
141
|
-
try {
|
|
142
|
-
const payload = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8"));
|
|
143
|
-
return typeof payload.exp === "number" ? payload.exp * 1e3 : 0;
|
|
144
|
-
} catch {
|
|
145
|
-
return 0;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
async function metadata(path) {
|
|
149
|
-
let res;
|
|
150
|
-
try {
|
|
151
|
-
res = await fetch(`${METADATA}${path}`, { headers: { "Metadata-Flavor": "Google" }, signal: AbortSignal.timeout(5e3) });
|
|
152
|
-
} catch {
|
|
153
|
-
throw new NotOnBuildersError("This");
|
|
154
|
-
}
|
|
155
|
-
if (!res.ok) throw new BuildersError(`The app's identity is not available (${res.status}).`, 503);
|
|
156
|
-
return res;
|
|
157
|
-
}
|
|
158
|
-
async function idToken(audience) {
|
|
159
|
-
const hit = idTokens.get(audience);
|
|
160
|
-
if (hit && hit.exp - Date.now() > 5 * 6e4) return hit.token;
|
|
161
|
-
const res = await metadata(`/identity?audience=${encodeURIComponent(audience)}&format=full`);
|
|
162
|
-
const token = (await res.text()).trim();
|
|
163
|
-
idTokens.set(audience, { token, exp: jwtExp(token) });
|
|
164
|
-
return token;
|
|
165
|
-
}
|
|
166
|
-
async function googleAccessToken() {
|
|
167
|
-
if (accessToken && accessToken.exp - Date.now() > 6e4) return accessToken.token;
|
|
168
|
-
const res = await metadata("/token");
|
|
169
|
-
const j = await res.json();
|
|
170
|
-
if (!j.access_token) throw new BuildersError("The app's identity gave no access token.", 503);
|
|
171
|
-
accessToken = { token: j.access_token, exp: Date.now() + (j.expires_in ?? 300) * 1e3 };
|
|
172
|
-
return accessToken.token;
|
|
173
|
-
}
|
|
174
|
-
function devUrl(env = process.env) {
|
|
175
|
-
const url = env[DEV_ENV.url]?.trim();
|
|
176
|
-
if (!url || env.NODE_ENV === "production" || env.K_SERVICE) return null;
|
|
177
|
-
return url.replace(/\/+$/, "");
|
|
178
|
-
}
|
|
179
|
-
var devTokenCache;
|
|
180
|
-
var NO_DEV_TOKEN = "Start the dev preview again with the preview command from open_app (it gives a new token).";
|
|
181
|
-
function devToken(env = process.env) {
|
|
182
|
-
const path = env[DEV_ENV.tokenFile]?.trim();
|
|
183
|
-
if (!path) throw new BuildersError(`The dev preview has no Builders token (${DEV_ENV.tokenFile} is not set). ${NO_DEV_TOKEN}`, 401);
|
|
184
|
-
let st;
|
|
185
|
-
try {
|
|
186
|
-
st = statSync(path);
|
|
187
|
-
} catch {
|
|
188
|
-
throw new BuildersError(`The dev preview's Builders token file is missing. ${NO_DEV_TOKEN}`, 401);
|
|
189
|
-
}
|
|
190
|
-
const c = devTokenCache;
|
|
191
|
-
if (c && c.path === path && c.mtimeMs === st.mtimeMs && c.size === st.size) return c.token;
|
|
192
|
-
let token;
|
|
193
|
-
try {
|
|
194
|
-
token = (readFileSync(path, "utf8").split("\n")[0] ?? "").trim();
|
|
195
|
-
} catch {
|
|
196
|
-
throw new BuildersError(`The dev preview's Builders token file cannot be read. ${NO_DEV_TOKEN}`, 401);
|
|
197
|
-
}
|
|
198
|
-
if (!token) throw new BuildersError(`The dev preview's Builders token file is empty. ${NO_DEV_TOKEN}`, 401);
|
|
199
|
-
devTokenCache = { path, mtimeMs: st.mtimeMs, size: st.size, token };
|
|
200
|
-
return token;
|
|
201
|
-
}
|
|
202
|
-
var NotOnBuildersError = class extends BuildersError {
|
|
203
|
-
constructor(what) {
|
|
204
|
-
super(
|
|
205
|
-
`${what} works only on Builders: in the dev preview, a saved version and the live app. It does not work in pnpm dev without the Builders preview, or in tests. Start the dev preview with the commands from open_app, or show a short note here.`,
|
|
206
|
-
503
|
|
207
|
-
);
|
|
208
|
-
this.name = "NotOnBuildersError";
|
|
209
|
-
}
|
|
210
|
-
};
|
|
211
|
-
var WHAT = { ai: "AI", notify: "Sending notifications" };
|
|
212
|
-
function gateway(addOn) {
|
|
213
|
-
const dev = devUrl();
|
|
214
|
-
if (dev) return { url: dev, app: "", dev: true };
|
|
215
|
-
const tenant = process.env[APP_ENV.tenant];
|
|
216
|
-
const app = process.env[APP_ENV.app];
|
|
217
|
-
if (!tenant || !app) throw new NotOnBuildersError(WHAT[addOn] ?? "This");
|
|
218
|
-
const url = process.env[APP_ENV.aiGateway];
|
|
219
|
-
if (!url) throw new AddOnNotEnabledError(addOn);
|
|
220
|
-
return { url: url.replace(/\/+$/, ""), app: `${tenant}/${app}` };
|
|
221
|
-
}
|
|
222
|
-
function errorOf(status, body, fallback) {
|
|
223
|
-
const msg = body?.error?.message ?? fallback;
|
|
224
|
-
return new BuildersError(msg, status === 429 && body?.error?.code === "budget" ? 402 : status);
|
|
225
|
-
}
|
|
226
|
-
async function gatewayFetch(t, path, body, o = {}) {
|
|
227
|
-
const headers = t.dev ? { "content-type": "application/json", authorization: `Bearer ${devToken()}` } : { "content-type": "application/json", authorization: `Bearer ${await idToken(t.url)}`, [APP_HEADER]: t.app };
|
|
228
|
-
const url = t.dev ? `${t.url}${path.replace(/^\/v1(?=\/)/, "")}` : `${t.url}${path}`;
|
|
229
|
-
let res;
|
|
230
|
-
try {
|
|
231
|
-
res = await fetch(url, {
|
|
232
|
-
method: "POST",
|
|
233
|
-
headers,
|
|
234
|
-
body: JSON.stringify(body),
|
|
235
|
-
signal: o.signal ?? AbortSignal.timeout(o.timeoutMs ?? 12e4)
|
|
236
|
-
});
|
|
237
|
-
} catch (e) {
|
|
238
|
-
throw new BuildersError(`Could not reach the platform's ${t.dev ? "dev preview service" : "AI service"}: ${e.message}`, 502);
|
|
239
|
-
}
|
|
240
|
-
if (!res.ok) {
|
|
241
|
-
const text = await res.text();
|
|
242
|
-
let j;
|
|
243
|
-
try {
|
|
244
|
-
j = JSON.parse(text);
|
|
245
|
-
} catch {
|
|
246
|
-
}
|
|
247
|
-
throw errorOf(res.status, j, `The platform's ${t.dev ? "dev preview service" : "AI service"} answered ${res.status}.`);
|
|
248
|
-
}
|
|
249
|
-
return res;
|
|
250
|
-
}
|
|
251
|
-
async function gatewayJson(addOn, path, body, o = {}) {
|
|
252
|
-
const res = await gatewayFetch(gateway(addOn), path, body, o);
|
|
253
|
-
return await res.json();
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
// src/ai.ts
|
|
257
|
-
var MODELS = new Set(AI_MODEL_CHOICES);
|
|
258
|
-
function model(m) {
|
|
259
|
-
const v = m ?? "balanced";
|
|
260
|
-
if (!MODELS.has(v)) throw new BuildersError(`Unknown AI model "${v}". Use "fast", "balanced" or "best".`, 400);
|
|
261
|
-
return v;
|
|
262
|
-
}
|
|
263
|
-
async function base64(a) {
|
|
264
|
-
return typeof a.data === "string" ? a.data : Buffer.from(a.data).toString("base64");
|
|
265
|
-
}
|
|
266
|
-
async function content(text, attachments = []) {
|
|
267
|
-
if (!attachments.length) return text;
|
|
268
|
-
const files = await Promise.all(attachments.map(async (a) => ({ type: "file", mediaType: a.mediaType, data: await base64(a) })));
|
|
269
|
-
return [...files, { type: "text", text }];
|
|
270
|
-
}
|
|
271
|
-
async function request(messages, o, extra = {}) {
|
|
272
|
-
return {
|
|
273
|
-
model: model(o.model),
|
|
274
|
-
...o.system ? { system: o.system } : {},
|
|
275
|
-
maxTokens: o.maxTokens ?? 1024,
|
|
276
|
-
...o.temperature !== void 0 ? { temperature: o.temperature } : {},
|
|
277
|
-
messages: await Promise.all(messages.map(async (m) => ({ role: m.role, content: await content(m.content, m.attachments) }))),
|
|
278
|
-
...extra
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
function toJsonSchema(schema) {
|
|
282
|
-
if (!schema || typeof schema !== "object" || !("_zod" in schema)) {
|
|
283
|
-
throw new BuildersError("ai.json needs a zod 4 schema, e.g. z.object({ city: z.string() }).", 400);
|
|
284
|
-
}
|
|
285
|
-
let js;
|
|
286
|
-
try {
|
|
287
|
-
js = z2.toJSONSchema(schema, { io: "input", unrepresentable: "throw" });
|
|
288
|
-
} catch (e) {
|
|
289
|
-
throw new BuildersError(
|
|
290
|
-
`ai.json cannot use this schema: ${e.message}. Use types that JSON can hold, for example z.iso.datetime() or z.coerce.date() instead of z.date().`,
|
|
291
|
-
400
|
|
292
|
-
);
|
|
293
|
-
}
|
|
294
|
-
delete js.$schema;
|
|
295
|
-
if (js.type !== "object") throw new BuildersError("ai.json needs an object schema (z.object({...})). Put a list in a field.", 400);
|
|
296
|
-
return js;
|
|
297
|
-
}
|
|
298
|
-
var ai = {
|
|
299
|
-
// One question, the answer as text.
|
|
300
|
-
async ask(prompt, opts = {}) {
|
|
301
|
-
return (await ai.chat([{ role: "user", content: prompt, ...opts.attachments ? { attachments: opts.attachments } : {} }], opts)).text;
|
|
302
|
-
},
|
|
303
|
-
// A conversation: the earlier messages, then the new question.
|
|
304
|
-
async chat(messages, opts = {}) {
|
|
305
|
-
const body = await request(messages, opts);
|
|
306
|
-
const r = await gatewayJson("ai", "/v1/messages", body, { signal: opts.signal, timeoutMs: 3e5 });
|
|
307
|
-
return { text: r.text, stopReason: r.stopReason, usage: r.usage };
|
|
308
|
-
},
|
|
309
|
-
// A typed object instead of text, checked with the schema. If the first
|
|
310
|
-
// answer does not match, Claude gets the problem and tries once more.
|
|
311
|
-
async json(prompt, opts) {
|
|
312
|
-
const schema = toJsonSchema(opts.schema);
|
|
313
|
-
const messages = [{ role: "user", content: prompt, ...opts.attachments ? { attachments: opts.attachments } : {} }];
|
|
314
|
-
let last = "";
|
|
315
|
-
for (let attempt = 0; attempt < 2; attempt++) {
|
|
316
|
-
const body = await request(messages, { ...opts, maxTokens: opts.maxTokens ?? 4096 }, { json: { schema, ...opts.description ? { description: opts.description } : {} } });
|
|
317
|
-
const r = await gatewayJson("ai", "/v1/messages", body, { signal: opts.signal, timeoutMs: 3e5 });
|
|
318
|
-
if (r.stopReason === "max_tokens") {
|
|
319
|
-
throw new BuildersError(`The AI answer was too long and was cut off. Raise maxTokens (now ${body.maxTokens}) or ask for less.`, 502);
|
|
320
|
-
}
|
|
321
|
-
const parsed = opts.schema.safeParse(r.json);
|
|
322
|
-
if (parsed.success) return parsed.data;
|
|
323
|
-
last = parsed.error.issues.slice(0, 5).map((i) => `${i.path.join(".") || "answer"}: ${i.message}`).join("; ");
|
|
324
|
-
messages.push({ role: "assistant", content: JSON.stringify(r.json ?? null).slice(0, 2e4) }, { role: "user", content: `That answer does not match the schema (${last}). Answer again with the tool, matching the schema exactly.` });
|
|
325
|
-
}
|
|
326
|
-
throw new BuildersError(`The AI answer did not match the schema: ${last}`, 502);
|
|
327
|
-
},
|
|
328
|
-
// The answer as it is written, piece by piece:
|
|
329
|
-
// for await (const piece of ai.stream("Write a poem")) send(piece);
|
|
330
|
-
async *stream(prompt, opts = {}) {
|
|
331
|
-
const messages = typeof prompt === "string" ? [{ role: "user", content: prompt, ...opts.attachments ? { attachments: opts.attachments } : {} }] : prompt;
|
|
332
|
-
const body = await request(messages, opts, { stream: true });
|
|
333
|
-
const res = await gatewayFetch(gateway("ai"), "/v1/messages", body, { signal: opts.signal, timeoutMs: 9e5 });
|
|
334
|
-
const reader = res.body.getReader();
|
|
335
|
-
const dec = new TextDecoder();
|
|
336
|
-
let buf = "";
|
|
337
|
-
let text = "";
|
|
338
|
-
let ended = false;
|
|
339
|
-
try {
|
|
340
|
-
for (; ; ) {
|
|
341
|
-
const { done, value } = await reader.read();
|
|
342
|
-
if (done) break;
|
|
343
|
-
buf += dec.decode(value, { stream: true });
|
|
344
|
-
let i;
|
|
345
|
-
while ((i = buf.indexOf("\n\n")) >= 0) {
|
|
346
|
-
const block = buf.slice(0, i);
|
|
347
|
-
buf = buf.slice(i + 2);
|
|
348
|
-
const line = block.split("\n").find((l) => l.startsWith("data:"));
|
|
349
|
-
if (!line) continue;
|
|
350
|
-
const ev = JSON.parse(line.slice(5));
|
|
351
|
-
if (ev.type === "text") {
|
|
352
|
-
text += ev.text;
|
|
353
|
-
yield ev.text;
|
|
354
|
-
} else if (ev.type === "done") {
|
|
355
|
-
ended = true;
|
|
356
|
-
return { text, stopReason: ev.stopReason, usage: ev.usage };
|
|
357
|
-
} else if (ev.type === "error") {
|
|
358
|
-
throw new BuildersError(ev.message, 502);
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
throw new BuildersError("The AI answer stopped early. Try again.", 502);
|
|
363
|
-
} finally {
|
|
364
|
-
if (!ended) await reader.cancel().catch(() => {
|
|
365
|
-
});
|
|
366
|
-
}
|
|
367
|
-
},
|
|
368
|
-
// A new image from a prompt, or a changed image (opts.images).
|
|
369
|
-
async image(prompt, opts = {}) {
|
|
370
|
-
const images = await Promise.all((opts.images ?? []).map(async (a) => ({ mediaType: a.mediaType, data: await base64(a) })));
|
|
371
|
-
const r = await gatewayJson("ai", "/v1/image", { prompt, ...opts.aspectRatio ? { aspectRatio: opts.aspectRatio } : {}, ...opts.size ? { size: opts.size } : {}, images }, { signal: opts.signal, timeoutMs: 3e5 });
|
|
372
|
-
const first = r.images[0];
|
|
373
|
-
if (!first) throw new BuildersError("The AI made no image. Change the prompt and try again.", 502);
|
|
374
|
-
return { mediaType: first.mediaType, data: Buffer.from(first.data, "base64"), text: r.text };
|
|
375
|
-
},
|
|
376
|
-
// Text to speech, as WAV audio.
|
|
377
|
-
async speak(text, opts = {}) {
|
|
378
|
-
const r = await gatewayJson("ai", "/v1/speech", { text, ...opts.voice ? { voice: opts.voice } : {}, ...opts.style ? { style: opts.style } : {} }, { signal: opts.signal, timeoutMs: 3e5 });
|
|
379
|
-
return { mediaType: "audio/wav", data: Buffer.from(r.data, "base64") };
|
|
380
|
-
},
|
|
381
|
-
// Speech to text, for audio up to one minute.
|
|
382
|
-
async transcribe(audio, opts) {
|
|
383
|
-
const data = Buffer.from(audio).toString("base64");
|
|
384
|
-
const r = await gatewayJson("ai", "/v1/transcribe", { mediaType: opts.mediaType, data, ...opts.languages ? { languages: opts.languages } : {} }, { signal: opts.signal, timeoutMs: 12e4 });
|
|
385
|
-
return { text: r.text, seconds: r.seconds };
|
|
386
|
-
}
|
|
387
|
-
};
|
|
388
|
-
|
|
389
|
-
// src/notify.ts
|
|
390
|
-
var notify = {
|
|
391
|
-
async email(to, subject, text) {
|
|
392
|
-
await gatewayJson("notify", "/v1/notify/email", { to: Array.isArray(to) ? to : [to], subject, text }, { timeoutMs: 3e4 });
|
|
393
|
-
},
|
|
394
|
-
async slack(text) {
|
|
395
|
-
await gatewayJson("notify", "/v1/notify/slack", { text }, { timeoutMs: 3e4 });
|
|
396
|
-
}
|
|
397
|
-
};
|
|
398
|
-
|
|
399
|
-
// src/secrets.ts
|
|
400
|
-
var cache = /* @__PURE__ */ new Map();
|
|
401
|
-
var TTL_MS = 5 * 6e4;
|
|
402
|
-
var secrets = {
|
|
403
|
-
async get(name) {
|
|
404
|
-
const bad = secretNameError(name);
|
|
405
|
-
if (bad) throw new BuildersError(`"${name}" is not a secret name. ${bad}`, 400);
|
|
406
|
-
if (process.env[APP_ENV.revision] === "preview") {
|
|
407
|
-
throw new BuildersError(`Secrets work only in the live app, not in a version preview. Make the version live to use ${name}; until then show a message instead.`, 503);
|
|
408
|
-
}
|
|
409
|
-
const project = process.env[APP_ENV.project];
|
|
410
|
-
if (!project) {
|
|
411
|
-
const v = process.env.NODE_ENV !== "production" ? process.env[name] : void 0;
|
|
412
|
-
if (v) return v;
|
|
413
|
-
throw new NotFoundError(`The secret ${name} is not available here. Secrets work in versions and the live app; for pnpm dev put ${name}=... in .env.local.`);
|
|
414
|
-
}
|
|
415
|
-
const hit = cache.get(name);
|
|
416
|
-
if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
|
|
417
|
-
const url = `https://secretmanager.googleapis.com/v1/projects/${encodeURIComponent(project)}/secrets/${name}/versions/latest:access`;
|
|
418
|
-
let res;
|
|
419
|
-
try {
|
|
420
|
-
res = await fetch(url, { headers: { authorization: `Bearer ${await googleAccessToken()}` }, signal: AbortSignal.timeout(1e4) });
|
|
421
|
-
} catch (e) {
|
|
422
|
-
throw new BuildersError(`Could not read the secret ${name}: ${e.message}`, 502);
|
|
423
|
-
}
|
|
424
|
-
if (res.status === 404 || res.status === 403) throw new NotFoundError(`The secret ${name} is not set. The app owner or an admin can set it in the Builders portal (app page, Secrets).`);
|
|
425
|
-
if (!res.ok) throw new BuildersError(`Could not read the secret ${name} (${res.status}).`, 502);
|
|
426
|
-
const j = await res.json();
|
|
427
|
-
const value = Buffer.from(j.payload?.data ?? "", "base64").toString("utf8");
|
|
428
|
-
cache.set(name, { value, at: Date.now() });
|
|
429
|
-
return value;
|
|
430
|
-
},
|
|
431
|
-
// For tests.
|
|
432
|
-
clearCache() {
|
|
433
|
-
cache.clear();
|
|
434
|
-
}
|
|
435
|
-
};
|
|
436
|
-
export {
|
|
437
|
-
AddOnNotEnabledError,
|
|
438
|
-
BuildersError,
|
|
439
|
-
IDENTITY_HEADER,
|
|
440
|
-
NotFoundError,
|
|
441
|
-
NotOnBuildersError,
|
|
442
|
-
NotSignedInError,
|
|
443
|
-
SIGN_OUT_PATH,
|
|
444
|
-
ai,
|
|
445
|
-
getUser,
|
|
446
|
-
nameFromEmail,
|
|
447
|
-
notify,
|
|
448
|
-
secrets
|
|
449
|
-
};
|
|
1
|
+
// @n-dream/builders-sdk (design 4.5, D13). Each later platform service
|
|
2
|
+
// adds one named export here (db, files, ai, ...).
|
|
3
|
+
export { appInfo, APP_INFO_PATH } from "./app-info.js";
|
|
4
|
+
export { BuildersError } from "./errors.js";
|
package/package.json
CHANGED
|
@@ -1,47 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@n-dream/builders-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Builders
|
|
3
|
+
"version": "1.0.0-next.0",
|
|
4
|
+
"description": "Builders SDK for app code: app information now, platform services later.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
|
-
"homepage": "https://builders.n-dream.com",
|
|
7
|
-
"keywords": [
|
|
8
|
-
"builders",
|
|
9
|
-
"nextjs"
|
|
10
|
-
],
|
|
11
6
|
"type": "module",
|
|
12
7
|
"main": "./dist/index.js",
|
|
13
8
|
"types": "./dist/index.d.ts",
|
|
14
9
|
"exports": {
|
|
15
10
|
".": {
|
|
16
11
|
"types": "./dist/index.d.ts",
|
|
17
|
-
"
|
|
18
|
-
}
|
|
19
|
-
"./next": {
|
|
20
|
-
"types": "./dist/next.d.ts",
|
|
21
|
-
"default": "./dist/next.js"
|
|
22
|
-
},
|
|
23
|
-
"./package.json": "./package.json"
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
}
|
|
24
14
|
},
|
|
25
15
|
"files": [
|
|
26
16
|
"dist",
|
|
27
17
|
"README.md"
|
|
28
18
|
],
|
|
29
|
-
"
|
|
30
|
-
"node": ">=22"
|
|
31
|
-
},
|
|
32
|
-
"dependencies": {
|
|
33
|
-
"jose": "^6.0.0",
|
|
34
|
-
"zod": "^4.6.7"
|
|
35
|
-
},
|
|
36
|
-
"peerDependencies": {
|
|
37
|
-
"next": ">=15"
|
|
38
|
-
},
|
|
39
|
-
"peerDependenciesMeta": {
|
|
40
|
-
"next": {
|
|
41
|
-
"optional": true
|
|
42
|
-
}
|
|
43
|
-
},
|
|
19
|
+
"sideEffects": false,
|
|
44
20
|
"publishConfig": {
|
|
45
|
-
"access": "public"
|
|
21
|
+
"access": "public",
|
|
22
|
+
"tag": "next"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsc -p tsconfig.build.json",
|
|
26
|
+
"test": "vitest run --minWorkers=1 --maxWorkers=2",
|
|
27
|
+
"typecheck": "tsc --noEmit"
|
|
46
28
|
}
|
|
47
|
-
}
|
|
29
|
+
}
|
|
@@ -1,136 +0,0 @@
|
|
|
1
|
-
// ../core/src/identity-token.ts
|
|
2
|
-
var IDENTITY_HEADER = "x-builders-identity";
|
|
3
|
-
var DEV_USER_HEADER = "x-builders-dev-user";
|
|
4
|
-
var SIGN_OUT_PATH = "/_builders/sign-out";
|
|
5
|
-
var IDENTITY_ALG = "ES256";
|
|
6
|
-
var IDENTITY_TOKEN_TTL_S = 60;
|
|
7
|
-
var IDENTITY_CLOCK_TOLERANCE_S = 30;
|
|
8
|
-
var IDENTITY_ENV = {
|
|
9
|
-
audience: "BUILDERS_IDENTITY_AUDIENCE",
|
|
10
|
-
issuer: "BUILDERS_IDENTITY_ISSUER",
|
|
11
|
-
jwksUrl: "BUILDERS_IDENTITY_JWKS_URL",
|
|
12
|
-
// Inline JWKS (JSON), for tests and BYOC setups without the bucket.
|
|
13
|
-
jwks: "BUILDERS_IDENTITY_JWKS"
|
|
14
|
-
};
|
|
15
|
-
|
|
16
|
-
// src/errors.ts
|
|
17
|
-
var BuildersError = class extends Error {
|
|
18
|
-
constructor(message, status = 500) {
|
|
19
|
-
super(message);
|
|
20
|
-
this.status = status;
|
|
21
|
-
this.name = "BuildersError";
|
|
22
|
-
}
|
|
23
|
-
status;
|
|
24
|
-
};
|
|
25
|
-
var NotSignedInError = class extends BuildersError {
|
|
26
|
-
constructor(message) {
|
|
27
|
-
super(message, 401);
|
|
28
|
-
this.name = "NotSignedInError";
|
|
29
|
-
}
|
|
30
|
-
};
|
|
31
|
-
var NotFoundError = class extends BuildersError {
|
|
32
|
-
constructor(message) {
|
|
33
|
-
super(message, 404);
|
|
34
|
-
this.name = "NotFoundError";
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
var ADDON_LABELS = {
|
|
38
|
-
ai: "AI",
|
|
39
|
-
storage: "file storage",
|
|
40
|
-
cron: "scheduled jobs",
|
|
41
|
-
notify: "notifications",
|
|
42
|
-
internet: "internet access"
|
|
43
|
-
};
|
|
44
|
-
var AddOnNotEnabledError = class extends BuildersError {
|
|
45
|
-
constructor(addOn) {
|
|
46
|
-
super(
|
|
47
|
-
`This add-on (${ADDON_LABELS[addOn]}) is not switched on for your app. Ask for it in the Builders portal.`,
|
|
48
|
-
503
|
|
49
|
-
);
|
|
50
|
-
this.addOn = addOn;
|
|
51
|
-
this.name = "AddOnNotEnabledError";
|
|
52
|
-
}
|
|
53
|
-
addOn;
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
// src/user.ts
|
|
57
|
-
import { createLocalJWKSet, createRemoteJWKSet, jwtVerify } from "jose";
|
|
58
|
-
var remoteKeys = /* @__PURE__ */ new Map();
|
|
59
|
-
function keysFrom(env) {
|
|
60
|
-
const inline = env[IDENTITY_ENV.jwks];
|
|
61
|
-
if (inline) return createLocalJWKSet(JSON.parse(inline));
|
|
62
|
-
const url = env[IDENTITY_ENV.jwksUrl];
|
|
63
|
-
if (!url) throw new BuildersError(`${IDENTITY_ENV.jwksUrl} is not set, so the signed-in user cannot be checked. The platform sets it on deploy.`);
|
|
64
|
-
let k = remoteKeys.get(url);
|
|
65
|
-
if (!k) {
|
|
66
|
-
k = createRemoteJWKSet(new URL(url), { cooldownDuration: 3e4, cacheMaxAge: 10 * 6e4 });
|
|
67
|
-
remoteKeys.set(url, k);
|
|
68
|
-
}
|
|
69
|
-
return k;
|
|
70
|
-
}
|
|
71
|
-
async function getUser(headers, opts = {}) {
|
|
72
|
-
const env = opts.env ?? process.env;
|
|
73
|
-
const token = readHeader(headers, IDENTITY_HEADER);
|
|
74
|
-
if (token) {
|
|
75
|
-
const audience = opts.audience ?? env[IDENTITY_ENV.audience];
|
|
76
|
-
const issuer = opts.issuer ?? env[IDENTITY_ENV.issuer];
|
|
77
|
-
if (!audience || !issuer) {
|
|
78
|
-
throw new BuildersError(
|
|
79
|
-
`${IDENTITY_ENV.audience} and ${IDENTITY_ENV.issuer} must be set, so the signed-in user can be checked. The platform sets them on deploy.`
|
|
80
|
-
);
|
|
81
|
-
}
|
|
82
|
-
let payload;
|
|
83
|
-
try {
|
|
84
|
-
({ payload } = await jwtVerify(token, opts.keys ?? keysFrom(env), {
|
|
85
|
-
issuer,
|
|
86
|
-
audience,
|
|
87
|
-
algorithms: [IDENTITY_ALG],
|
|
88
|
-
requiredClaims: ["exp", "iat", "email"],
|
|
89
|
-
maxTokenAge: IDENTITY_TOKEN_TTL_S + IDENTITY_CLOCK_TOLERANCE_S,
|
|
90
|
-
clockTolerance: IDENTITY_CLOCK_TOLERANCE_S
|
|
91
|
-
}));
|
|
92
|
-
} catch (e) {
|
|
93
|
-
if (e instanceof BuildersError) throw e;
|
|
94
|
-
throw new NotSignedInError(`The sign-in token is not valid: ${e.message}`);
|
|
95
|
-
}
|
|
96
|
-
if (typeof payload.email !== "string" || !payload.email || payload.email_verified !== true) {
|
|
97
|
-
throw new NotSignedInError("The sign-in token has no verified email address.");
|
|
98
|
-
}
|
|
99
|
-
const email = payload.email.toLowerCase();
|
|
100
|
-
return { email, name: typeof payload.name === "string" && payload.name ? payload.name : nameFromEmail(email) };
|
|
101
|
-
}
|
|
102
|
-
const viewer = readHeader(headers, DEV_USER_HEADER)?.trim();
|
|
103
|
-
const devUser = (viewer && viewer.length <= 254 && /^[^\s@]+@[^\s@]+$/.test(viewer) ? viewer : void 0) || env.BUILDERS_DEV_USER;
|
|
104
|
-
if (env.NODE_ENV !== "production" && devUser) {
|
|
105
|
-
return { email: devUser.toLowerCase(), name: nameFromEmail(devUser) };
|
|
106
|
-
}
|
|
107
|
-
throw new NotSignedInError(
|
|
108
|
-
env.NODE_ENV === "production" ? "No signed-in user. Open the app through its Builders link, which signs you in." : "No signed-in user. For local development set BUILDERS_DEV_USER (the dev script does this)."
|
|
109
|
-
);
|
|
110
|
-
}
|
|
111
|
-
function nameFromEmail(email) {
|
|
112
|
-
const local = email.split("@")[0] ?? "";
|
|
113
|
-
const parts = local.split(/[._-]+/).filter((p) => /^[a-z]+$/i.test(p));
|
|
114
|
-
if (parts.length === 0) return void 0;
|
|
115
|
-
return parts.map((p) => p[0].toUpperCase() + p.slice(1).toLowerCase()).join(" ");
|
|
116
|
-
}
|
|
117
|
-
function readHeader(headers, name) {
|
|
118
|
-
if (typeof headers.get === "function") {
|
|
119
|
-
return headers.get(name) ?? void 0;
|
|
120
|
-
}
|
|
121
|
-
const rec = headers;
|
|
122
|
-
const key = Object.keys(rec).find((k) => k.toLowerCase() === name);
|
|
123
|
-
const v = key === void 0 ? void 0 : rec[key];
|
|
124
|
-
return (Array.isArray(v) ? v[0] : v) || void 0;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
export {
|
|
128
|
-
IDENTITY_HEADER,
|
|
129
|
-
SIGN_OUT_PATH,
|
|
130
|
-
BuildersError,
|
|
131
|
-
NotSignedInError,
|
|
132
|
-
NotFoundError,
|
|
133
|
-
AddOnNotEnabledError,
|
|
134
|
-
getUser,
|
|
135
|
-
nameFromEmail
|
|
136
|
-
};
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { JWTVerifyGetKey } from 'jose';
|
|
2
|
-
|
|
3
|
-
interface User {
|
|
4
|
-
email: string;
|
|
5
|
-
name?: string;
|
|
6
|
-
}
|
|
7
|
-
type HeaderSource = {
|
|
8
|
-
get(name: string): string | null;
|
|
9
|
-
} | Record<string, string | string[] | undefined>;
|
|
10
|
-
interface GetUserOptions {
|
|
11
|
-
audience?: string;
|
|
12
|
-
issuer?: string;
|
|
13
|
-
keys?: JWTVerifyGetKey;
|
|
14
|
-
env?: Record<string, string | undefined>;
|
|
15
|
-
}
|
|
16
|
-
declare function getUser(headers: HeaderSource, opts?: GetUserOptions): Promise<User>;
|
|
17
|
-
declare function nameFromEmail(email: string): string | undefined;
|
|
18
|
-
|
|
19
|
-
export { getUser as g, nameFromEmail as n };
|
|
20
|
-
export type { GetUserOptions as G, HeaderSource as H, User as U };
|
package/dist/next.d.ts
DELETED