@open-artifact/server-sdk 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/bin/frame-host.d.ts +2 -0
- package/bin/frame-host.js +29 -0
- package/package.json +71 -4
- package/src/daemon.d.ts +65 -0
- package/src/daemon.js +157 -0
- package/src/frame/client/comments.css +1 -0
- package/src/frame/client/comments.js +57 -0
- package/src/frame/client/runtime.js +995 -0
- package/src/frame/client/shell.css +45 -0
- package/src/frame/client/shell.html +29 -0
- package/src/frame/client/shell.js +990 -0
- package/src/frame/comments.d.ts +87 -0
- package/src/frame/comments.js +228 -0
- package/src/frame/db.d.ts +149 -0
- package/src/frame/db.js +573 -0
- package/src/frame/declaration.d.ts +24 -0
- package/src/frame/declaration.js +65 -0
- package/src/frame/files.d.ts +107 -0
- package/src/frame/files.js +348 -0
- package/src/frame/index.d.ts +138 -0
- package/src/frame/index.js +1075 -0
- package/src/frame/wire.d.ts +184 -0
- package/src/frame/wire.js +21 -0
- package/src/index.d.ts +15 -0
- package/src/index.js +15 -0
- package/src/lan.d.ts +74 -0
- package/src/lan.js +201 -0
- package/src/serve.d.ts +362 -0
- package/src/serve.js +779 -0
- package/src/ws.d.ts +46 -0
- package/src/ws.js +182 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The artifact's files as an original page sees them: everything in the
|
|
3
|
+
* artifact folder except what the host keeps for itself, listed as
|
|
4
|
+
* `_files.json` `{ver, files: {path: {sha256, size, contentType}}}`. `ver`
|
|
5
|
+
* names one state of that list. `publish` writes a batch of files with
|
|
6
|
+
* optional per-file preconditions (`ifMatch`: the sha256 the page last saw, or
|
|
7
|
+
* null for "must not exist") and answers `conflict` when one does not hold.
|
|
8
|
+
* Blobs (the assets capability) are content-addressed files under `_blobs/`.
|
|
9
|
+
*/
|
|
10
|
+
export declare const PUBLISH_MAX_PATHS = 256;
|
|
11
|
+
export declare const FILE_MAX_BYTES: number;
|
|
12
|
+
export declare const BLOB_MAX_BYTES: number;
|
|
13
|
+
export declare const BLOB_SVG_MAX_BYTES: number;
|
|
14
|
+
export declare const BLOB_CODE_MAX_BYTES: number;
|
|
15
|
+
export declare const BLOBS_MAX_FILES = 2000;
|
|
16
|
+
export declare const BLOBS_MAX_BYTES: number;
|
|
17
|
+
export declare const BLOB_TYPES: ReadonlySet<string>;
|
|
18
|
+
export declare const contentTypeOf: (file: string) => string;
|
|
19
|
+
export declare class FrameError extends Error {
|
|
20
|
+
readonly code: string;
|
|
21
|
+
readonly status: number;
|
|
22
|
+
readonly extra: Record<string, unknown>;
|
|
23
|
+
constructor(code: string, message: string, status?: number, extra?: Record<string, unknown>);
|
|
24
|
+
}
|
|
25
|
+
/** Paths of the type (never the artifact's): neither listed nor writable by a page. */
|
|
26
|
+
export declare function typePath(rel: string): boolean;
|
|
27
|
+
/** Paths the host keeps for itself. */
|
|
28
|
+
export declare function reservedPath(rel: string): boolean;
|
|
29
|
+
/** A page-relative path, normalized, or null when it is not one. */
|
|
30
|
+
export declare function cleanPath(p: unknown): string | null;
|
|
31
|
+
export interface FileEntry {
|
|
32
|
+
sha256: string;
|
|
33
|
+
size: number;
|
|
34
|
+
contentType: string;
|
|
35
|
+
}
|
|
36
|
+
export interface FileManifest {
|
|
37
|
+
ver: string;
|
|
38
|
+
files: Record<string, FileEntry>;
|
|
39
|
+
}
|
|
40
|
+
/** One write of a publish: content, or a delete; `ifMatch` is the sha256 expected now (null: must not exist). */
|
|
41
|
+
export type FileWrite = {
|
|
42
|
+
data: Buffer;
|
|
43
|
+
contentType?: string;
|
|
44
|
+
ifMatch?: string | null;
|
|
45
|
+
delete?: false;
|
|
46
|
+
} | {
|
|
47
|
+
delete: true;
|
|
48
|
+
ifMatch?: string | null;
|
|
49
|
+
};
|
|
50
|
+
export interface PublishResult {
|
|
51
|
+
version: string;
|
|
52
|
+
changed: {
|
|
53
|
+
path: string;
|
|
54
|
+
sha256: string | null;
|
|
55
|
+
}[];
|
|
56
|
+
shas: Record<string, string>;
|
|
57
|
+
unchanged?: true;
|
|
58
|
+
}
|
|
59
|
+
declare function writeAtomic(file: string, data: Buffer | string): void;
|
|
60
|
+
export declare class FileStore {
|
|
61
|
+
readonly root: string;
|
|
62
|
+
/** rel → the hash of the file at that mtime and size. */
|
|
63
|
+
private readonly cache;
|
|
64
|
+
current: FileManifest | null;
|
|
65
|
+
constructor(root: string);
|
|
66
|
+
private sha;
|
|
67
|
+
/** The current listing. */
|
|
68
|
+
manifest(): FileManifest;
|
|
69
|
+
/** The artifact file a page asks for: an absolute path, or null. */
|
|
70
|
+
resolve(rel: string): string | null;
|
|
71
|
+
/** Writes a batch. Throws {@link FrameError} `conflict` (with `live`, `paths`) when a precondition fails. */
|
|
72
|
+
publish(files: Record<string, FileWrite>): PublishResult;
|
|
73
|
+
}
|
|
74
|
+
export interface BlobMeta {
|
|
75
|
+
id: string;
|
|
76
|
+
contentType: string;
|
|
77
|
+
sizeBytes: number;
|
|
78
|
+
createdAt: string;
|
|
79
|
+
}
|
|
80
|
+
export interface BlobInfo extends BlobMeta {
|
|
81
|
+
url: string;
|
|
82
|
+
}
|
|
83
|
+
export interface BlobList {
|
|
84
|
+
assets: BlobInfo[];
|
|
85
|
+
usage: {
|
|
86
|
+
files: number;
|
|
87
|
+
bytes: number;
|
|
88
|
+
maxFiles: number;
|
|
89
|
+
maxBytes: number;
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/** The most bytes an asset of `type` may have. */
|
|
93
|
+
export declare function blobLimit(type: string): number;
|
|
94
|
+
export declare class BlobStore {
|
|
95
|
+
readonly root: string;
|
|
96
|
+
readonly dir: string;
|
|
97
|
+
constructor(root: string);
|
|
98
|
+
meta(id: string): BlobMeta | null;
|
|
99
|
+
fileOf(id: string): string | null;
|
|
100
|
+
list(): BlobList;
|
|
101
|
+
upload(data: Buffer, contentType: unknown): BlobInfo;
|
|
102
|
+
/** Deletes by id or `/_blob/<id>` url. */
|
|
103
|
+
delete(ref: unknown): {
|
|
104
|
+
deleted: boolean;
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
export { writeAtomic };
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The artifact's files as an original page sees them: everything in the
|
|
3
|
+
* artifact folder except what the host keeps for itself, listed as
|
|
4
|
+
* `_files.json` `{ver, files: {path: {sha256, size, contentType}}}`. `ver`
|
|
5
|
+
* names one state of that list. `publish` writes a batch of files with
|
|
6
|
+
* optional per-file preconditions (`ifMatch`: the sha256 the page last saw, or
|
|
7
|
+
* null for "must not exist") and answers `conflict` when one does not hold.
|
|
8
|
+
* Blobs (the assets capability) are content-addressed files under `_blobs/`.
|
|
9
|
+
*/
|
|
10
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
11
|
+
import { mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, existsSync } from 'node:fs';
|
|
12
|
+
import { basename, dirname, extname, join, sep } from 'node:path';
|
|
13
|
+
export const PUBLISH_MAX_PATHS = 256;
|
|
14
|
+
export const FILE_MAX_BYTES = 16 * 1024 * 1024;
|
|
15
|
+
export const BLOB_MAX_BYTES = 20 * 1024 * 1024;
|
|
16
|
+
export const BLOB_SVG_MAX_BYTES = 2 * 1024 * 1024;
|
|
17
|
+
export const BLOB_CODE_MAX_BYTES = 16 * 1024 * 1024;
|
|
18
|
+
export const BLOBS_MAX_FILES = 2000;
|
|
19
|
+
export const BLOBS_MAX_BYTES = 1024 * 1024 * 1024;
|
|
20
|
+
const WALK_MAX_FILES = 20_000;
|
|
21
|
+
const SHA = /^[0-9a-f]{64}$/;
|
|
22
|
+
const BLOB_ID = /^[0-9a-f]{32}$/;
|
|
23
|
+
export const BLOB_TYPES = new Set([
|
|
24
|
+
'image/png',
|
|
25
|
+
'image/jpeg',
|
|
26
|
+
'image/gif',
|
|
27
|
+
'image/webp',
|
|
28
|
+
'image/svg+xml',
|
|
29
|
+
'video/mp4',
|
|
30
|
+
'video/webm',
|
|
31
|
+
'application/pdf',
|
|
32
|
+
'font/woff2',
|
|
33
|
+
'font/woff',
|
|
34
|
+
'font/ttf',
|
|
35
|
+
'font/otf',
|
|
36
|
+
'text/csv',
|
|
37
|
+
'text/markdown',
|
|
38
|
+
'application/json',
|
|
39
|
+
'text/plain',
|
|
40
|
+
'text/css',
|
|
41
|
+
'text/javascript',
|
|
42
|
+
]);
|
|
43
|
+
const TYPES = {
|
|
44
|
+
'.html': 'text/html; charset=utf-8',
|
|
45
|
+
'.htm': 'text/html; charset=utf-8',
|
|
46
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
47
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
48
|
+
'.css': 'text/css; charset=utf-8',
|
|
49
|
+
'.json': 'application/json; charset=utf-8',
|
|
50
|
+
'.md': 'text/markdown; charset=utf-8',
|
|
51
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
52
|
+
'.csv': 'text/csv; charset=utf-8',
|
|
53
|
+
'.svg': 'image/svg+xml',
|
|
54
|
+
'.png': 'image/png',
|
|
55
|
+
'.jpg': 'image/jpeg',
|
|
56
|
+
'.jpeg': 'image/jpeg',
|
|
57
|
+
'.gif': 'image/gif',
|
|
58
|
+
'.webp': 'image/webp',
|
|
59
|
+
'.avif': 'image/avif',
|
|
60
|
+
'.ico': 'image/x-icon',
|
|
61
|
+
'.woff': 'font/woff',
|
|
62
|
+
'.woff2': 'font/woff2',
|
|
63
|
+
'.ttf': 'font/ttf',
|
|
64
|
+
'.otf': 'font/otf',
|
|
65
|
+
'.mp3': 'audio/mpeg',
|
|
66
|
+
'.wav': 'audio/wav',
|
|
67
|
+
'.ogg': 'audio/ogg',
|
|
68
|
+
'.mp4': 'video/mp4',
|
|
69
|
+
'.webm': 'video/webm',
|
|
70
|
+
'.pdf': 'application/pdf',
|
|
71
|
+
'.wasm': 'application/wasm',
|
|
72
|
+
'.xml': 'application/xml',
|
|
73
|
+
};
|
|
74
|
+
export const contentTypeOf = (file) => TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream';
|
|
75
|
+
export class FrameError extends Error {
|
|
76
|
+
code;
|
|
77
|
+
status;
|
|
78
|
+
extra;
|
|
79
|
+
constructor(code, message, status = 400, extra = {}) {
|
|
80
|
+
super(message);
|
|
81
|
+
this.code = code;
|
|
82
|
+
this.status = status;
|
|
83
|
+
this.extra = extra;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** Paths of the type (never the artifact's): neither listed nor writable by a page. */
|
|
87
|
+
export function typePath(rel) {
|
|
88
|
+
return rel === 'index.html' || rel === 'SKILL.md' || rel === 'artifact-type' || rel.startsWith('artifact-type/');
|
|
89
|
+
}
|
|
90
|
+
/** Paths the host keeps for itself. */
|
|
91
|
+
export function reservedPath(rel) {
|
|
92
|
+
const segs = rel.split('/');
|
|
93
|
+
if (segs.some((s) => s === '' || s === '.' || s === '..' || s.startsWith('.')))
|
|
94
|
+
return true;
|
|
95
|
+
if (segs[0].startsWith('_'))
|
|
96
|
+
return true;
|
|
97
|
+
if (segs[0] === 'db' || segs[0] === 'history' || segs[0] === 'node_modules')
|
|
98
|
+
return true;
|
|
99
|
+
if (rel === 'comments.json' || rel.endsWith('.lock'))
|
|
100
|
+
return true;
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
/** A page-relative path, normalized, or null when it is not one. */
|
|
104
|
+
export function cleanPath(p) {
|
|
105
|
+
if (typeof p !== 'string' || !p || p.length > 1024 || p.includes('\\') || p.includes('\0'))
|
|
106
|
+
return null;
|
|
107
|
+
const rel = p.replace(/^\/+/, '');
|
|
108
|
+
if (!rel || rel.split('/').some((s) => s === '' || s === '.' || s === '..'))
|
|
109
|
+
return null;
|
|
110
|
+
return rel;
|
|
111
|
+
}
|
|
112
|
+
function writeAtomic(file, data) {
|
|
113
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
114
|
+
const tmp = join(dirname(file), `.${basename(file)}.${randomBytes(4).toString('hex')}.tmp`);
|
|
115
|
+
writeFileSync(tmp, data);
|
|
116
|
+
renameSync(tmp, file);
|
|
117
|
+
}
|
|
118
|
+
export class FileStore {
|
|
119
|
+
root;
|
|
120
|
+
/** rel → the hash of the file at that mtime and size. */
|
|
121
|
+
cache = new Map();
|
|
122
|
+
current = null;
|
|
123
|
+
constructor(root) {
|
|
124
|
+
this.root = root;
|
|
125
|
+
}
|
|
126
|
+
sha(rel, st) {
|
|
127
|
+
const have = this.cache.get(rel);
|
|
128
|
+
if (have && have.mtimeMs === st.mtimeMs && have.size === st.size)
|
|
129
|
+
return have.sha256;
|
|
130
|
+
const sha256 = createHash('sha256').update(readFileSync(join(this.root, rel))).digest('hex');
|
|
131
|
+
this.cache.set(rel, { mtimeMs: st.mtimeMs, size: st.size, sha256 });
|
|
132
|
+
return sha256;
|
|
133
|
+
}
|
|
134
|
+
/** The current listing. */
|
|
135
|
+
manifest() {
|
|
136
|
+
const files = {};
|
|
137
|
+
let count = 0;
|
|
138
|
+
const walk = (dir, prefix) => {
|
|
139
|
+
let entries;
|
|
140
|
+
try {
|
|
141
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
for (const e of entries) {
|
|
147
|
+
const rel = prefix ? `${prefix}/${e.name}` : e.name;
|
|
148
|
+
if (reservedPath(rel) || typePath(rel))
|
|
149
|
+
continue;
|
|
150
|
+
if (e.isDirectory())
|
|
151
|
+
walk(join(dir, e.name), rel);
|
|
152
|
+
else if (e.isFile() && ++count <= WALK_MAX_FILES) {
|
|
153
|
+
try {
|
|
154
|
+
const st = statSync(join(dir, e.name));
|
|
155
|
+
files[rel] = { sha256: this.sha(rel, st), size: st.size, contentType: contentTypeOf(rel) };
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
// gone between readdir and stat
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
walk(this.root, '');
|
|
164
|
+
const sorted = Object.fromEntries(Object.keys(files)
|
|
165
|
+
.sort()
|
|
166
|
+
.map((k) => [k, files[k]]));
|
|
167
|
+
const ver = createHash('sha256')
|
|
168
|
+
.update(Object.entries(sorted)
|
|
169
|
+
.map(([k, v]) => `${k}\0${v.sha256}`)
|
|
170
|
+
.join('\n'))
|
|
171
|
+
.digest('hex')
|
|
172
|
+
.slice(0, 12);
|
|
173
|
+
this.current = { ver, files: sorted };
|
|
174
|
+
return this.current;
|
|
175
|
+
}
|
|
176
|
+
/** The artifact file a page asks for: an absolute path, or null. */
|
|
177
|
+
resolve(rel) {
|
|
178
|
+
const clean = cleanPath(rel);
|
|
179
|
+
if (!clean || reservedPath(clean) || typePath(clean))
|
|
180
|
+
return null;
|
|
181
|
+
const file = join(this.root, clean);
|
|
182
|
+
if (!file.startsWith(this.root + sep))
|
|
183
|
+
return null;
|
|
184
|
+
try {
|
|
185
|
+
const real = realpathSync(file);
|
|
186
|
+
const realRoot = realpathSync(this.root);
|
|
187
|
+
if (!real.startsWith(realRoot + sep))
|
|
188
|
+
return null;
|
|
189
|
+
return statSync(real).isFile() ? real : null;
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/** Writes a batch. Throws {@link FrameError} `conflict` (with `live`, `paths`) when a precondition fails. */
|
|
196
|
+
publish(files) {
|
|
197
|
+
const entries = Object.entries(files ?? {});
|
|
198
|
+
if (entries.length === 0) {
|
|
199
|
+
const m = this.manifest();
|
|
200
|
+
return { version: m.ver, changed: [], shas: {}, unchanged: true };
|
|
201
|
+
}
|
|
202
|
+
if (entries.length > PUBLISH_MAX_PATHS)
|
|
203
|
+
throw new FrameError('too_large', `At most ${PUBLISH_MAX_PATHS} paths in one publish.`, 413);
|
|
204
|
+
const plan = [];
|
|
205
|
+
for (const [p, spec] of entries) {
|
|
206
|
+
const rel = cleanPath(p);
|
|
207
|
+
if (!rel)
|
|
208
|
+
throw new FrameError('invalid_content', `${JSON.stringify(p)} is not a file path.`);
|
|
209
|
+
if (typePath(rel))
|
|
210
|
+
throw new FrameError('read_only_path', `${rel} belongs to the type and cannot be written.`, 403);
|
|
211
|
+
if (reservedPath(rel))
|
|
212
|
+
throw new FrameError(rel.startsWith('_') ? 'invalid_content' : 'read_only_path', `${rel} is reserved for the host.`, 403);
|
|
213
|
+
if (spec.ifMatch !== undefined && spec.ifMatch !== null && !SHA.test(spec.ifMatch))
|
|
214
|
+
throw new FrameError('invalid_content', `${rel}: ifMatch is a lowercase sha256 or null.`);
|
|
215
|
+
if (!spec.delete) {
|
|
216
|
+
if (!Buffer.isBuffer(spec.data))
|
|
217
|
+
throw new FrameError('invalid_content', `${rel}: no content.`);
|
|
218
|
+
if (spec.data.length > FILE_MAX_BYTES)
|
|
219
|
+
throw new FrameError('too_large', `${rel} is over ${FILE_MAX_BYTES} bytes.`, 413);
|
|
220
|
+
}
|
|
221
|
+
plan.push({ rel, ...spec });
|
|
222
|
+
}
|
|
223
|
+
const before = this.manifest();
|
|
224
|
+
const conflicts = [];
|
|
225
|
+
for (const w of plan) {
|
|
226
|
+
if (w.ifMatch === undefined)
|
|
227
|
+
continue;
|
|
228
|
+
const actual = before.files[w.rel]?.sha256 ?? null;
|
|
229
|
+
if (actual !== w.ifMatch)
|
|
230
|
+
conflicts.push({ path: w.rel, expected: w.ifMatch, actual });
|
|
231
|
+
}
|
|
232
|
+
if (conflicts.length) {
|
|
233
|
+
throw new FrameError('conflict', 'The files changed since this page read them.', 409, {
|
|
234
|
+
live: before.ver,
|
|
235
|
+
paths: conflicts,
|
|
236
|
+
changed: conflicts.map((c) => c.path),
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
const changed = [];
|
|
240
|
+
const shas = {};
|
|
241
|
+
for (const w of plan) {
|
|
242
|
+
const file = join(this.root, w.rel);
|
|
243
|
+
if (w.delete) {
|
|
244
|
+
if (before.files[w.rel]) {
|
|
245
|
+
rmSync(file, { force: true });
|
|
246
|
+
this.cache.delete(w.rel);
|
|
247
|
+
changed.push({ path: w.rel, sha256: null });
|
|
248
|
+
}
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
const sha256 = createHash('sha256').update(w.data).digest('hex');
|
|
252
|
+
shas[w.rel] = sha256;
|
|
253
|
+
if (before.files[w.rel]?.sha256 === sha256)
|
|
254
|
+
continue;
|
|
255
|
+
writeAtomic(file, w.data);
|
|
256
|
+
changed.push({ path: w.rel, sha256 });
|
|
257
|
+
}
|
|
258
|
+
const after = this.manifest();
|
|
259
|
+
return { version: after.ver, changed, shas, ...(changed.length === 0 ? { unchanged: true } : {}) };
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
/** The most bytes an asset of `type` may have. */
|
|
263
|
+
export function blobLimit(type) {
|
|
264
|
+
if (type === 'image/svg+xml')
|
|
265
|
+
return BLOB_SVG_MAX_BYTES;
|
|
266
|
+
if (type === 'text/css' || type === 'text/javascript')
|
|
267
|
+
return BLOB_CODE_MAX_BYTES;
|
|
268
|
+
return BLOB_MAX_BYTES;
|
|
269
|
+
}
|
|
270
|
+
export class BlobStore {
|
|
271
|
+
root;
|
|
272
|
+
dir;
|
|
273
|
+
constructor(root) {
|
|
274
|
+
this.root = root;
|
|
275
|
+
this.dir = join(root, '_blobs');
|
|
276
|
+
}
|
|
277
|
+
meta(id) {
|
|
278
|
+
if (!BLOB_ID.test(id))
|
|
279
|
+
return null;
|
|
280
|
+
try {
|
|
281
|
+
const m = JSON.parse(readFileSync(join(this.dir, `${id}.json`), 'utf8'));
|
|
282
|
+
return existsSync(join(this.dir, id)) ? { id, ...m } : null;
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
fileOf(id) {
|
|
289
|
+
return this.meta(id) ? join(this.dir, id) : null;
|
|
290
|
+
}
|
|
291
|
+
list() {
|
|
292
|
+
let names = [];
|
|
293
|
+
try {
|
|
294
|
+
names = readdirSync(this.dir);
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
// none yet
|
|
298
|
+
}
|
|
299
|
+
const assets = [];
|
|
300
|
+
for (const n of names) {
|
|
301
|
+
if (!BLOB_ID.test(n))
|
|
302
|
+
continue;
|
|
303
|
+
const m = this.meta(n);
|
|
304
|
+
if (m)
|
|
305
|
+
assets.push({ id: n, url: `/_blob/${n}`, contentType: m.contentType, sizeBytes: m.sizeBytes, createdAt: m.createdAt });
|
|
306
|
+
}
|
|
307
|
+
assets.sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
|
|
308
|
+
const bytes = assets.reduce((s, a) => s + (a.sizeBytes ?? 0), 0);
|
|
309
|
+
return { assets, usage: { files: assets.length, bytes, maxFiles: BLOBS_MAX_FILES, maxBytes: BLOBS_MAX_BYTES } };
|
|
310
|
+
}
|
|
311
|
+
upload(data, contentType) {
|
|
312
|
+
const raw = typeof contentType === 'string' ? contentType.split(';')[0].trim().toLowerCase() : '';
|
|
313
|
+
if (!raw)
|
|
314
|
+
throw new FrameError('invalid_request', 'upload() needs a content type.');
|
|
315
|
+
if (!BLOB_TYPES.has(raw))
|
|
316
|
+
throw new FrameError('unsupported_type', `Assets of type ${raw} are not supported.`);
|
|
317
|
+
if (!data.length)
|
|
318
|
+
throw new FrameError('invalid_request', 'An empty file.');
|
|
319
|
+
const max = blobLimit(raw);
|
|
320
|
+
if (data.length > max)
|
|
321
|
+
throw new FrameError('too_large', `An asset of type ${raw} is at most ${max} bytes.`, 413);
|
|
322
|
+
const id = createHash('sha256').update(data).digest('hex').slice(0, 32);
|
|
323
|
+
if (!this.meta(id)) {
|
|
324
|
+
const { usage } = this.list();
|
|
325
|
+
if (usage.files + 1 > BLOBS_MAX_FILES || usage.bytes + data.length > BLOBS_MAX_BYTES) {
|
|
326
|
+
throw new FrameError('quota_or_state', 'The artifact holds as many assets as it can.', 413);
|
|
327
|
+
}
|
|
328
|
+
mkdirSync(this.dir, { recursive: true });
|
|
329
|
+
writeFileSync(join(this.dir, id), data);
|
|
330
|
+
writeFileSync(join(this.dir, `${id}.json`), `${JSON.stringify({ contentType: raw, sizeBytes: data.length, createdAt: new Date().toISOString() })}\n`);
|
|
331
|
+
}
|
|
332
|
+
const m = this.meta(id);
|
|
333
|
+
return { id, url: `/_blob/${id}`, sizeBytes: m.sizeBytes, contentType: m.contentType, createdAt: m.createdAt };
|
|
334
|
+
}
|
|
335
|
+
/** Deletes by id or `/_blob/<id>` url. */
|
|
336
|
+
delete(ref) {
|
|
337
|
+
const match = /^(?:\/?_blob\/)?([0-9a-f]{32})$/.exec(String(ref ?? '').replace(/^https?:\/\/[^/]+/, ''));
|
|
338
|
+
if (!match)
|
|
339
|
+
throw new FrameError('invalid_request', 'delete() takes an asset id or its /_blob/ url.');
|
|
340
|
+
const id = match[1];
|
|
341
|
+
if (!this.meta(id))
|
|
342
|
+
return { deleted: false };
|
|
343
|
+
rmSync(join(this.dir, id), { force: true });
|
|
344
|
+
rmSync(join(this.dir, `${id}.json`), { force: true });
|
|
345
|
+
return { deleted: true };
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
export { writeAtomic };
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* frame-host: serves an original artifact type (a folder whose index.html
|
|
3
|
+
* declares itself in an inline `// artifact.json` block) so its page runs as
|
|
4
|
+
* it would in its first home.
|
|
5
|
+
*
|
|
6
|
+
* Three windows take part:
|
|
7
|
+
*
|
|
8
|
+
* the outer Shell (the daemon's /a/<id>)
|
|
9
|
+
* └─ embeds ─▶ the inner shell (this server, /f/<token>/, Site.page)
|
|
10
|
+
* └─ embeds ─▶ the original page on its own origin
|
|
11
|
+
* (http://<id>.frame.localhost:<port>/_f/<ver>/, Site.content)
|
|
12
|
+
*
|
|
13
|
+
* The page gets `window.openartifact` from the Frame Runtime this server injects
|
|
14
|
+
* first in its <head> (client/runtime.ts). Every capability call is a
|
|
15
|
+
* `__frame_cap` postMessage to the inner shell (client/shell.ts), which
|
|
16
|
+
* carries it here over HTTP and pushes events (db changes, room, file and
|
|
17
|
+
* comment changes, rewiring) back from one event stream.
|
|
18
|
+
*
|
|
19
|
+
* Backends live in the artifact folder: db/ (db.ts), comments.json
|
|
20
|
+
* (comments.ts), the files the page publishes and _blobs/ (files.ts). An
|
|
21
|
+
* agent's edits land on disk; a watcher sends them to open pages.
|
|
22
|
+
*/
|
|
23
|
+
import { ServerResponse, type IncomingMessage } from 'node:http';
|
|
24
|
+
import type { Duplex } from 'node:stream';
|
|
25
|
+
import type { ServerAction, Site, SiteContext, StreamResponse } from '../serve.ts';
|
|
26
|
+
import { CommentStore } from './comments.ts';
|
|
27
|
+
import { DbStore } from './db.ts';
|
|
28
|
+
import { type Declaration } from './declaration.ts';
|
|
29
|
+
import { BlobStore, FileStore, type PublishResult } from './files.ts';
|
|
30
|
+
import { type CapReply, type FrameSession, type LocalUser } from './wire.ts';
|
|
31
|
+
export { parseDeclaration, readDeclaration, DECLARATION_LINE, type Declaration } from './declaration.ts';
|
|
32
|
+
export { FrameError } from './files.ts';
|
|
33
|
+
export type * from './wire.ts';
|
|
34
|
+
/** The Frame Runtime contract reported to pages. */
|
|
35
|
+
export declare const CONTRACT = "0.2.92";
|
|
36
|
+
/**
|
|
37
|
+
* Where the browser scripts and the shell page are: `$OPEN_ARTIFACT_FRAME_CLIENT_DIR`,
|
|
38
|
+
* else `client/` beside this module (src/frame/client from source, or
|
|
39
|
+
* dist/daemon/frame-host/client beside the bundle).
|
|
40
|
+
*/
|
|
41
|
+
export declare const CLIENT_DIR: string;
|
|
42
|
+
/** What {@link mountFrameSite} takes: serve()'s context, plus the type folder. */
|
|
43
|
+
export interface FrameSiteContext extends SiteContext {
|
|
44
|
+
/** The type folder (default `OPEN_ARTIFACT_TYPE_DIR`, else the working directory). */
|
|
45
|
+
typeDir?: string;
|
|
46
|
+
}
|
|
47
|
+
type Args = Record<string, unknown>;
|
|
48
|
+
/** Mounts one artifact folder. Throws when the type folder carries no declaration or the server has no content hosts. */
|
|
49
|
+
export declare function mountFrameSite(root: string, ctx: FrameSiteContext): Promise<FrameSite>;
|
|
50
|
+
/** One open artifact of an original type. */
|
|
51
|
+
export declare class FrameSite implements Site {
|
|
52
|
+
readonly root: string;
|
|
53
|
+
readonly typeDir: string;
|
|
54
|
+
readonly id: string;
|
|
55
|
+
readonly page: string;
|
|
56
|
+
readonly contentOrigin: string;
|
|
57
|
+
readonly shellOrigin: string;
|
|
58
|
+
readonly db: DbStore;
|
|
59
|
+
readonly comments: CommentStore;
|
|
60
|
+
readonly files: FileStore;
|
|
61
|
+
readonly blobs: BlobStore;
|
|
62
|
+
/** The broker generation: bumped when the type or the files change under an open page. */
|
|
63
|
+
brokerGen: number;
|
|
64
|
+
declaration: Declaration;
|
|
65
|
+
title: string;
|
|
66
|
+
ver: string;
|
|
67
|
+
grants: string[];
|
|
68
|
+
stubs: Record<string, string>;
|
|
69
|
+
readonly me: LocalUser;
|
|
70
|
+
private readonly ctx;
|
|
71
|
+
private readonly shellOrigins;
|
|
72
|
+
private readonly config;
|
|
73
|
+
private flagKeys;
|
|
74
|
+
private typeVer;
|
|
75
|
+
private readonly clients;
|
|
76
|
+
private touchTimer;
|
|
77
|
+
private readonly touchPaths;
|
|
78
|
+
private presenceCache;
|
|
79
|
+
private watchers;
|
|
80
|
+
private watchTimer;
|
|
81
|
+
private typeTimer;
|
|
82
|
+
private readonly pending;
|
|
83
|
+
constructor(root: string, typeDir: string, declaration: Declaration, ctx: FrameSiteContext);
|
|
84
|
+
private applyDeclaration;
|
|
85
|
+
private log;
|
|
86
|
+
close(): void;
|
|
87
|
+
hasBlob(id: string): boolean;
|
|
88
|
+
private watch;
|
|
89
|
+
/** Re-reads the type; when what it serves changed, rewires. */
|
|
90
|
+
typeChanged(): boolean;
|
|
91
|
+
/** A new broker generation: calls stamped with the old one are not run, open shells cut theirs and reload. */
|
|
92
|
+
private rewire;
|
|
93
|
+
/** Applies what the folder watcher gathered (exposed for tests: watchers are slow to settle). */
|
|
94
|
+
flushWatch(): void;
|
|
95
|
+
/** Files changed on disk, not by this page's own publish: a new manifest rewires and reloads open pages. */
|
|
96
|
+
filesChanged(paths?: string[]): boolean;
|
|
97
|
+
private broadcast;
|
|
98
|
+
/** A write from the page: the daemon records it (best effort, gathered). */
|
|
99
|
+
private touched;
|
|
100
|
+
handle(req: IncomingMessage, res: ServerResponse | StreamResponse): Promise<void>;
|
|
101
|
+
/** The inner shell's own requests: from its origin, never from a page elsewhere. */
|
|
102
|
+
private sameOrigin;
|
|
103
|
+
/** Per-capability config, as `__frame_init.capabilities[cap].config` or a grant carries it. */
|
|
104
|
+
private configs;
|
|
105
|
+
session(): FrameSession;
|
|
106
|
+
/** The event stream of one inner shell: JSON objects, over a `baoyu-sse` WebSocket or as SSE. */
|
|
107
|
+
private events;
|
|
108
|
+
private peers;
|
|
109
|
+
gate(cap: string, gen: number | undefined): CapReply | null;
|
|
110
|
+
/** `POST /api/frame/cap`: one call, answered as `{result}` or `{error}`. */
|
|
111
|
+
call(body: Args): Promise<CapReply>;
|
|
112
|
+
private author;
|
|
113
|
+
capability(cap: string, method: string, a: Args, client: string): Promise<unknown>;
|
|
114
|
+
/** The page's publish: its wire form (`{text}` | `{b64}` | null | `{delete:true}`, each with an optional ifMatch). */
|
|
115
|
+
publish(files: Record<string, unknown>, client: string): PublishResult;
|
|
116
|
+
commentsChanged(): void;
|
|
117
|
+
private presence;
|
|
118
|
+
private canSendToAgent;
|
|
119
|
+
private sendToAgent;
|
|
120
|
+
private proposeTitle;
|
|
121
|
+
private askAgent;
|
|
122
|
+
private activity;
|
|
123
|
+
content(req: IncomingMessage, res: ServerResponse): Promise<void>;
|
|
124
|
+
contentUpgrade(_req: IncomingMessage, socket: Duplex): void;
|
|
125
|
+
/** The type's index.html with the Frame Runtime first in its <head>. */
|
|
126
|
+
private sendIndex;
|
|
127
|
+
private sendClientFile;
|
|
128
|
+
/** A browser script: the built `<name>.js`, or, from source, `<name>.ts` with its types stripped. */
|
|
129
|
+
private sendScript;
|
|
130
|
+
private sendBlob;
|
|
131
|
+
private sendFile;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The type's actions (`/__open-artifact/actions/<name>`): `info` for Artifact `call`,
|
|
135
|
+
* and the hidden `open-artifact.db.*` and `open-artifact.comments.*` that ArtifactData and
|
|
136
|
+
* ArtifactComments use, in the shapes `libraryActions` answers.
|
|
137
|
+
*/
|
|
138
|
+
export declare const frameActions: Record<string, ServerAction>;
|