@emabuild/ai 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,148 @@
1
+ import { runAI } from './run.js';
2
+ import { corsHeaders } from '@emabuild/shared';
3
+ /** NDJSON content type used by the streaming protocol */
4
+ export const NDJSON_CONTENT_TYPE = 'application/x-ndjson; charset=utf-8';
5
+ const DEFAULT_MAX_BODY = 5 * 1024 * 1024;
6
+ function jsonResponse(status, body, headers) {
7
+ return new Response(JSON.stringify(body), {
8
+ status,
9
+ headers: { ...headers, 'content-type': 'application/json; charset=utf-8' },
10
+ });
11
+ }
12
+ /**
13
+ * Checks that a parsed body looks like an AIRequest. Returns an error message
14
+ * or null when valid.
15
+ */
16
+ export function validateAIRequest(body) {
17
+ if (!body || typeof body !== 'object' || Array.isArray(body))
18
+ return 'Body must be a JSON object';
19
+ const b = body;
20
+ if (typeof b.action !== 'string' || !b.action)
21
+ return '`action` must be a non-empty string';
22
+ if (typeof b.prompt !== 'string')
23
+ return '`prompt` must be a string';
24
+ if (b.context !== undefined && (typeof b.context !== 'object' || b.context === null || Array.isArray(b.context))) {
25
+ return '`context` must be an object';
26
+ }
27
+ const design = b.design;
28
+ const body_ = design?.body;
29
+ if (!design || typeof design !== 'object' || !body_ || typeof body_ !== 'object' || !Array.isArray(body_.rows)) {
30
+ return '`design` must be an EmailDesign with body.rows';
31
+ }
32
+ const schema = b.schema;
33
+ if (!schema || typeof schema !== 'object' || !Array.isArray(schema.tools))
34
+ return '`schema` must be a DesignSchema with tools';
35
+ if (b.mergeTags !== undefined && (typeof b.mergeTags !== 'object' || b.mergeTags === null)) {
36
+ return '`mergeTags` must be an array';
37
+ }
38
+ if (b.selection !== undefined && b.selection !== null && typeof b.selection !== 'object')
39
+ return '`selection` must be an object';
40
+ if (b.sourceHtml !== undefined && typeof b.sourceHtml !== 'string')
41
+ return '`sourceHtml` must be a string';
42
+ if (b.action === 'import-html' && !b.sourceHtml)
43
+ return '`sourceHtml` is required for the import-html action';
44
+ return null;
45
+ }
46
+ /**
47
+ * Creates a Web Fetch handler `(req: Request) => Promise<Response>` that
48
+ * speaks the editor's AI protocol: POST an AIRequest as JSON, receive an
49
+ * NDJSON stream of AIStreamEvents. Works in Node 18+, Bun, Deno, Cloudflare
50
+ * Workers, Next.js route handlers, Hono, etc.
51
+ */
52
+ export function createAIHandler(options = {}) {
53
+ const { cors = false, authorize, transformRequest, maxBodyBytes = DEFAULT_MAX_BODY, run = runAI, onError, ...runOptions } = options;
54
+ return async (req) => {
55
+ const ch = corsHeaders(req, cors);
56
+ if (req.method === 'OPTIONS')
57
+ return new Response(null, { status: 204, headers: ch });
58
+ if (req.method !== 'POST') {
59
+ return jsonResponse(405, { error: 'Method not allowed' }, { ...ch, allow: 'POST, OPTIONS' });
60
+ }
61
+ try {
62
+ if (authorize && !(await authorize(req)))
63
+ return jsonResponse(401, { error: 'Unauthorized' }, ch);
64
+ }
65
+ catch (err) {
66
+ onError?.(err);
67
+ return jsonResponse(401, { error: 'Unauthorized' }, ch);
68
+ }
69
+ const declared = Number(req.headers.get('content-length') ?? '0');
70
+ if (declared > maxBodyBytes)
71
+ return jsonResponse(413, { error: 'Request body too large' }, ch);
72
+ let text;
73
+ try {
74
+ text = await req.text();
75
+ }
76
+ catch {
77
+ return jsonResponse(400, { error: 'Could not read request body' }, ch);
78
+ }
79
+ if (text.length > maxBodyBytes)
80
+ return jsonResponse(413, { error: 'Request body too large' }, ch);
81
+ let body;
82
+ try {
83
+ body = JSON.parse(text);
84
+ }
85
+ catch {
86
+ return jsonResponse(400, { error: 'Body must be valid JSON' }, ch);
87
+ }
88
+ const invalid = validateAIRequest(body);
89
+ if (invalid)
90
+ return jsonResponse(400, { error: invalid }, ch);
91
+ let aiRequest = body;
92
+ aiRequest.context ??= {};
93
+ if (transformRequest) {
94
+ try {
95
+ aiRequest = await transformRequest(aiRequest, req);
96
+ }
97
+ catch (err) {
98
+ onError?.(err);
99
+ return jsonResponse(500, { error: 'Failed to prepare the AI request' }, ch);
100
+ }
101
+ }
102
+ // Abort the model call when the client disconnects or cancels the stream.
103
+ const abort = new AbortController();
104
+ const onClientAbort = () => abort.abort();
105
+ if (req.signal.aborted)
106
+ abort.abort();
107
+ else
108
+ req.signal.addEventListener('abort', onClientAbort, { once: true });
109
+ const encoder = new TextEncoder();
110
+ const iterator = run(aiRequest, { ...runOptions, signal: abort.signal })[Symbol.asyncIterator]();
111
+ const cleanup = () => req.signal.removeEventListener('abort', onClientAbort);
112
+ const stream = new ReadableStream({
113
+ async pull(controller) {
114
+ try {
115
+ const { value, done } = await iterator.next();
116
+ if (done) {
117
+ cleanup();
118
+ controller.close();
119
+ return;
120
+ }
121
+ controller.enqueue(encoder.encode(`${JSON.stringify(value)}\n`));
122
+ }
123
+ catch (err) {
124
+ onError?.(err);
125
+ cleanup();
126
+ const message = err instanceof Error ? err.message : String(err);
127
+ controller.enqueue(encoder.encode(`${JSON.stringify({ type: 'error', error: message })}\n`));
128
+ controller.close();
129
+ }
130
+ },
131
+ async cancel() {
132
+ abort.abort();
133
+ cleanup();
134
+ await iterator.return?.(undefined);
135
+ },
136
+ });
137
+ return new Response(stream, {
138
+ status: 200,
139
+ headers: {
140
+ ...ch,
141
+ 'content-type': NDJSON_CONTENT_TYPE,
142
+ 'cache-control': 'no-cache, no-transform',
143
+ 'x-accel-buffering': 'no',
144
+ },
145
+ });
146
+ };
147
+ }
148
+ //# sourceMappingURL=handler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handler.js","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAqB,MAAM,UAAU,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C,yDAAyD;AACzD,MAAM,CAAC,MAAM,mBAAmB,GAAG,qCAAqC,CAAC;AAqBzE,MAAM,gBAAgB,GAAG,CAAC,GAAG,IAAI,GAAG,I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AQ,CAAC,MAAM,EAAE;YAC1B,MAAM,EAAE,GAAG;YACX,OAAO,EAAE;gBACP,GAAG,EAAE;gBACL,cAAc,EAAE,mBAAmB;gBACnC,eAAe,EAAE,wBAAwB;gBACzC,mBAAmB,EAAE,IAAI;aAC1B;SACF,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Minimal Openverse (api.openverse.org) image search, no API key needed.
3
+ * Defaults to CC0 / public-domain results, which need no attribution.
4
+ * Mirrors @emabuild/core (src/images/openverse.ts); backs the `search_images` tool.
5
+ */
6
+ import type { FreeImage, FreeImageSearchOptions } from '@emabuild/types';
7
+ export interface OpenverseOptions extends FreeImageSearchOptions {
8
+ /** Openverse `license` filter (default "cc0,pdm") */
9
+ licenses?: string;
10
+ }
11
+ export declare function searchOpenverse(query: string, options?: OpenverseOptions): Promise<{
12
+ images: FreeImage[];
13
+ hasMore: boolean;
14
+ }>;
15
+ //# sourceMappingURL=images.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"images.d.ts","sourceRoot":"","sources":["../src/images.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAMzE,MAAM,WAAW,gBAAiB,SAAQ,sBAAsB;IAC9D,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,wBAAsB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB,GAAG,OAAO,CAAC;IAAE,MAAM,EAAE,SAAS,EAAE,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC,CAuCvI"}
package/dist/images.js ADDED
@@ -0,0 +1,48 @@
1
+ const API = 'https://api.openverse.org/v1/images/';
2
+ const ASPECT = { landscape: 'wide', portrait: 'tall', square: 'square' };
3
+ const TIMEOUT_MS = 12000;
4
+ export async function searchOpenverse(query, options = {}) {
5
+ const params = new URLSearchParams({
6
+ q: query,
7
+ license: options.licenses ?? 'cc0,pdm',
8
+ page_size: String(Math.min(Math.max(options.count ?? 20, 1), 20)),
9
+ page: String(options.page ?? 1),
10
+ mature: 'false',
11
+ extension: 'jpg,png',
12
+ });
13
+ if (options.orientation)
14
+ params.set('aspect_ratio', ASPECT[options.orientation]);
15
+ // Openverse can be slow: give up after a while instead of hanging the UI
16
+ const ctrl = new AbortController();
17
+ const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);
18
+ const onAbort = () => ctrl.abort();
19
+ options.signal?.addEventListener('abort', onAbort);
20
+ try {
21
+ const res = await fetch(`${API}?${params}`, { signal: ctrl.signal });
22
+ if (!res.ok)
23
+ throw new Error(`Openverse ${res.status}`);
24
+ const data = await res.json();
25
+ const images = (data.results ?? []).filter((r) => r.url).map((r) => ({
26
+ url: String(r.url).replace(/^http:/, 'https:'),
27
+ thumbnail: r.thumbnail || r.url,
28
+ width: r.width ?? undefined,
29
+ height: r.height ?? undefined,
30
+ title: r.title || undefined,
31
+ creator: r.creator || undefined,
32
+ license: r.license,
33
+ licenseUrl: r.license_url || undefined,
34
+ landingUrl: r.foreign_landing_url || undefined,
35
+ }));
36
+ return { images, hasMore: (options.page ?? 1) < (data.page_count ?? 1) };
37
+ }
38
+ catch (err) {
39
+ if (ctrl.signal.aborted && !options.signal?.aborted)
40
+ throw new Error('Openverse did not respond in time');
41
+ throw err;
42
+ }
43
+ finally {
44
+ clearTimeout(timer);
45
+ options.signal?.removeEventListener('abort', onAbort);
46
+ }
47
+ }
48
+ //# sourceMappingURL=images.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"images.js","sourceRoot":"","sources":["../src/images.ts"],"names":[],"mappings":"AAOA,MAAM,GAAG,GAAG,sCAAsC,CAAC;AACnD,MAAM,MAAM,GAAG,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAW,CAAC;A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AC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @emabuild/ai — server side of the Emabuild editor's AI connector.
3
+ *
4
+ * Turns an `AIRequest` into a stream of `AIStreamEvent`s using Claude, and
5
+ * exposes it over HTTP as NDJSON.
6
+ */
7
+ export { runAI, buildRequestParams, DEFAULT_MODEL, DEFAULT_MAX_TOKENS, DEFAULT_MAX_TURNS, type RunAIOptions, type RequestParams, type AIEffort, } from './run.js';
8
+ export { MODEL_PRICING, pricingFor, UsageMeter, type ModelPricing, type MessageUsage } from './usage.js';
9
+ export { createAIHandler, validateAIRequest, NDJSON_CONTENT_TYPE, type AIHandlerOptions } from './handler.js';
10
+ export { toNodeHandler, type FetchHandler, type NodeHandler } from '@emabuild/shared/node';
11
+ export { BASE_SYSTEM_PROMPT, buildSchemaPrompt, buildUserPrompt, flattenMergeTags, compactSourceHtml, MAX_SOURCE_HTML } from './prompt.js';
12
+ export { compactDesign, compactContent, describeSchema, pruneValues, isDesignEmpty, type CompactDesign } from './compact.js';
13
+ export { validateOperations, DesignState, type ValidationResult } from './validate.js';
14
+ export { AI_TOOLS, OPERATION_SCHEMA, APPLY_OPERATIONS_TOOL, FINISH_TOOL } from './tools.js';
15
+ export type { AIRequest, AIStreamEvent, AIUsage, DesignOperation } from '@emabuild/types';
16
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EACL,KAAK,EACL,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,iBAAiB,EACjB,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,QAAQ,GACd,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,UAAU,EAAE,KAAK,YAAY,EAAE,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AACzG,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,KAAK,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC9G,OAAO,EAAE,aAAa,EAAE,KAAK,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAC3F,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,eAAe,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC3I,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,cAAc,EAAE,WAAW,EAAE,aAAa,EAAE,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7H,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACvF,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC5F,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @emabuild/ai — server side of the Emabuild editor's AI connector.
3
+ *
4
+ * Turns an `AIRequest` into a stream of `AIStreamEvent`s using Claude, and
5
+ * exposes it over HTTP as NDJSON.
6
+ */
7
+ export { runAI, buildRequestParams, DEFAULT_MODEL, DEFAULT_MAX_TOKENS, DEFAULT_MAX_TURNS, } from './run.js';
8
+ export { MODEL_PRICING, pricingFor, UsageMeter } from './usage.js';
9
+ export { createAIHandler, validateAIRequest, NDJSON_CONTENT_TYPE } from './handler.js';
10
+ export { toNodeHandler } from '@emabuild/shared/node';
11
+ export { BASE_SYSTEM_PROMPT, buildSchemaPrompt, buildUserPrompt, flattenMergeTags, compactSourceHtml, MAX_SOURCE_HTML } from './prompt.js';
12
+ export { compactDesign, compactContent, describeSchema, pruneValues, isDesignEmpty } from './compact.js';
13
+ export { validateOperations, DesignState } from './validate.js';
14
+ export { AI_TOOLS, OPERATION_SCHEMA, APPLY_OPERATIONS_TOOL, FINISH_TOOL } from './tools.js';
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EACL,KAAK,EACL,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,iBAAiB,GAIlB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,UAAU,EAAwC,MAAM,YAAY,CAAC;AACzG,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,mBAAmB,EAAyB,MAAM,cAAc,CAAC;AAC9G,OAAO,EAAE,aAAa,EAAuC,MAAM,uBAAuB,CAAC;AAC3F,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,eAAe,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC3I,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,cAAc,EAAE,WAAW,EAAE,aAAa,EAAsB,MAAM,cAAc,CAAC;AAC7H,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAyB,MAAM,eAAe,CAAC;AACvF,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC"}
package/dist/node.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ /** A Web Fetch style handler */
3
+ export type FetchHandler = (req: Request) => Response | Promise<Response>;
4
+ /** A `node:http` / Express style handler */
5
+ export type NodeHandler = (req: IncomingMessage & {
6
+ body?: unknown;
7
+ originalUrl?: string;
8
+ }, res: ServerResponse, next?: (err?: unknown) => void) => Promise<void>;
9
+ /**
10
+ * Adapts a Web Fetch handler (such as the one returned by `createAIHandler`)
11
+ * to `node:http` / Express `(req, res)`. Response bodies are streamed chunk
12
+ * by chunk (respecting backpressure), and a client disconnect aborts the
13
+ * request signal so the model call is cancelled.
14
+ */
15
+ export declare function toNodeHandler(handler: FetchHandler): NodeHandler;
16
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEjE,gCAAgC;AAChC,MAAM,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AAE1E,4CAA4C;AAC5C,MAAM,MAAM,WAAW,GAAG,CACxB,GAAG,EAAE,eAAe,GAAG;IAAE,IAAI,CAAC,EAAE,OAAO,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,EAC/D,GAAG,EAAE,cAAc,EACnB,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,KAAK,IAAI,KAC3B,OAAO,CAAC,IAAI,CAAC,CAAC;AAuCnB;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,GAAG,WAAW,CA2DhE"}
package/dist/node.js ADDED
@@ -0,0 +1,117 @@
1
+ async function readBody(req) {
2
+ const method = (req.method ?? 'GET').toUpperCase();
3
+ if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS')
4
+ return undefined;
5
+ // Body already consumed by a parser middleware (e.g. express.json())
6
+ if (req.body !== undefined) {
7
+ if (typeof req.body === 'string')
8
+ return req.body;
9
+ if (Buffer.isBuffer(req.body))
10
+ return req.body.toString('utf8');
11
+ return JSON.stringify(req.body);
12
+ }
13
+ const chunks = [];
14
+ for await (const chunk of req)
15
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
16
+ return Buffer.concat(chunks).toString('utf8');
17
+ }
18
+ /** Resolves when the response can take more data or the connection closes */
19
+ function waitForDrain(res) {
20
+ return new Promise((resolve) => {
21
+ const done = () => {
22
+ res.off('drain', done);
23
+ res.off('close', done);
24
+ resolve();
25
+ };
26
+ res.on('drain', done);
27
+ res.on('close', done);
28
+ });
29
+ }
30
+ function toHeaders(req) {
31
+ const headers = new Headers();
32
+ for (const [key, value] of Object.entries(req.headers)) {
33
+ if (value === undefined)
34
+ continue;
35
+ if (Array.isArray(value))
36
+ value.forEach((v) => headers.append(key, v));
37
+ else
38
+ headers.set(key, value);
39
+ }
40
+ return headers;
41
+ }
42
+ /**
43
+ * Adapts a Web Fetch handler (such as the one returned by `createAIHandler`)
44
+ * to `node:http` / Express `(req, res)`. Response bodies are streamed chunk
45
+ * by chunk (respecting backpressure), and a client disconnect aborts the
46
+ * request signal so the model call is cancelled.
47
+ */
48
+ export function toNodeHandler(handler) {
49
+ return async (req, res, next) => {
50
+ const abort = new AbortController();
51
+ const onClose = () => {
52
+ if (!res.writableFinished)
53
+ abort.abort();
54
+ };
55
+ res.on('close', onClose);
56
+ try {
57
+ const host = req.headers.host ?? 'localhost';
58
+ const proto = req.headers['x-forwarded-proto']?.split(',')[0]?.trim() || 'http';
59
+ const url = new URL(req.originalUrl ?? req.url ?? '/', `${proto}://${host}`);
60
+ const body = await readBody(req);
61
+ const request = new Request(url, {
62
+ method: req.method,
63
+ headers: toHeaders(req),
64
+ body,
65
+ signal: abort.signal,
66
+ });
67
+ const response = await handler(request);
68
+ const headers = {};
69
+ response.headers.forEach((value, key) => {
70
+ headers[key] = value;
71
+ });
72
+ const cookies = response.headers.getSetCookie?.();
73
+ if (cookies?.length)
74
+ headers['set-cookie'] = cookies;
75
+ res.writeHead(response.status, headers);
76
+ res.flushHeaders?.();
77
+ if (!response.body) {
78
+ res.end();
79
+ return;
80
+ }
81
+ const reader = response.body.getReader();
82
+ try {
83
+ while (true) {
84
+ const { value, done } = await reader.read();
85
+ if (done)
86
+ break;
87
+ if (abort.signal.aborted)
88
+ break;
89
+ if (!res.write(value))
90
+ await waitForDrain(res);
91
+ }
92
+ }
93
+ finally {
94
+ if (abort.signal.aborted)
95
+ await reader.cancel().catch(() => undefined);
96
+ else
97
+ reader.releaseLock();
98
+ }
99
+ res.end();
100
+ }
101
+ catch (err) {
102
+ if (next)
103
+ return next(err);
104
+ if (!res.headersSent) {
105
+ res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
106
+ res.end(JSON.stringify({ error: 'Internal server error' }));
107
+ }
108
+ else {
109
+ res.destroy(err instanceof Error ? err : undefined);
110
+ }
111
+ }
112
+ finally {
113
+ res.off('close', onClose);
114
+ }
115
+ };
116
+ }
117
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAYA,KAAK,UAAU,QAAQ,CAAC,GAAyC;IAC/D,MAAM,MAAM,GAAG,CAAC,GAAG,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;IACnD,IAAI,MAAM,KAAK,KAAK,IAAI,MAAM,KAAK,MAAM,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IACpF,qEAAqE;IACrE,IAAI,GAAG,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAC3B,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,QAAQ;YAAE,OAAO,GAAG,CAAC,IAAI,CAAC;QAClD,IAAI,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC;YAAE,OAAO,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QAChE,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAClC,CAAC;IACD,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,GAAG;QAAE,MAAM,CAAC,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IA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,CAAC,EAAE,KAAK,EAAE,uBAAuB,EAAE,CAAC,CAAC,CAAC;YAC9D,CAAC;iBAAM,CAAC;gBACN,GAAG,CAAC,OAAO,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;YACtD,CAAC;QACH,CAAC;gBAAS,CAAC;YACT,GAAG,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5B,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,28 @@
1
+ import type { AIRequest } from '@emabuild/types';
2
+ /**
3
+ * Static part of the system prompt. It never varies between requests, so it
4
+ * is sent as its own cacheable block.
5
+ */
6
+ export declare const BASE_SYSTEM_PROMPT = "You are the AI assistant inside Emabuild, a drag-and-drop email template editor. You build and edit email templates by calling the `apply_operations` tool; every batch you send is applied live on the user's canvas as one undo step, so the user watches the email take shape.\n\n# The design model\nAn email has a body (global values such as backgroundColor, contentWidth, fontFamily, textColor, subject, preheaderText, language) with rows. A row has `cells` (column proportions, e.g. [1], [1, 1], [1, 2]) and one column per cell. Columns hold content blocks; each block has a `type` (a tool from the schema) and `values`.\n\n# Operations\n- Existing nodes are referenced by their real ids from the current design.\n- New nodes get their ids from the editor, which you never see. To refer to something you create, set `ref` on `addRow` / `addContent` (short, unique, e.g. \"hero\", \"cta\"). Then:\n - a row ref works anywhere a rowId is expected;\n - its columns are \"<rowRef>:<columnIndex>\" (0-based), e.g. columnId \"hero:0\";\n - a content ref works anywhere a contentId is expected.\n Refs stay valid for the whole session.\n- `values` only needs the keys you want to change; the editor fills the rest from the tool defaults. Use the property keys, value formats and dropdown options listed in the schema (look at the defaults to learn formats such as \"10px 20px\" paddings or hex colors). Do not invent keys.\n- Text-like tools (text, heading, paragraph\u2026) keep HTML in `text`: use simple inline markup (p, br, strong, em, a, span with inline style, ul/ol/li). No scripts, no <style> blocks, no classes that rely on external CSS.\n- Buttons take a label in `text` and a link in `href` (check the schema for the exact shape).\n- Prefer incremental operations. `replaceDesign` is a last resort and should practically never be needed.\n- If a batch is rejected, nothing in it was applied: read the error, fix the batch and send it again.\n\n# Building templates\n- When building a template, work top to bottom and send one row per `apply_operations` call (an `addRow` with its `columns[].contents`, or an `addRow` with a ref followed by `addContent` ops), so the user sees progress row by row.\n- Typical structure: header with logo, hero (headline, short intro, primary call to action), 1-3 content sections, secondary call to action, footer (company info, unsubscribe link). Adapt it to the brief.\n- Email-safe design: single-column first and at most 3 columns, content width around 600px, generous padding, clear hierarchy, sufficient contrast, web-safe or provided fonts, descriptive image alt text, real-looking hrefs (use links from the context; otherwise use the brand website or \"#\").\n- Images: use URLs from the context (logo, product images\u2026) first. Otherwise, if the `search_images` tool is available, search free photos for heroes and content images: short English queries describing the subject (\"autumn leaves\", \"running shoes\"), orientation matching the slot (landscape for heroes and wide banners), and use a returned `url` with its width/height. Never use search results for logos or specific products. If no tool is available or a search finds nothing usable, use placeholders like https://placehold.co/600x300?text=Hero and keep them consistent in size.\n- Use the brand colors, fonts and voice when provided.\n\n# Copy\n- Write copy in the requested language (context.language); if none is given, use the language of the user's prompt.\n- Follow the tone, audience and goal from the context. Use products, offers and other data from the context verbatim (names, prices, links); never make up prices or facts that contradict it.\n- Merge tags are placeholders replaced at send time. Keep existing merge tags exactly as written. Use the listed merge tag values where personalization helps (e.g. a greeting), and never invent merge tags that are not listed.\n\n# Working style\n- Do not ask questions: make reasonable assumptions and proceed.\n- Before your first tool call, write one short sentence telling the user what you are about to do. Do not narrate ids, JSON or operations.\n- When everything is applied, call `finish` with a 1-2 sentence summary for the user, in the language of the copy.";
7
+ /** Upper bound for the source HTML sent to the model (characters, after compaction) */
8
+ export declare const MAX_SOURCE_HTML = 180000;
9
+ /**
10
+ * Shrink HTML before sending it to the model: drop scripts, comments
11
+ * (including Outlook conditionals), meta/link tags and redundant whitespace,
12
+ * then cap the length.
13
+ */
14
+ export declare function compactSourceHtml(html: string, max?: number): string;
15
+ /** Flattens merge tag groups / definitions (any nesting) into name → value pairs */
16
+ export declare function flattenMergeTags(input: unknown): Array<{
17
+ name: string;
18
+ value: string;
19
+ sample?: string;
20
+ }>;
21
+ /** Builds the per-schema system block (cacheable as long as the editor's tool set is unchanged) */
22
+ export declare function buildSchemaPrompt(request: Pick<AIRequest, 'schema'>): string;
23
+ /**
24
+ * Builds the user message for a request: task, context, merge tags,
25
+ * selection, current design (compacted) and the user's prompt.
26
+ */
27
+ export declare function buildUserPrompt(request: AIRequest): string;
28
+ //# sourceMappingURL=prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAsB,MAAM,iBAAiB,CAAC;AAIrE;;;GAGG;AACH,eAAO,MAAM,kBAAkB,qpIAiC8F,CAAC;AAoB9H,uFAAuF;AACvF,eAAO,MAAM,eAAe,SAAU,CAAC;AAEvC;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,SAAkB,GAAG,MAAM,CAW7E;AAID,oFAAoF;AACpF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAkBxG;AAED,mGAAmG;AACnG,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC,GAAG,MAAM,CAI5E;AAMD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,SAAS,GAAG,MAAM,CAmD1D"}
package/dist/prompt.js ADDED
@@ -0,0 +1,155 @@
1
+ import { compactContent, compactDesign, describeSchema, isDesignEmpty } from './compact.js';
2
+ import { APPLY_OPERATIONS_TOOL, FINISH_TOOL, SEARCH_IMAGES_TOOL } from './tools.js';
3
+ /**
4
+ * Static part of the system prompt. It never varies between requests, so it
5
+ * is sent as its own cacheable block.
6
+ */
7
+ export const BASE_SYSTEM_PROMPT = `You are the AI assistant inside Emabuild, a drag-and-drop email template editor. You build and edit email templates by calling the \`${APPLY_OPERATIONS_TOOL}\` tool; every batch you send is applied live on the user's canvas as one undo step, so the user watches the email take shape.
8
+
9
+ # The design model
10
+ An email has a body (global values such as backgroundColor, contentWidth, fontFamily, textColor, subject, preheaderText, language) with rows. A row has \`cells\` (column proportions, e.g. [1], [1, 1], [1, 2]) and one column per cell. Columns hold content blocks; each block has a \`type\` (a tool from the schema) and \`values\`.
11
+
12
+ # Operations
13
+ - Existing nodes are referenced by their real ids from the current design.
14
+ - New nodes get their ids from the editor, which you never see. To refer to something you create, set \`ref\` on \`addRow\` / \`addContent\` (short, unique, e.g. "hero", "cta"). Then:
15
+ - a row ref works anywhere a rowId is expected;
16
+ - its columns are "<rowRef>:<columnIndex>" (0-based), e.g. columnId "hero:0";
17
+ - a content ref works anywhere a contentId is expected.
18
+ Refs stay valid for the whole session.
19
+ - \`values\` only needs the keys you want to change; the editor fills the rest from the tool defaults. Use the property keys, value formats and dropdown options listed in the schema (look at the defaults to learn formats such as "10px 20px" paddings or hex colors). Do not invent keys.
20
+ - Text-like tools (text, heading, paragraph…) keep HTML in \`text\`: use simple inline markup (p, br, strong, em, a, span with inline style, ul/ol/li). No scripts, no <style> blocks, no classes that rely on external CSS.
21
+ - Buttons take a label in \`text\` and a link in \`href\` (check the schema for the exact shape).
22
+ - Prefer incremental operations. \`replaceDesign\` is a last resort and should practically never be needed.
23
+ - If a batch is rejected, nothing in it was applied: read the error, fix the batch and send it again.
24
+
25
+ # Building templates
26
+ - When building a template, work top to bottom and send one row per \`${APPLY_OPERATIONS_TOOL}\` call (an \`addRow\` with its \`columns[].contents\`, or an \`addRow\` with a ref followed by \`addContent\` ops), so the user sees progress row by row.
27
+ - Typical structure: header with logo, hero (headline, short intro, primary call to action), 1-3 content sections, secondary call to action, footer (company info, unsubscribe link). Adapt it to the brief.
28
+ - Email-safe design: single-column first and at most 3 columns, content width around 600px, generous padding, clear hierarchy, sufficient contrast, web-safe or provided fonts, descriptive image alt text, real-looking hrefs (use links from the context; otherwise use the brand website or "#").
29
+ - Images: use URLs from the context (logo, product images…) first. Otherwise, if the \`${SEARCH_IMAGES_TOOL}\` tool is available, search free photos for heroes and content images: short English queries describing the subject ("autumn leaves", "running shoes"), orientation matching the slot (landscape for heroes and wide banners), and use a returned \`url\` with its width/height. Never use search results for logos or specific products. If no tool is available or a search finds nothing usable, use placeholders like https://placehold.co/600x300?text=Hero and keep them consistent in size.
30
+ - Use the brand colors, fonts and voice when provided.
31
+
32
+ # Copy
33
+ - Write copy in the requested language (context.language); if none is given, use the language of the user's prompt.
34
+ - Follow the tone, audience and goal from the context. Use products, offers and other data from the context verbatim (names, prices, links); never make up prices or facts that contradict it.
35
+ - Merge tags are placeholders replaced at send time. Keep existing merge tags exactly as written. Use the listed merge tag values where personalization helps (e.g. a greeting), and never invent merge tags that are not listed.
36
+
37
+ # Working style
38
+ - Do not ask questions: make reasonable assumptions and proceed.
39
+ - Before your first tool call, write one short sentence telling the user what you are about to do. Do not narrate ids, JSON or operations.
40
+ - When everything is applied, call \`${FINISH_TOOL}\` with a 1-2 sentence summary for the user, in the language of the copy.`;
41
+ const ACTION_INSTRUCTIONS = {
42
+ generate: 'Build a complete email template from the brief. Build it incrementally, one row per tool call, top to bottom.',
43
+ edit: 'Modify the existing template as the prompt asks. Change only what is needed, keep existing ids, structure and content that the prompt does not mention.',
44
+ rewrite: 'Rewrite the copy as the prompt asks, keeping the meaning, HTML structure, inline styles, links and merge tags.',
45
+ shorten: 'Make the copy noticeably shorter and punchier while keeping the key message, HTML structure, inline styles, links and merge tags.',
46
+ translate: 'Translate the copy into the target language (from the prompt, or context.language). Keep the HTML structure, inline styles, links and merge tags unchanged; translate alt text and button labels too.',
47
+ subject: 'Write the subject line and preheader for the current template, based on its content and the prompt. Call applyOperations once with a single updateBody { subject, preheaderText }: subject at most 60 characters, specific and not spammy (no ALL CAPS, at most one emoji, no "free!!!"); preheader 40-100 characters that complements the subject instead of repeating it. Write in context.language, or the language of the template copy. Keep merge tags valid. Change nothing else.',
48
+ 'import-html': 'Recreate the email in <source_html> as a design, as faithfully as possible: same section order and column layout, the same copy verbatim (merge tags included), links, image URLs, alt text, colors, font sizes, paddings and alignment. ' +
49
+ 'Start with one updateBody (backgroundColor, contentWidth, fontFamily, textColor; preheaderText from the hidden preheader, if any). Then build one row per call, top to bottom: side-by-side cells become columns of one row, full-width bands become row backgroundColor, the content-area color becomes columnsBackgroundColor. ' +
50
+ 'Map every part to the closest native tool (heading, text, image, button, divider, menu, social…); use an `html` block only for what no tool can represent. Never invent, rewrite or translate content unless the prompt asks to. Ignore scripts, tracking pixels (1×1 images) and Outlook conditional comments.',
51
+ };
52
+ /** Upper bound for the source HTML sent to the model (characters, after compaction) */
53
+ export const MAX_SOURCE_HTML = 180_000;
54
+ /**
55
+ * Shrink HTML before sending it to the model: drop scripts, comments
56
+ * (including Outlook conditionals), meta/link tags and redundant whitespace,
57
+ * then cap the length.
58
+ */
59
+ export function compactSourceHtml(html, max = MAX_SOURCE_HTML) {
60
+ let out = (html ?? '')
61
+ .replace(/<script\b[\s\S]*?<\/script>/gi, '')
62
+ .replace(/<!--[\s\S]*?-->/g, '')
63
+ .replace(/<(meta|link)\b[^>]*>/gi, '')
64
+ .replace(/\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*')/gi, '')
65
+ .replace(/[\t ]+/g, ' ')
66
+ .replace(/\s*\n\s*/g, '\n')
67
+ .trim();
68
+ if (out.length > max)
69
+ out = `${out.slice(0, max)}\n<!-- truncated: the source is longer; recreate what is above -->`;
70
+ return out;
71
+ }
72
+ const TEXT_ACTIONS = new Set(['rewrite', 'shorten', 'translate']);
73
+ /** Flattens merge tag groups / definitions (any nesting) into name → value pairs */
74
+ export function flattenMergeTags(input) {
75
+ const out = [];
76
+ const visitDef = (def) => {
77
+ if (!def || typeof def !== 'object')
78
+ return;
79
+ if (typeof def.value === 'string' && def.value)
80
+ out.push({ name: def.name ?? def.value, value: def.value, sample: def.sample });
81
+ if (def.mergeTags)
82
+ Object.values(def.mergeTags).forEach(visitDef);
83
+ };
84
+ const visit = (item) => {
85
+ if (!item || typeof item !== 'object')
86
+ return;
87
+ const rec = item;
88
+ if (typeof rec.value === 'string')
89
+ return visitDef(rec);
90
+ if (rec.mergeTags && typeof rec.mergeTags === 'object') {
91
+ Object.values(rec.mergeTags).forEach(visitDef);
92
+ }
93
+ };
94
+ if (Array.isArray(input))
95
+ input.forEach(visit);
96
+ else if (input && typeof input === 'object')
97
+ Object.values(input).forEach(visit);
98
+ return out;
99
+ }
100
+ /** Builds the per-schema system block (cacheable as long as the editor's tool set is unchanged) */
101
+ export function buildSchemaPrompt(request) {
102
+ return `# Tool schema\nEvery property below can be set in \`values\`. Format: "- key [widget] options: … default: …".\n\n${describeSchema(request.schema)}`;
103
+ }
104
+ function json(value) {
105
+ return JSON.stringify(value);
106
+ }
107
+ /**
108
+ * Builds the user message for a request: task, context, merge tags,
109
+ * selection, current design (compacted) and the user's prompt.
110
+ */
111
+ export function buildUserPrompt(request) {
112
+ const action = request.action || 'edit';
113
+ const parts = [];
114
+ const empty = isDesignEmpty(request.design);
115
+ const selected = request.selection?.content;
116
+ let task = ACTION_INSTRUCTIONS[action] ?? `Perform the "${action}" action described by the prompt.`;
117
+ if (action === 'generate' && !empty) {
118
+ task +=
119
+ ' The design already has content: unless the prompt says to keep or extend it, start with one batch removing the existing rows, then build the new template.';
120
+ }
121
+ if (TEXT_ACTIONS.has(action)) {
122
+ task += selected
123
+ ? ` Apply it only to the selected block "${selected.id}" with a single updateContent operation; do not touch anything else.`
124
+ : ` No block is selected: apply it to every block that holds copy, using updateContent operations.${action === 'translate'
125
+ ? ' Then send one updateBody with the translated subject, preheaderText and title, and language set to the target language code (e.g. "en").'
126
+ : ''}`;
127
+ }
128
+ else if (request.selection) {
129
+ task += ` The user has selected ${request.selection.kind} "${request.selection.id}"${request.selection.type ? ` (${request.selection.type})` : ''}; focus on it when the prompt refers to "this" or is ambiguous.`;
130
+ }
131
+ parts.push(`<task action="${action}">\n${task}\n</task>`);
132
+ const context = request.context ?? {};
133
+ if (Object.keys(context).length > 0)
134
+ parts.push(`<context>\n${json(context)}\n</context>`);
135
+ const lang = context.language ?? null;
136
+ if (!lang && request.locale)
137
+ parts.push(`<editor_locale>${request.locale}</editor_locale>`);
138
+ const tags = flattenMergeTags(request.mergeTags);
139
+ if (tags.length > 0) {
140
+ parts.push(`<merge_tags>\n${tags.map((t) => `- ${t.name}: ${t.value}${t.sample ? ` (e.g. ${t.sample})` : ''}`).join('\n')}\n</merge_tags>`);
141
+ }
142
+ if (request.selection) {
143
+ const sel = selected ? { ...request.selection, content: compactContent(selected, request.schema) } : request.selection;
144
+ parts.push(`<selection>\n${json(sel)}\n</selection>`);
145
+ }
146
+ parts.push(empty
147
+ ? `<design>\nThe design is empty (no rows yet). Body values: ${json(compactDesign(request.design, request.schema).body.values)}\n</design>`
148
+ : `<design>\n${json(compactDesign(request.design, request.schema))}\n</design>`);
149
+ if (typeof request.sourceHtml === 'string' && request.sourceHtml) {
150
+ parts.push(`<source_html>\n${compactSourceHtml(request.sourceHtml)}\n</source_html>`);
151
+ }
152
+ parts.push(`<user_prompt>\n${request.prompt ?? ''}\n</user_prompt>`);
153
+ return parts.join('\n\n');
154
+ }
155
+ //# sourceMappingURL=prompt.js.map