iagenify 0.4.1 → 0.4.3
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 +38 -0
- package/dist/index.cjs +1338 -166
- package/dist/index.js +1338 -166
- package/dist/studio.js +907 -0
- package/package.json +7 -2
package/dist/index.cjs
CHANGED
|
@@ -580,11 +580,15 @@ function createHttpClient({ baseUrl, sessionManager, appName = "", timeout = DEF
|
|
|
580
580
|
async function request(method, path, body, opts = {}) {
|
|
581
581
|
const url = `${baseUrl}${path}`;
|
|
582
582
|
const isFormData = typeof FormData !== "undefined" && body instanceof FormData;
|
|
583
|
+
const isBinary = body instanceof Uint8Array;
|
|
583
584
|
const headers = {
|
|
584
585
|
"X-IaGenify-Version": SDK_VERSION,
|
|
585
|
-
...appName ? { "X-IaGenify-App-Name": appName } : {}
|
|
586
|
+
...appName ? { "X-IaGenify-App-Name": appName } : {},
|
|
587
|
+
...opts.headers || {}
|
|
586
588
|
};
|
|
587
|
-
if (
|
|
589
|
+
if (isBinary) {
|
|
590
|
+
headers["Content-Type"] = "application/octet-stream";
|
|
591
|
+
} else if (!isFormData) {
|
|
588
592
|
headers["Content-Type"] = "application/json";
|
|
589
593
|
}
|
|
590
594
|
if (opts.skipAuth !== true) {
|
|
@@ -604,7 +608,7 @@ function createHttpClient({ baseUrl, sessionManager, appName = "", timeout = DEF
|
|
|
604
608
|
const res = await doFetch(url, {
|
|
605
609
|
method,
|
|
606
610
|
headers,
|
|
607
|
-
body: body !== void 0 ? isFormData ? body : JSON.stringify(body) : void 0
|
|
611
|
+
body: body !== void 0 ? isFormData || isBinary ? body : JSON.stringify(body) : void 0
|
|
608
612
|
}, { timeout: opts.timeout ?? timeout, signal: opts.signal });
|
|
609
613
|
const text2 = await res.text();
|
|
610
614
|
let data;
|
|
@@ -1719,10 +1723,10 @@ function cloudUsageLine(storage, usage) {
|
|
|
1719
1723
|
const u = usage?.[storage?.service];
|
|
1720
1724
|
if (!u) return "";
|
|
1721
1725
|
const mine = storage.limits?.usedBytes || 0;
|
|
1722
|
-
const
|
|
1723
|
-
const plafond =
|
|
1726
|
+
const base2 = (u.storages || []).find((b) => String(b.id) === String(storage.id));
|
|
1727
|
+
const plafond = base2 ? base2.quotaBytes : u.perBaseBytes;
|
|
1724
1728
|
const plan = `(${PLAN_NAMES[usage.pack] || usage.pack} plan)`;
|
|
1725
|
-
const plein =
|
|
1729
|
+
const plein = base2?.overQuota || !base2 && u.overQuota;
|
|
1726
1730
|
if (plafond == null) {
|
|
1727
1731
|
return `${formatBytes(mine)} used, ${SERVICE_NAMES[storage.service]} space ${formatBytes(u.usedBytes)} of ${formatBytes(u.quotaBytes)} ${plan}${u.overQuota ? " \u2014 FULL: writes are refused" : ""}`;
|
|
1728
1732
|
}
|
|
@@ -4173,6 +4177,135 @@ function createServiceTools() {
|
|
|
4173
4177
|
};
|
|
4174
4178
|
}
|
|
4175
4179
|
|
|
4180
|
+
// src/resources/designTools.js
|
|
4181
|
+
var DESIGN_TOOL_NAMES = ["design_read", "design_apply", "design_render", "design_check", "design_template"];
|
|
4182
|
+
var fail5 = (message) => {
|
|
4183
|
+
throw Object.assign(new Error(message), { code: "tool_error" });
|
|
4184
|
+
};
|
|
4185
|
+
var clip3 = (value, max = 48e3) => String(value || "").length > max ? `${String(value).slice(0, max)}
|
|
4186
|
+
\u2026[truncated]` : String(value || "");
|
|
4187
|
+
var projectId = (value) => {
|
|
4188
|
+
const id = String(value || "").trim();
|
|
4189
|
+
if (!id) fail5('"projectId" is required. Use the design project currently open in the editor.');
|
|
4190
|
+
return id;
|
|
4191
|
+
};
|
|
4192
|
+
var parseOperations = (value) => {
|
|
4193
|
+
let operations = value;
|
|
4194
|
+
if (typeof value === "string") {
|
|
4195
|
+
try {
|
|
4196
|
+
operations = JSON.parse(value);
|
|
4197
|
+
} catch (error) {
|
|
4198
|
+
fail5(`"operations" is not valid JSON (${error.message}).`);
|
|
4199
|
+
}
|
|
4200
|
+
}
|
|
4201
|
+
if (!Array.isArray(operations) || operations.length < 1 || operations.length > 100) {
|
|
4202
|
+
fail5('"operations" must be a JSON array with 1 to 100 document operations.');
|
|
4203
|
+
}
|
|
4204
|
+
return operations;
|
|
4205
|
+
};
|
|
4206
|
+
function createDesignTools() {
|
|
4207
|
+
return {
|
|
4208
|
+
design_read: {
|
|
4209
|
+
category: "read",
|
|
4210
|
+
description: "Read the Design document of projectId. Optional node selects one subtree; otherwise return the page/frame tree, tokens, and node ids, names, types, sizes, layout and text. Call before making changes.",
|
|
4211
|
+
parameters: {
|
|
4212
|
+
projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" },
|
|
4213
|
+
node: { type: "string", description: "An existing node id from this document" }
|
|
4214
|
+
},
|
|
4215
|
+
async run({ projectId: id, node: node4 }, { api }) {
|
|
4216
|
+
const project = await api.design.projects.get(projectId(id));
|
|
4217
|
+
const doc = await project.open();
|
|
4218
|
+
const json = doc.toJSON();
|
|
4219
|
+
const describe = (nodeId) => {
|
|
4220
|
+
const item = json.nodes[nodeId];
|
|
4221
|
+
if (!item) return null;
|
|
4222
|
+
return {
|
|
4223
|
+
id: nodeId,
|
|
4224
|
+
type: item.type,
|
|
4225
|
+
name: item.name,
|
|
4226
|
+
size: item.size,
|
|
4227
|
+
position: item.position,
|
|
4228
|
+
text: item.text,
|
|
4229
|
+
style: item.style,
|
|
4230
|
+
layout: item.layout,
|
|
4231
|
+
children: (item.children || []).map(describe)
|
|
4232
|
+
};
|
|
4233
|
+
};
|
|
4234
|
+
if (node4) {
|
|
4235
|
+
const item = json.nodes[node4];
|
|
4236
|
+
if (!item) fail5(`Unknown design node id "${node4}".`);
|
|
4237
|
+
return { output: clip3(JSON.stringify(describe(node4))), summary: `Read ${item.name || node4}`, meta: { projectId: project.id, node: node4 } };
|
|
4238
|
+
}
|
|
4239
|
+
const pages = json.pages.map((page) => ({ id: page.id, name: page.name, frames: page.frames.map(describe) }));
|
|
4240
|
+
return { output: clip3(JSON.stringify({ pages, tokens: json.tokens || {}, version: project.version?.id || null })), summary: `Read ${project.label}`, meta: { projectId: project.id, pages: pages.length } };
|
|
4241
|
+
}
|
|
4242
|
+
},
|
|
4243
|
+
design_apply: {
|
|
4244
|
+
category: "write",
|
|
4245
|
+
description: "Apply an atomic, undoable batch to the saved Design document. operations is JSON text containing 1\u2013100 set/insert/move/remove operations. Use ids from design_read. The project is version-checked; the editor receives the exact operations and new version.",
|
|
4246
|
+
parameters: {
|
|
4247
|
+
projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" },
|
|
4248
|
+
operations: { type: "string", required: true, description: "JSON array of 1\u2013100 valid document operations" }
|
|
4249
|
+
},
|
|
4250
|
+
async run({ projectId: id, operations: raw }, { api }) {
|
|
4251
|
+
const operations = parseOperations(raw);
|
|
4252
|
+
const project = await api.design.projects.get(projectId(id));
|
|
4253
|
+
const doc = await project.open();
|
|
4254
|
+
const applied = doc.apply(operations, { source: "agent" });
|
|
4255
|
+
const saved = await doc.save();
|
|
4256
|
+
return {
|
|
4257
|
+
output: `Applied and saved ${applied.applied} design operation${applied.applied === 1 ? "" : "s"} to ${project.label}. The open editor will receive this exact batch.`,
|
|
4258
|
+
summary: `Updated ${project.label}`,
|
|
4259
|
+
meta: { projectId: project.id, version: saved.version, operations, created: applied.created }
|
|
4260
|
+
};
|
|
4261
|
+
}
|
|
4262
|
+
},
|
|
4263
|
+
design_render: {
|
|
4264
|
+
category: "read",
|
|
4265
|
+
description: "Render one frame of a saved Design project as PNG. The PNG is attached to your context so you can inspect it visually and correct the design.",
|
|
4266
|
+
parameters: {
|
|
4267
|
+
projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" },
|
|
4268
|
+
frame: { type: "string", description: "Frame id from design_read; omit to render the first frame" }
|
|
4269
|
+
},
|
|
4270
|
+
async run({ projectId: id, frame }, { api }) {
|
|
4271
|
+
const project = await api.design.projects.get(projectId(id));
|
|
4272
|
+
const result = await project.render({ frame });
|
|
4273
|
+
if (!result?.image?.data) fail5("The design preview returned no image.");
|
|
4274
|
+
return {
|
|
4275
|
+
output: `Rendered frame ${result.image.frame || frame || "first frame"} at ${result.image.width}\xD7${result.image.height}. Inspect the attached image before changing the design again.`,
|
|
4276
|
+
summary: "Rendered the design for visual review",
|
|
4277
|
+
meta: { projectId: project.id, frame: result.image.frame, width: result.image.width, height: result.image.height },
|
|
4278
|
+
attachments: [{ mime: result.image.mime || "image/png", data: result.image.data }]
|
|
4279
|
+
};
|
|
4280
|
+
}
|
|
4281
|
+
},
|
|
4282
|
+
design_check: {
|
|
4283
|
+
category: "read",
|
|
4284
|
+
description: "Run deterministic design checks on a saved project and report every issue with rule, severity, node and measured details.",
|
|
4285
|
+
parameters: { projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" } },
|
|
4286
|
+
async run({ projectId: id }, { api }) {
|
|
4287
|
+
const project = await api.design.projects.get(projectId(id));
|
|
4288
|
+
const doc = await project.open();
|
|
4289
|
+
const result = doc.check();
|
|
4290
|
+
return { output: clip3(JSON.stringify(result)), summary: `${result.issues.length} design checks reported`, meta: { projectId: project.id, issues: result.issues.length } };
|
|
4291
|
+
}
|
|
4292
|
+
},
|
|
4293
|
+
design_template: {
|
|
4294
|
+
category: "read",
|
|
4295
|
+
description: "List available Design templates, or read one template by id including its starting document.",
|
|
4296
|
+
parameters: { id: { type: "string", description: "Template id; omit to list templates" } },
|
|
4297
|
+
async run({ id }, { api }) {
|
|
4298
|
+
if (!id) {
|
|
4299
|
+
const templates2 = await api.design.templates.list({ type: "design" });
|
|
4300
|
+
return { output: clip3(JSON.stringify(templates2)), summary: `${templates2.length} design templates`, meta: { count: templates2.length } };
|
|
4301
|
+
}
|
|
4302
|
+
const template = await api.design.templates.get(id);
|
|
4303
|
+
return { output: clip3(JSON.stringify(template)), summary: `Read template ${id}`, meta: { template: id } };
|
|
4304
|
+
}
|
|
4305
|
+
}
|
|
4306
|
+
};
|
|
4307
|
+
}
|
|
4308
|
+
|
|
4176
4309
|
// src/resources/workspaceTools.js
|
|
4177
4310
|
var MAX_OUTPUT = 6e4;
|
|
4178
4311
|
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", "__pycache__", ".venv"]);
|
|
@@ -4195,12 +4328,12 @@ var MEDIA_MIME = {
|
|
|
4195
4328
|
};
|
|
4196
4329
|
var EXT_FOR = { markdown: "md", text: "txt", jpeg: "jpg", base64: "txt" };
|
|
4197
4330
|
var ATTACHMENT_MAX = 15 * 1024 * 1024;
|
|
4198
|
-
var
|
|
4331
|
+
var fail6 = (message) => {
|
|
4199
4332
|
throw new IaGenifyError(400, "tool_error", message);
|
|
4200
4333
|
};
|
|
4201
4334
|
var short = (text2 = "", max = 80) => String(text2).length > max ? `${String(text2).slice(0, max)}\u2026` : String(text2);
|
|
4202
4335
|
var filled2 = (value) => typeof value === "string" && value.trim() !== "";
|
|
4203
|
-
var
|
|
4336
|
+
var clip4 = (text2, max = MAX_OUTPUT) => text2.length > max ? `${text2.slice(0, max)}
|
|
4204
4337
|
\u2026[truncated ${text2.length - max} characters]` : text2;
|
|
4205
4338
|
var stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
4206
4339
|
var isTextMime = (mime) => mime.startsWith("text/") || /json|xml|yaml|javascript|typescript/.test(mime);
|
|
@@ -4274,7 +4407,7 @@ async function backup(files, path) {
|
|
|
4274
4407
|
}
|
|
4275
4408
|
async function readText(files, path) {
|
|
4276
4409
|
const file = await files.read(path);
|
|
4277
|
-
if (typeof file.content !== "string")
|
|
4410
|
+
if (typeof file.content !== "string") fail6(`"${path}" is not a text file.`);
|
|
4278
4411
|
return file.content;
|
|
4279
4412
|
}
|
|
4280
4413
|
var countOf = (text2, needle) => needle ? text2.split(needle).length - 1 : 0;
|
|
@@ -4332,11 +4465,11 @@ function storageArgs(args = {}) {
|
|
|
4332
4465
|
try {
|
|
4333
4466
|
parsed = JSON.parse(value);
|
|
4334
4467
|
} catch (err) {
|
|
4335
|
-
|
|
4468
|
+
fail6(`"${name}" is not valid JSON (${err.message}). Send it as JSON text, e.g. ${shape === "array" ? "[{\u2026}]" : "{\u2026}"}.`);
|
|
4336
4469
|
}
|
|
4337
4470
|
}
|
|
4338
4471
|
const isArray = Array.isArray(parsed);
|
|
4339
|
-
if (shape === "array" ? !isArray : isArray || parsed === null || typeof parsed !== "object")
|
|
4472
|
+
if (shape === "array" ? !isArray : isArray || parsed === null || typeof parsed !== "object") fail6(`"${name}" must be a JSON ${shape}.`);
|
|
4340
4473
|
return parsed;
|
|
4341
4474
|
};
|
|
4342
4475
|
return {
|
|
@@ -4349,25 +4482,25 @@ function storageArgs(args = {}) {
|
|
|
4349
4482
|
documents: parse("documents", "array")
|
|
4350
4483
|
};
|
|
4351
4484
|
}
|
|
4352
|
-
var requireText2 = (value, name) => typeof value === "string" && value.trim() ? value.trim() :
|
|
4485
|
+
var requireText2 = (value, name) => typeof value === "string" && value.trim() ? value.trim() : fail6(`"${name}" is required for this action.`);
|
|
4353
4486
|
async function pickStorage(api, name, providers) {
|
|
4354
|
-
if (!providers)
|
|
4487
|
+
if (!providers) fail6("Unknown action for this tool.");
|
|
4355
4488
|
const connected = (await api.storage.list()).filter((s) => s.type === "database" || s.type === "object");
|
|
4356
|
-
if (!connected.length)
|
|
4489
|
+
if (!connected.length) fail6("No database or bucket is connected. Tell the user to connect one in Cloud.");
|
|
4357
4490
|
const describe = (list) => list.map((s) => `"${s.label}" (${storageKindName(s, PROVIDER_NAMES)})`).join(", ");
|
|
4358
4491
|
const byName = name ? connected.find((s) => s.id === name || s.label === name) || connected.find((s) => s.label.toLowerCase() === String(name).trim().toLowerCase()) : null;
|
|
4359
|
-
if (name && !byName)
|
|
4492
|
+
if (name && !byName) fail6(`No connected storage named "${name}". Connected: ${describe(connected)}.`);
|
|
4360
4493
|
const able = connected.filter((s) => providers.includes(engineOf(s)));
|
|
4361
4494
|
const storage = byName || (able.length === 1 ? able[0] : null);
|
|
4362
|
-
if (!storage)
|
|
4363
|
-
if (!providers.includes(engineOf(storage)))
|
|
4495
|
+
if (!storage) fail6(able.length ? `Several storages can do this: set "storage" to one of ${describe(able)}.` : `No connected storage supports this action (it needs ${providers.map((p) => PROVIDER_NAMES[p]).join(" or ")}). Connected: ${describe(connected)}.`);
|
|
4496
|
+
if (!providers.includes(engineOf(storage))) fail6(`"${storage.label}" is ${storageKindName(storage, PROVIDER_NAMES)}; this action needs ${providers.map((p) => PROVIDER_NAMES[p]).join(" or ")}.`);
|
|
4364
4497
|
return storage;
|
|
4365
4498
|
}
|
|
4366
4499
|
function sqlStatement(input) {
|
|
4367
4500
|
const sql = String(input || "").trim().replace(/;\s*$/, "");
|
|
4368
|
-
if (!sql)
|
|
4501
|
+
if (!sql) fail6('"sql" is required for this action.');
|
|
4369
4502
|
const bare = sql.replace(/--[^\n]*/g, " ").replace(/\/\*[\s\S]*?\*\//g, " ").replace(/'(?:[^']|'')*'/g, "''").replace(/"(?:[^"]|"")*"/g, '""');
|
|
4370
|
-
if (bare.includes(";"))
|
|
4503
|
+
if (bare.includes(";")) fail6("Send one SQL statement per call.");
|
|
4371
4504
|
const verb = (bare.match(/^\s*([a-z]+)/i) || [])[1]?.toUpperCase() || "";
|
|
4372
4505
|
const writesInside = /\b(INSERT|UPDATE|DELETE|REPLACE|CREATE|ALTER|DROP)\b/i.test(bare);
|
|
4373
4506
|
const read = ["SELECT", "EXPLAIN"].includes(verb) && !writesInside || verb === "WITH" && !writesInside || verb === "PRAGMA" && !bare.includes("=");
|
|
@@ -4382,28 +4515,28 @@ async function checkStorageWrite(rawArgs = {}, { api, mode } = {}) {
|
|
|
4382
4515
|
const emptyFilter = !args.filter || !Object.keys(args.filter).length;
|
|
4383
4516
|
let statement = null;
|
|
4384
4517
|
if (["insert", "update", "delete"].includes(action)) requireText2(args.collection, "collection");
|
|
4385
|
-
if (action === "insert" && (!Array.isArray(args.documents) || !args.documents.length || args.documents.length > 500))
|
|
4518
|
+
if (action === "insert" && (!Array.isArray(args.documents) || !args.documents.length || args.documents.length > 500)) fail6("insert needs documents: a list of 1 to 500 objects.");
|
|
4386
4519
|
if (action === "update") {
|
|
4387
|
-
if (emptyFilter && args.all !== true)
|
|
4388
|
-
if (!args.update || !Object.keys(args.update).length || !Object.keys(args.update).every((k) => k.startsWith("$")))
|
|
4520
|
+
if (emptyFilter && args.all !== true) fail6("update with an empty filter would change every document. Add a filter, or all: true if that is really what the user wants.");
|
|
4521
|
+
if (!args.update || !Object.keys(args.update).length || !Object.keys(args.update).every((k) => k.startsWith("$"))) fail6('update needs operators such as {"$set":{"field":"value"}}, not a whole document.');
|
|
4389
4522
|
}
|
|
4390
|
-
if (action === "delete" && emptyFilter && args.all !== true)
|
|
4523
|
+
if (action === "delete" && emptyFilter && args.all !== true) fail6("delete with an empty filter would remove every document. Add a filter, or all: true if that is really what the user wants.");
|
|
4391
4524
|
if (action === "sql") {
|
|
4392
4525
|
statement = sqlStatement(args.sql);
|
|
4393
|
-
if (statement.read)
|
|
4394
|
-
if (!statement.write)
|
|
4395
|
-
if (statement.drop && mode?.() !== "full")
|
|
4396
|
-
if (statement.unbounded && args.all !== true)
|
|
4526
|
+
if (statement.read) fail6('This statement only reads: use query_storage with action "sql".');
|
|
4527
|
+
if (!statement.write) fail6(`write_storage runs INSERT, UPDATE, DELETE, REPLACE, CREATE, ALTER or DROP \u2014 not ${statement.verb || "this statement"}.`);
|
|
4528
|
+
if (statement.drop && mode?.() !== "full") fail6("DROP is only allowed in Full access mode. Ask the user to switch mode if they really want to drop it.");
|
|
4529
|
+
if (statement.unbounded && args.all !== true) fail6(`${statement.verb} without WHERE would touch every row. Add a WHERE clause, or all: true if that is really what the user wants.`);
|
|
4397
4530
|
}
|
|
4398
4531
|
if (action === "put") {
|
|
4399
4532
|
requireText2(args.key, "key");
|
|
4400
|
-
if (args.content == null && !args.path)
|
|
4533
|
+
if (args.content == null && !args.path) fail6("put needs content (text) or path (a workspace file).");
|
|
4401
4534
|
}
|
|
4402
4535
|
if (action === "remove") requireText2(args.key, "key");
|
|
4403
4536
|
if (action === "create_collection") requireText2(args.collection, "collection");
|
|
4404
4537
|
if (action === "drop_collection") {
|
|
4405
4538
|
requireText2(args.collection, "collection");
|
|
4406
|
-
if (mode?.() !== "full")
|
|
4539
|
+
if (mode?.() !== "full") fail6("drop_collection removes a collection and every document in it: it is only allowed in Full access mode. Ask the user to switch mode if they really want to drop it.");
|
|
4407
4540
|
}
|
|
4408
4541
|
return { db, statement, args };
|
|
4409
4542
|
}
|
|
@@ -4417,7 +4550,7 @@ function createWorkspaceTools({ client }) {
|
|
|
4417
4550
|
if (typeof text2 !== "string" && attachMime) {
|
|
4418
4551
|
if (file.size > ATTACHMENT_MAX) {
|
|
4419
4552
|
const advice = /^(audio|video)\//.test(attachMime) ? ` Convert it to a lighter form first \u2014 convert { path: "${file.path}", to: "mp3" } keeps the sound and drops the weight.` : " Ask the user for a smaller version.";
|
|
4420
|
-
|
|
4553
|
+
fail6(`"${file.path}" is ${(file.size / 1048576).toFixed(1)} MB; files over ${ATTACHMENT_MAX / 1048576} MB cannot be attached.${advice}`);
|
|
4421
4554
|
}
|
|
4422
4555
|
const kind = attachMime.startsWith("audio/") ? "Listen to it" : attachMime.startsWith("video/") ? "Watch it" : "Read it";
|
|
4423
4556
|
return {
|
|
@@ -4431,7 +4564,7 @@ function createWorkspaceTools({ client }) {
|
|
|
4431
4564
|
if (CONVERTIBLE[ext]) {
|
|
4432
4565
|
const converted = await convert.convert({ from: ext, to: CONVERTIBLE[ext], file: file.content });
|
|
4433
4566
|
text2 = String(converted.content ?? converted.markdown ?? converted.text ?? "");
|
|
4434
|
-
if (!text2)
|
|
4567
|
+
if (!text2) fail6(`Could not extract text from "${path}".`);
|
|
4435
4568
|
} else {
|
|
4436
4569
|
return { output: `"${file.path}" is a binary file (${file.mimeType}, ${file.size} bytes) and has no text to read.`, summary: `${file.path} (binary)`, meta: { path: file.path } };
|
|
4437
4570
|
}
|
|
@@ -4442,7 +4575,7 @@ function createWorkspaceTools({ client }) {
|
|
|
4442
4575
|
const numbered = slice.map((l, i) => `${start + i} ${l.length > 2e3 ? `${l.slice(0, 2e3)}\u2026` : l}`).join("\n");
|
|
4443
4576
|
const more = start - 1 + slice.length < lines.length ? `
|
|
4444
4577
|
\u2026[${lines.length - (start - 1 + slice.length)} more lines \u2014 use offset]` : "";
|
|
4445
|
-
return { output:
|
|
4578
|
+
return { output: clip4(numbered + more) || "(empty file)", summary: `${file.path} \xB7 ${lines.length} lines`, meta: { path: file.path, lines: lines.length } };
|
|
4446
4579
|
}
|
|
4447
4580
|
const search = new SearchResource(client);
|
|
4448
4581
|
const fetchPage = new FetchResource(client);
|
|
@@ -4451,6 +4584,7 @@ function createWorkspaceTools({ client }) {
|
|
|
4451
4584
|
...createPlatformTools(),
|
|
4452
4585
|
// P54 : les services de la plateforme — hébergement, courrier, domaines, compte, documents, second modèle.
|
|
4453
4586
|
...createServiceTools(),
|
|
4587
|
+
...createDesignTools(),
|
|
4454
4588
|
read: {
|
|
4455
4589
|
category: "read",
|
|
4456
4590
|
description: "Read any file in the workspace and SEE it: text and code as numbered lines (use offset/limit for long files); PDFs (including scanned ones), images, audio and video are attached so you read, hear and watch them directly, like a person would; DOCX, PPTX and XLSX are converted to text. This is the only tool you need to understand a document, a recording or a clip \u2014 never write scripts to parse file formats, and never look for a transcription tool: read the file.",
|
|
@@ -4462,8 +4596,8 @@ function createWorkspaceTools({ client }) {
|
|
|
4462
4596
|
},
|
|
4463
4597
|
async run({ path, paths, offset = 1, limit = 2e3 }, context) {
|
|
4464
4598
|
const liste = Array.isArray(paths) && paths.length ? paths.map((p) => String(p)) : [String(path ?? "")];
|
|
4465
|
-
if (!filled2(liste[0]))
|
|
4466
|
-
if (liste.length > 20)
|
|
4599
|
+
if (!filled2(liste[0])) fail6('Give "path" (one file) or "paths" (several).');
|
|
4600
|
+
if (liste.length > 20) fail6(`A single call reads at most 20 files (got ${liste.length}).`);
|
|
4467
4601
|
if (liste.length === 1) return lireFichier(liste[0], { offset, limit }, context);
|
|
4468
4602
|
const lus = [];
|
|
4469
4603
|
const pieces2 = [];
|
|
@@ -4479,7 +4613,7 @@ Error: ${err.message}`);
|
|
|
4479
4613
|
}
|
|
4480
4614
|
}
|
|
4481
4615
|
return {
|
|
4482
|
-
output:
|
|
4616
|
+
output: clip4(lus.join("\n\n"), 6e4),
|
|
4483
4617
|
summary: `${liste.length} files`,
|
|
4484
4618
|
meta: { paths: liste, attached: pieces2.length || void 0 },
|
|
4485
4619
|
...pieces2.length ? { attachments: pieces2 } : {}
|
|
@@ -4516,7 +4650,7 @@ Error: ${err.message}`);
|
|
|
4516
4650
|
try {
|
|
4517
4651
|
re = new RegExp(pattern, ignore_case ? "i" : "");
|
|
4518
4652
|
} catch (err) {
|
|
4519
|
-
|
|
4653
|
+
fail6(`Invalid regular expression: ${err.message}`);
|
|
4520
4654
|
}
|
|
4521
4655
|
const only = glob ? globToRegExp(glob) : null;
|
|
4522
4656
|
const hits = [];
|
|
@@ -4550,8 +4684,8 @@ Error: ${err.message}`);
|
|
|
4550
4684
|
async run({ path, old_string, new_string, replace_all = false }, { files }) {
|
|
4551
4685
|
const before = await readText(files, path);
|
|
4552
4686
|
const count = countOf(before, old_string);
|
|
4553
|
-
if (!count)
|
|
4554
|
-
if (count > 1 && !replace_all)
|
|
4687
|
+
if (!count) fail6(`old_string was not found in "${path}". Read the file and copy the text exactly.`);
|
|
4688
|
+
if (count > 1 && !replace_all) fail6(`old_string appears ${count} times in "${path}". Add surrounding lines to make it unique, or set replace_all.`);
|
|
4555
4689
|
const after = replace_all ? before.split(old_string).join(new_string) : before.replace(old_string, () => new_string);
|
|
4556
4690
|
await backup(files, path);
|
|
4557
4691
|
await files.write(path, after);
|
|
@@ -4575,8 +4709,8 @@ Error: ${err.message}`);
|
|
|
4575
4709
|
const diffs = [];
|
|
4576
4710
|
edits.forEach((e, i) => {
|
|
4577
4711
|
const count = countOf(text2, e.old_string);
|
|
4578
|
-
if (!count)
|
|
4579
|
-
if (count > 1 && !e.replace_all)
|
|
4712
|
+
if (!count) fail6(`Edit ${i + 1}: old_string not found in "${path}". Nothing was changed.`);
|
|
4713
|
+
if (count > 1 && !e.replace_all) fail6(`Edit ${i + 1}: old_string appears ${count} times. Nothing was changed.`);
|
|
4580
4714
|
diffs.push(diffOf(text2, e.old_string, e.new_string));
|
|
4581
4715
|
text2 = e.replace_all ? text2.split(e.old_string).join(e.new_string) : text2.replace(e.old_string, () => e.new_string);
|
|
4582
4716
|
});
|
|
@@ -4620,17 +4754,17 @@ Error: ${err.message}`);
|
|
|
4620
4754
|
// Refusé avant toute permission, en disant comment faire.
|
|
4621
4755
|
check({ command = "", commands, background } = {}, { shell, terminals } = {}) {
|
|
4622
4756
|
if (commands !== void 0) {
|
|
4623
|
-
if (!Array.isArray(commands) || !commands.length)
|
|
4624
|
-
if (commands.some((c) => typeof c !== "string" || !c.trim()))
|
|
4625
|
-
if (commands.length > 20)
|
|
4626
|
-
if (background === true)
|
|
4757
|
+
if (!Array.isArray(commands) || !commands.length) fail6('"commands" must be a list of shell commands, e.g. ["npm ci", "npm run build"].');
|
|
4758
|
+
if (commands.some((c) => typeof c !== "string" || !c.trim())) fail6('Every entry of "commands" must be a non-empty command.');
|
|
4759
|
+
if (commands.length > 20) fail6(`A single call runs at most 20 commands (got ${commands.length}).`);
|
|
4760
|
+
if (background === true) fail6("background: true runs ONE command in a terminal. Use command, not commands \u2014 or run the sequence without background.");
|
|
4627
4761
|
} else if (!filled2(command)) {
|
|
4628
|
-
|
|
4762
|
+
fail6('Give "command" (one command) or "commands" (several, run in order).');
|
|
4629
4763
|
}
|
|
4630
4764
|
if (background === true || !terminals) return;
|
|
4631
4765
|
const text2 = [command, ...Array.isArray(commands) ? commands : []].filter(Boolean).join("\n");
|
|
4632
4766
|
if (DETACHED.test(text2) && RUNTIME.test(text2)) {
|
|
4633
|
-
|
|
4767
|
+
fail6(`Do not detach servers or dev tools (Start-Process, Start-Job, nohup, setsid, a trailing &): they would run hidden, outside the user's terminals, where nobody can see or stop them. Run the command itself with background: true \u2014 e.g. bash { command: "cd my-app; npm run dev -- --port 5173", background: true } \u2014 then read it with terminal { action: "output" } and stop it with terminal { action: "kill" }.`);
|
|
4634
4768
|
}
|
|
4635
4769
|
},
|
|
4636
4770
|
async run({ command, commands, timeout_ms = 12e4, background = false, stop_on_error = true, port = null }, { root, signal, shell, terminals }) {
|
|
@@ -4639,7 +4773,7 @@ Error: ${err.message}`);
|
|
|
4639
4773
|
const seule = liste[0];
|
|
4640
4774
|
const auto = background !== true && Boolean(terminals) && liste.length === 1 && LONG_RUNNING.test(seule);
|
|
4641
4775
|
if (background === true || auto) {
|
|
4642
|
-
if (!terminals)
|
|
4776
|
+
if (!terminals) fail6("Background commands need a terminal environment, and there are none here. Run the command without background.");
|
|
4643
4777
|
const note = auto ? "This command starts a server that never exits, so it runs in a terminal instead of blocking.\n" : "";
|
|
4644
4778
|
const terminal = await terminals.create({ name: short(seule, 60), command: seule, by: "agent", ...port ? { port } : {} });
|
|
4645
4779
|
const first = await settle(terminal, signal);
|
|
@@ -4648,9 +4782,9 @@ Error: ${err.message}`);
|
|
|
4648
4782
|
const exited = first.status === "exited";
|
|
4649
4783
|
const output = exited ? `Terminal ${terminal.id} (${seule}) exited with code ${first.exitCode} right away.
|
|
4650
4784
|
--- output ---
|
|
4651
|
-
${
|
|
4785
|
+
${clip4(text2, 2e4)}` : `Started terminal ${terminal.id} (${seule}). It keeps running after your answer; use terminal { action: "output", id: "${terminal.id}" } to check it and terminal { action: "kill" } to stop it.
|
|
4652
4786
|
--- first output ---
|
|
4653
|
-
${
|
|
4787
|
+
${clip4(text2, 2e4) || "(nothing yet)"}`;
|
|
4654
4788
|
const adresse = terminal.url ? `
|
|
4655
4789
|
|
|
4656
4790
|
Open it at: ${terminal.url}
|
|
@@ -4658,7 +4792,7 @@ If it does not answer, the server is listening on localhost instead of 0.0.0.0 \
|
|
|
4658
4792
|
return {
|
|
4659
4793
|
output: note + output + adresse,
|
|
4660
4794
|
summary: `${seule.slice(0, 80)} \xB7 ${exited ? `exit ${first.exitCode}` : terminal.url || `terminal ${terminal.id}`}`,
|
|
4661
|
-
meta: { command: seule, background: true, terminalId: terminal.id, status: first.status, exitCode: first.exitCode, stdout:
|
|
4795
|
+
meta: { command: seule, background: true, terminalId: terminal.id, status: first.status, exitCode: first.exitCode, stdout: clip4(text2, 4e3), url: terminal.url ?? null, port: terminal.port ?? null }
|
|
4662
4796
|
};
|
|
4663
4797
|
}
|
|
4664
4798
|
const executer = async (cmd) => {
|
|
@@ -4710,9 +4844,9 @@ If it does not answer, the server is listening on localhost instead of 0.0.0.0 \
|
|
|
4710
4844
|
if (liste.length === 1) {
|
|
4711
4845
|
const r = await executer(seule);
|
|
4712
4846
|
const output = [`exit code ${etat(r)}`, r.stdout && `--- stdout ---
|
|
4713
|
-
${
|
|
4714
|
-
${
|
|
4715
|
-
return { output, summary: `${seule.slice(0, 80)} \xB7 exit ${etat(r)}`, meta: { command: seule, exitCode: r.code, timedOut: r.timedOut, stdout:
|
|
4847
|
+
${clip4(r.stdout, 3e4)}`, r.stderr && `--- stderr ---
|
|
4848
|
+
${clip4(r.stderr, 3e4)}`].filter(Boolean).join("\n");
|
|
4849
|
+
return { output, summary: `${seule.slice(0, 80)} \xB7 exit ${etat(r)}`, meta: { command: seule, exitCode: r.code, timedOut: r.timedOut, stdout: clip4(r.stdout, 4e3), stderr: clip4(r.stderr, 4e3) } };
|
|
4716
4850
|
}
|
|
4717
4851
|
const faits = [];
|
|
4718
4852
|
for (const cmd of liste) {
|
|
@@ -4725,9 +4859,9 @@ ${clip3(r.stderr, 3e4)}`].filter(Boolean).join("\n");
|
|
|
4725
4859
|
const bloc = faits.map((r, i) => [
|
|
4726
4860
|
`[${i + 1}/${liste.length}] ${r.cmd} \u2014 exit ${etat(r)}`,
|
|
4727
4861
|
r.stdout && `--- stdout ---
|
|
4728
|
-
${
|
|
4862
|
+
${clip4(r.stdout, part)}`,
|
|
4729
4863
|
r.stderr && `--- stderr ---
|
|
4730
|
-
${
|
|
4864
|
+
${clip4(r.stderr, part)}`
|
|
4731
4865
|
].filter(Boolean).join("\n")).join("\n\n");
|
|
4732
4866
|
const dernier = faits.at(-1);
|
|
4733
4867
|
const rates = faits.filter((r) => r.timedOut || r.code !== 0).length;
|
|
@@ -4743,8 +4877,8 @@ Stopped at command ${faits.length} of ${liste.length}: the rest was not run.` :
|
|
|
4743
4877
|
exitCode: dernier ? dernier.code : null,
|
|
4744
4878
|
timedOut: Boolean(dernier?.timedOut),
|
|
4745
4879
|
results: faits.map((r) => ({ command: r.cmd, exitCode: r.code, timedOut: r.timedOut })),
|
|
4746
|
-
stdout:
|
|
4747
|
-
stderr:
|
|
4880
|
+
stdout: clip4(faits.map((r) => r.stdout).filter(Boolean).join("\n"), 4e3),
|
|
4881
|
+
stderr: clip4(faits.map((r) => r.stderr).filter(Boolean).join("\n"), 4e3)
|
|
4748
4882
|
}
|
|
4749
4883
|
};
|
|
4750
4884
|
}
|
|
@@ -4761,14 +4895,14 @@ Stopped at command ${faits.length} of ${liste.length}: the rest was not run.` :
|
|
|
4761
4895
|
since: { type: "integer", description: "output: read from this position; 0 = everything kept" }
|
|
4762
4896
|
},
|
|
4763
4897
|
async run({ action, id, since }, { terminals }) {
|
|
4764
|
-
if (!terminals)
|
|
4898
|
+
if (!terminals) fail6("There are no terminals here: they only exist on a computer.");
|
|
4765
4899
|
if (action === "list") {
|
|
4766
4900
|
const all = await terminals.list();
|
|
4767
4901
|
if (!all.length) return { output: "No terminals are open.", summary: "No terminals", meta: { terminals: [] } };
|
|
4768
4902
|
const lines = all.map((t) => `${t.id} \xB7 ${t.status}${t.status === "exited" ? ` (code ${t.exitCode ?? "stopped"})` : ""} \xB7 ${t.command || t.name} \xB7 cwd ${t.cwd || "."} \xB7 by ${t.by} \xB7 started ${t.startedAt}`);
|
|
4769
4903
|
return { output: lines.join("\n"), summary: `${all.filter((t) => t.status === "running").length} running \xB7 ${all.length} terminals`, meta: { terminals: all } };
|
|
4770
4904
|
}
|
|
4771
|
-
if (!id)
|
|
4905
|
+
if (!id) fail6(`"id" is required for ${action}. Use terminal { action: "list" } to find it.`);
|
|
4772
4906
|
const terminal = await terminals.get(id);
|
|
4773
4907
|
if (action === "output") {
|
|
4774
4908
|
const from = since != null ? Number(since) : terminal.agentCursor || 0;
|
|
@@ -4778,16 +4912,16 @@ Stopped at command ${faits.length} of ${liste.length}: the rest was not run.` :
|
|
|
4778
4912
|
return {
|
|
4779
4913
|
output: `${terminal.id} \xB7 ${out.status}${out.status === "exited" ? ` (code ${out.exitCode ?? "stopped"})` : ""}${out.truncated ? " \xB7 older output was dropped" : ""}
|
|
4780
4914
|
--- output ---
|
|
4781
|
-
${
|
|
4915
|
+
${clip4(text2, 3e4) || "(no new output)"}`,
|
|
4782
4916
|
summary: `${terminal.name} \xB7 ${out.status}`,
|
|
4783
|
-
meta: { terminalId: terminal.id, status: out.status, exitCode: out.exitCode, stdout:
|
|
4917
|
+
meta: { terminalId: terminal.id, status: out.status, exitCode: out.exitCode, stdout: clip4(text2, 4e3) }
|
|
4784
4918
|
};
|
|
4785
4919
|
}
|
|
4786
4920
|
if (action === "kill") {
|
|
4787
4921
|
const stopped = await terminal.kill();
|
|
4788
4922
|
return { output: `Stopped terminal ${stopped.id} (${stopped.command || stopped.name}).`, summary: `Stopped ${stopped.name}`, meta: { terminalId: stopped.id, status: stopped.status } };
|
|
4789
4923
|
}
|
|
4790
|
-
|
|
4924
|
+
fail6(`Unknown action "${action}": use list, output or kill.`);
|
|
4791
4925
|
}
|
|
4792
4926
|
},
|
|
4793
4927
|
ask_user: {
|
|
@@ -4860,7 +4994,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
4860
4994
|
const shot = r.screenshot?.base64 ? { mime: r.screenshot.mimeType || "image/jpeg", data: r.screenshot.base64 } : null;
|
|
4861
4995
|
if (screenshot === true && !shot) sections.push("--- screenshot ---\n(the page could not be captured as an image)");
|
|
4862
4996
|
return {
|
|
4863
|
-
output:
|
|
4997
|
+
output: clip4(sections.filter(Boolean).join("\n\n"), 3e4),
|
|
4864
4998
|
summary: `${r.title || url}${shot ? " \xB7 seen" : ""}`,
|
|
4865
4999
|
meta: { url: r.url || url, title: r.title || "", credits: r.creditsUsed ?? 1, ...shot ? { screenshot: true } : {}, ...wants.has("console") ? { consoleErrors: (r.console || []).filter((l) => l.level === "error").length } : {} },
|
|
4866
5000
|
...shot ? { attachments: [shot] } : {}
|
|
@@ -4879,12 +5013,12 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
4879
5013
|
},
|
|
4880
5014
|
async run({ path, url, to, save }, { files }) {
|
|
4881
5015
|
const target = String(to || "").trim().toLowerCase();
|
|
4882
|
-
if (!target)
|
|
4883
|
-
if (!filled2(path) && !filled2(url))
|
|
4884
|
-
if (filled2(path) && filled2(url))
|
|
5016
|
+
if (!target) fail6('"to" is required: the format to convert into, e.g. "pdf".');
|
|
5017
|
+
if (!filled2(path) && !filled2(url)) fail6('Give "path" (a workspace file) or "url".');
|
|
5018
|
+
if (filled2(path) && filled2(url)) fail6('Give "path" or "url", not both.');
|
|
4885
5019
|
const sourceName = filled2(path) ? String(path) : new URL(String(url)).pathname.split("/").filter(Boolean).pop() || "page";
|
|
4886
5020
|
const from = sourceName.includes(".") ? sourceName.split(".").pop().toLowerCase() : "";
|
|
4887
|
-
if (!from)
|
|
5021
|
+
if (!from) fail6(`Cannot tell the format of "${sourceName}": the name has no extension.`);
|
|
4888
5022
|
let result;
|
|
4889
5023
|
if (filled2(path)) {
|
|
4890
5024
|
const file = await files.read(path);
|
|
@@ -4893,11 +5027,11 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
4893
5027
|
} else {
|
|
4894
5028
|
result = await convert.convert({ from, to: target, url: String(url) });
|
|
4895
5029
|
}
|
|
4896
|
-
if (!result?.ok)
|
|
5030
|
+
if (!result?.ok) fail6(result?.message || `Conversion ${from} \u2192 ${target} failed.`);
|
|
4897
5031
|
const data = result.content !== void 0 ? String(result.content) : Buffer.from(result.base64 || "", "base64");
|
|
4898
5032
|
const ext = EXT_FOR[target] || target;
|
|
4899
|
-
const
|
|
4900
|
-
const destination = filled2(save) ? String(save) : filled2(path) ? `${
|
|
5033
|
+
const base2 = sourceName.replace(/\.[^.]+$/, "");
|
|
5034
|
+
const destination = filled2(save) ? String(save) : filled2(path) ? `${base2}.${ext}` : `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${base2}.${ext}`;
|
|
4901
5035
|
const written = await files.write(destination, data);
|
|
4902
5036
|
return {
|
|
4903
5037
|
output: `Converted ${sourceName} (${from} \u2192 ${target}) to ${written.path} \u2014 ${Math.round(written.size / 1024)} KB, ${result.creditsUsed ?? 1} credit.`,
|
|
@@ -4974,7 +5108,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
4974
5108
|
const usage = await api.cloud.usage();
|
|
4975
5109
|
if (!args.storage) return { output: cloudUsageReport(usage), summary: "IaGenify Cloud \xB7 usage", meta: { action, storage: null } };
|
|
4976
5110
|
const target2 = await pickStorage(api, args.storage, STORAGE_READS.usage);
|
|
4977
|
-
if (!target2.service)
|
|
5111
|
+
if (!target2.service) fail6(`"${target2.label}" is a connected storage: its space is managed by its own provider. usage only reports IaGenify Cloud storages.`);
|
|
4978
5112
|
return { output: cloudUsageReport(usage, target2), summary: `${target2.label} \xB7 usage`, meta: { storage: target2.label, provider: target2.provider, action } };
|
|
4979
5113
|
}
|
|
4980
5114
|
const db = await pickStorage(api, args.storage, STORAGE_READS[action]);
|
|
@@ -4982,7 +5116,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
4982
5116
|
if (action === "overview") {
|
|
4983
5117
|
const seen = await db.run({ action: "overview" });
|
|
4984
5118
|
return {
|
|
4985
|
-
output:
|
|
5119
|
+
output: clip4(overviewReport(db, seen), 3e4),
|
|
4986
5120
|
summary: `${db.label} \xB7 overview`,
|
|
4987
5121
|
meta: { storage: db.label, provider: db.provider, action, returned: (seen.collections || seen.tables || seen.folders || []).length }
|
|
4988
5122
|
};
|
|
@@ -4998,13 +5132,13 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
4998
5132
|
});
|
|
4999
5133
|
} else if (action === "count") result = await db.run({ action: "count", collection: requireText2(args.collection, "collection"), filter: args.filter || {} });
|
|
5000
5134
|
else if (action === "aggregate") {
|
|
5001
|
-
if (!Array.isArray(args.pipeline) || !args.pipeline.length)
|
|
5002
|
-
if (/"\$(out|merge)"/.test(JSON.stringify(args.pipeline)))
|
|
5135
|
+
if (!Array.isArray(args.pipeline) || !args.pipeline.length) fail6('aggregate needs a pipeline: a list of stages such as [{"$group":{"_id":"$model","total":{"$sum":"$credits"}}}].');
|
|
5136
|
+
if (/"\$(out|merge)"/.test(JSON.stringify(args.pipeline))) fail6("aggregate is read-only: $out and $merge are not allowed.");
|
|
5003
5137
|
result = await db.run({ action: "aggregate", collection: requireText2(args.collection, "collection"), pipeline: args.pipeline });
|
|
5004
5138
|
} else if (action === "tables") result = await db.run({ action: "tables" });
|
|
5005
5139
|
else if (action === "sql") {
|
|
5006
5140
|
const statement = sqlStatement(args.sql);
|
|
5007
|
-
if (!statement.read)
|
|
5141
|
+
if (!statement.read) fail6(`query_storage only runs SELECT, WITH, PRAGMA or EXPLAIN. To change data (${statement.verb || "this statement"}), use write_storage with action "sql".`);
|
|
5008
5142
|
result = await db.run({ sql: statement.sql, params: Array.isArray(args.params) ? args.params : [] });
|
|
5009
5143
|
} else if (action === "objects") result = await db.run({ action: "list", prefix: String(args.prefix || "") });
|
|
5010
5144
|
else if (action === "object") result = await db.run({ action: "object", key: requireText2(args.key, "key") });
|
|
@@ -5019,7 +5153,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
5019
5153
|
};
|
|
5020
5154
|
}
|
|
5021
5155
|
return {
|
|
5022
|
-
output:
|
|
5156
|
+
output: clip4(results.map((r, i) => `[${i + 1}] ${r.source?.name || "document"} \xB7 ${r.score}
|
|
5023
5157
|
${r.text}`).join("\n\n"), 3e4),
|
|
5024
5158
|
summary: `${db.label} \xB7 ${results.length} extract${results.length === 1 ? "" : "s"}`,
|
|
5025
5159
|
meta: { storage: db.label, provider: db.provider, action, credits: found.creditsUsed ?? 1, returned: results.length, scanned: found.scanned ?? null, sources: [...new Set(results.map((r) => r.source?.name).filter(Boolean))] }
|
|
@@ -5073,7 +5207,7 @@ ${r.text}`).join("\n\n"), 3e4),
|
|
|
5073
5207
|
else if (action === "drop_collection") result = await db.run({ action: "dropCollection", collection: args.collection.trim() });
|
|
5074
5208
|
const target = args.collection || args.key || (args.sql ? String(args.sql).trim().split(/\s+/).slice(0, 3).join(" ") : "");
|
|
5075
5209
|
return {
|
|
5076
|
-
output:
|
|
5210
|
+
output: clip4(JSON.stringify(result, null, 1), 3e4),
|
|
5077
5211
|
summary: `${db.label} \xB7 ${action}${target ? ` ${target}` : ""}`,
|
|
5078
5212
|
meta: { storage: db.label, provider: db.provider, action, collection: args.collection || null, result }
|
|
5079
5213
|
};
|
|
@@ -5144,28 +5278,28 @@ var MEDIA = {
|
|
|
5144
5278
|
// produire doit se dire tout de suite, pas revenir en erreur du fournisseur une fois payé.
|
|
5145
5279
|
verify: (a, model) => {
|
|
5146
5280
|
if (OMNI_MODELS.includes(model)) {
|
|
5147
|
-
if (a.audio === true)
|
|
5281
|
+
if (a.audio === true) fail6(`"${model}" has no sound option. Use veo-3.1 for sound.`);
|
|
5148
5282
|
if (a.duration !== void 0 && a.duration !== null && a.duration !== "") {
|
|
5149
5283
|
const d = Number(a.duration);
|
|
5150
5284
|
if (!Number.isFinite(d) || d < OMNI_SECONDS.min || d > OMNI_SECONDS.max) {
|
|
5151
|
-
|
|
5285
|
+
fail6(`"${model}" makes videos of ${OMNI_SECONDS.min} to ${OMNI_SECONDS.max} seconds (the provider's limit); you asked for ${a.duration}.`);
|
|
5152
5286
|
}
|
|
5153
5287
|
}
|
|
5154
5288
|
const permises = VIDEO_RESOLUTIONS[model] || [];
|
|
5155
5289
|
if (filled2(a.resolution) && !permises.includes(a.resolution)) {
|
|
5156
|
-
|
|
5290
|
+
fail6(`"${model}" has no ${a.resolution}. It does ${permises.join(", ")}.`);
|
|
5157
5291
|
}
|
|
5158
5292
|
return;
|
|
5159
5293
|
}
|
|
5160
5294
|
if (a.audio === true && !VIDEO_WITH_AUDIO.includes(model)) {
|
|
5161
|
-
|
|
5295
|
+
fail6(`"${model}" makes no sound. Only ${VIDEO_WITH_AUDIO.join(", ")} does \u2014 pass model: "veo-3.1", or leave audio out.`);
|
|
5162
5296
|
}
|
|
5163
5297
|
if (a.duration !== void 0 && a.duration !== null && !VIDEO_DURATIONS.includes(Number(a.duration))) {
|
|
5164
|
-
|
|
5298
|
+
fail6(`duration must be ${VIDEO_DURATIONS.join(", ")} seconds; you asked for ${a.duration}.`);
|
|
5165
5299
|
}
|
|
5166
5300
|
const allowed = VIDEO_RESOLUTIONS[model] || [];
|
|
5167
5301
|
if (filled2(a.resolution) && !allowed.includes(a.resolution)) {
|
|
5168
|
-
|
|
5302
|
+
fail6(`"${model}" has no ${a.resolution}. It does ${allowed.join(", ")} \u2014 change the resolution, or pick another model.`);
|
|
5169
5303
|
}
|
|
5170
5304
|
},
|
|
5171
5305
|
// Omni : seulement ce qui a été demandé — sans durée, le modèle fait ses 10 s par défaut, et un
|
|
@@ -5254,7 +5388,7 @@ function createMediaTools({ client, media = {} }) {
|
|
|
5254
5388
|
const args = fusionner(spec, media[MEDIA_KINDS[name]] || {}, brut);
|
|
5255
5389
|
const model = filled2(args.model) ? args.model : spec.model;
|
|
5256
5390
|
if (!spec.models.includes(model)) {
|
|
5257
|
-
|
|
5391
|
+
fail6(`${name} has no model "${args.model}". Available: ${spec.models.join(", ")}.`);
|
|
5258
5392
|
}
|
|
5259
5393
|
if (spec.verify) spec.verify(args, model);
|
|
5260
5394
|
},
|
|
@@ -5266,15 +5400,15 @@ function createMediaTools({ client, media = {} }) {
|
|
|
5266
5400
|
if (spec.from && filled2(image)) {
|
|
5267
5401
|
const source = await files.read(String(image));
|
|
5268
5402
|
const mime = /^image\//.test(source.mimeType || "") ? source.mimeType : mimeOf(String(image));
|
|
5269
|
-
if (!mime || !mime.startsWith("image/"))
|
|
5270
|
-
if (source.size > ATTACHMENT_MAX)
|
|
5403
|
+
if (!mime || !mime.startsWith("image/")) fail6(`"${source.path}" is not an image (${source.mimeType || "unknown type"}).`);
|
|
5404
|
+
if (source.size > ATTACHMENT_MAX) fail6(`"${source.path}" is ${(source.size / 1048576).toFixed(1)} MB; the starting image must be under ${ATTACHMENT_MAX / 1048576} MB.`);
|
|
5271
5405
|
inputs.push({ type: "image", content: Buffer.from(source.content).toString("base64"), mime });
|
|
5272
5406
|
}
|
|
5273
5407
|
const session = await models.create({ model, settings: spec.settings(args, model), memory: false });
|
|
5274
5408
|
try {
|
|
5275
5409
|
const result = await session.generate({ inputs, outputs: [{ type: spec.output }] });
|
|
5276
5410
|
const output = result.outputs?.find((o) => o.content);
|
|
5277
|
-
if (!output)
|
|
5411
|
+
if (!output) fail6(`The ${spec.type} model returned nothing.`);
|
|
5278
5412
|
const ext = output.mime?.split("/")[1]?.split(";")[0]?.replace("mpeg", "mp3") || spec.ext;
|
|
5279
5413
|
const target = path || `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${Date.now()}.${ext}`;
|
|
5280
5414
|
const item = await files.write(target, Buffer.from(output.content, "base64"));
|
|
@@ -5291,10 +5425,10 @@ function createMediaTools({ client, media = {} }) {
|
|
|
5291
5425
|
}
|
|
5292
5426
|
}]));
|
|
5293
5427
|
}
|
|
5294
|
-
var WORKSPACE_TOOL_NAMES = ["read", "list", "glob", "grep", "write", "edit", "multi_edit", "move", "delete", "bash", "terminal", "todo_write", "ask_user", "search", "fetch", "convert", "account", "query_storage", "write_storage", "memory", "recall", ...PLATFORM_TOOL_NAMES, ...SERVICE_TOOL_NAMES, ...Object.keys(MEDIA)];
|
|
5428
|
+
var WORKSPACE_TOOL_NAMES = ["read", "list", "glob", "grep", "write", "edit", "multi_edit", "move", "delete", "bash", "terminal", "todo_write", "ask_user", "search", "fetch", "convert", "account", "query_storage", "write_storage", "memory", "recall", ...PLATFORM_TOOL_NAMES, ...SERVICE_TOOL_NAMES, ...DESIGN_TOOL_NAMES, ...Object.keys(MEDIA)];
|
|
5295
5429
|
|
|
5296
5430
|
// src/resources/prompt.js
|
|
5297
|
-
var
|
|
5431
|
+
var fail7 = (code, message) => new IaGenifyError(400, code, message);
|
|
5298
5432
|
var PROMPT_OPTIONS = {
|
|
5299
5433
|
model: "text",
|
|
5300
5434
|
mode: ["ask", "auto", "plan", "full"],
|
|
@@ -5317,8 +5451,8 @@ function storageIndex(storages = []) {
|
|
|
5317
5451
|
const byProvider = /* @__PURE__ */ new Map();
|
|
5318
5452
|
for (const s of storages) {
|
|
5319
5453
|
if (!s) continue;
|
|
5320
|
-
const
|
|
5321
|
-
if (
|
|
5454
|
+
const slug2 = storageSlug(s.label || s.name);
|
|
5455
|
+
if (slug2) index.set(slug2, s);
|
|
5322
5456
|
if (s.provider) byProvider.set(s.provider, [...byProvider.get(s.provider) || [], s]);
|
|
5323
5457
|
}
|
|
5324
5458
|
for (const [provider, list] of byProvider) if (list.length === 1 && !index.has(provider)) index.set(provider, list[0]);
|
|
@@ -5335,26 +5469,26 @@ function parsePrompt(input, library = {}) {
|
|
|
5335
5469
|
if (!flag) break;
|
|
5336
5470
|
const key = flag[1].toLowerCase();
|
|
5337
5471
|
const kind = PROMPT_OPTIONS[key];
|
|
5338
|
-
if (!kind) throw
|
|
5472
|
+
if (!kind) throw fail7("unknown_option", `Unknown option --${key}. Options: ${Object.keys(PROMPT_OPTIONS).map((k) => `--${k}`).join(" ")}. Write \\-- to start a message with "--".`);
|
|
5339
5473
|
rest = rest.slice(flag[0].length);
|
|
5340
5474
|
if (kind === "flag") {
|
|
5341
5475
|
if (key === "no-memory") options.memory = false;
|
|
5342
5476
|
continue;
|
|
5343
5477
|
}
|
|
5344
5478
|
const found = rest.match(/^(?:=|[ \t]+)("([^"]*)"|'([^']*)'|\S+)/);
|
|
5345
|
-
if (!found) throw
|
|
5479
|
+
if (!found) throw fail7("option_value_required", `--${key} needs a value.`);
|
|
5346
5480
|
const value = found[2] ?? found[3] ?? found[1];
|
|
5347
5481
|
rest = rest.slice(found[0].length);
|
|
5348
5482
|
if (key === "mode") {
|
|
5349
|
-
if (!kind.includes(value)) throw
|
|
5483
|
+
if (!kind.includes(value)) throw fail7("invalid_option", `--mode must be one of ${kind.join(", ")}.`);
|
|
5350
5484
|
options.mode = value;
|
|
5351
5485
|
} else if (key === "budget") {
|
|
5352
5486
|
if (value === "none") options.budget = null;
|
|
5353
5487
|
else if (Number(value) > 0) options.budget = Math.round(Number(value));
|
|
5354
|
-
else throw
|
|
5488
|
+
else throw fail7("invalid_option", "--budget takes a number of credits, or none.");
|
|
5355
5489
|
} else if (key === "context") {
|
|
5356
5490
|
const tokens = parseTokenCount(value);
|
|
5357
|
-
if (!tokens) throw
|
|
5491
|
+
if (!tokens) throw fail7("invalid_option", "--context takes a number of tokens: 200k, 400k, 1M.");
|
|
5358
5492
|
options.contextTokens = tokens;
|
|
5359
5493
|
} else {
|
|
5360
5494
|
options[key] = value;
|
|
@@ -5395,7 +5529,7 @@ function parsePrompt(input, library = {}) {
|
|
|
5395
5529
|
}
|
|
5396
5530
|
|
|
5397
5531
|
// src/resources/library.js
|
|
5398
|
-
var
|
|
5532
|
+
var fail8 = (status, code, message) => new IaGenifyError(status, code, message);
|
|
5399
5533
|
var NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
5400
5534
|
var MAX_CONTENT = 1e5;
|
|
5401
5535
|
var CLAUDE_TOOLS = { ls: "list", websearch: "search", webfetch: "fetch", multiedit: "multi_edit", todowrite: "todo_write" };
|
|
@@ -5477,34 +5611,34 @@ var LocalLibrary = class {
|
|
|
5477
5611
|
}
|
|
5478
5612
|
async _ready() {
|
|
5479
5613
|
if (typeof process === "undefined" || !process.versions?.node) {
|
|
5480
|
-
throw
|
|
5614
|
+
throw fail8(400, "local_files_require_node", "A computer's skills and subagents live on its disk: that source is only available from Node.js. The account's own are available everywhere.");
|
|
5481
5615
|
}
|
|
5482
5616
|
if (this.storage && this.storage.type !== "filesystem") {
|
|
5483
|
-
throw
|
|
5617
|
+
throw fail8(400, "storage_not_local", `\xAB ${this.storage.label} \xBB n'est pas un stockage ordinateur : ses ${this.kind} ne sont pas sur un disque.`);
|
|
5484
5618
|
}
|
|
5485
5619
|
if (this.storage?.machineId && this.storage.machineId !== await getMachineId()) {
|
|
5486
|
-
throw
|
|
5620
|
+
throw fail8(409, "storage_not_on_this_machine", `\xAB ${this.storage.label} \xBB belongs to another computer: its ${this.kind} stay there.`);
|
|
5487
5621
|
}
|
|
5488
5622
|
const { fs, path, os } = await node3();
|
|
5489
|
-
const
|
|
5490
|
-
const dir = path.join(
|
|
5623
|
+
const base2 = this.root || path.join(os.homedir(), ".iagenify");
|
|
5624
|
+
const dir = path.join(base2, this.spec.folder);
|
|
5491
5625
|
await fs.mkdir(dir, { recursive: true, mode: 448 });
|
|
5492
|
-
return { fs, path, base, dir };
|
|
5626
|
+
return { fs, path, base: base2, dir };
|
|
5493
5627
|
}
|
|
5494
5628
|
_file(path, dir, name) {
|
|
5495
5629
|
return this.kind === "skills" ? path.join(dir, name, "SKILL.md") : path.join(dir, `${name}.md`);
|
|
5496
5630
|
}
|
|
5497
5631
|
_checkName(name) {
|
|
5498
5632
|
if (typeof name !== "string" || !NAME.test(name)) {
|
|
5499
|
-
throw
|
|
5633
|
+
throw fail8(400, "invalid_name", `A ${this.spec.label} name uses lowercase letters, digits and dashes (e.g. "legal-review"), 64 characters at most.`);
|
|
5500
5634
|
}
|
|
5501
5635
|
}
|
|
5502
5636
|
/** Un élément lu sur disque : { name, description, …, content, builtIn: false }. */
|
|
5503
5637
|
_fromFile(name, text2, extra = {}) {
|
|
5504
5638
|
const { data, body } = parseFrontmatter(text2);
|
|
5505
|
-
const
|
|
5506
|
-
if (this.kind === "subagents") Object.assign(
|
|
5507
|
-
return { ...
|
|
5639
|
+
const base2 = { name, description: String(data.description || "").trim(), builtIn: false };
|
|
5640
|
+
if (this.kind === "subagents") Object.assign(base2, { tools: normalizeTools(data.tools), model: normalizeModel(data.model) });
|
|
5641
|
+
return { ...base2, ...extra, content: body };
|
|
5508
5642
|
}
|
|
5509
5643
|
_builtIn(name) {
|
|
5510
5644
|
const item = this.spec.builtIns[name];
|
|
@@ -5540,7 +5674,7 @@ var LocalLibrary = class {
|
|
|
5540
5674
|
try {
|
|
5541
5675
|
text2 = await fs.readFile(file, "utf8");
|
|
5542
5676
|
} catch (err) {
|
|
5543
|
-
if (err.code === "ENOENT") throw
|
|
5677
|
+
if (err.code === "ENOENT") throw fail8(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
|
|
5544
5678
|
throw err;
|
|
5545
5679
|
}
|
|
5546
5680
|
if (this.kind !== "skills") return this._fromFile(name, text2);
|
|
@@ -5564,10 +5698,10 @@ var LocalLibrary = class {
|
|
|
5564
5698
|
async save(item = {}) {
|
|
5565
5699
|
const { name, description, content } = item;
|
|
5566
5700
|
this._checkName(name);
|
|
5567
|
-
if (this.spec.builtIns[name]) throw
|
|
5568
|
-
if (typeof description !== "string" || !description.trim()) throw
|
|
5569
|
-
if (typeof content !== "string" || !content.trim()) throw
|
|
5570
|
-
if (content.length > MAX_CONTENT) throw
|
|
5701
|
+
if (this.spec.builtIns[name]) throw fail8(409, "name_reserved", `"${name}" is a built-in ${this.spec.label}; choose another name.`);
|
|
5702
|
+
if (typeof description !== "string" || !description.trim()) throw fail8(400, "description_required", `A ${this.spec.label} needs a description: it is how the agent knows when to use it.`);
|
|
5703
|
+
if (typeof content !== "string" || !content.trim()) throw fail8(400, "content_required", `A ${this.spec.label} needs instructions (content).`);
|
|
5704
|
+
if (content.length > MAX_CONTENT) throw fail8(400, "content_too_long", `Instructions are limited to ${MAX_CONTENT.toLocaleString("en")} characters.`);
|
|
5571
5705
|
const data = { name, description: description.trim().replace(/\s+/g, " ") };
|
|
5572
5706
|
if (this.kind === "subagents") {
|
|
5573
5707
|
const tools = normalizeTools(item.tools);
|
|
@@ -5583,30 +5717,30 @@ var LocalLibrary = class {
|
|
|
5583
5717
|
/** Met l'élément à la corbeille (~/.iagenify/.trash/<horodatage>/…), d'où on peut le récupérer. */
|
|
5584
5718
|
async remove(name) {
|
|
5585
5719
|
this._checkName(name);
|
|
5586
|
-
if (this.spec.builtIns[name]) throw
|
|
5587
|
-
const { fs, path, base, dir } = await this._ready();
|
|
5720
|
+
if (this.spec.builtIns[name]) throw fail8(400, "builtin_item", `"${name}" is built in and cannot be removed.`);
|
|
5721
|
+
const { fs, path, base: base2, dir } = await this._ready();
|
|
5588
5722
|
const source = this.kind === "skills" ? path.join(dir, name) : this._file(path, dir, name);
|
|
5589
5723
|
try {
|
|
5590
5724
|
await fs.access(source);
|
|
5591
5725
|
} catch {
|
|
5592
|
-
throw
|
|
5726
|
+
throw fail8(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
|
|
5593
5727
|
}
|
|
5594
|
-
const target = path.join(
|
|
5728
|
+
const target = path.join(base2, ".trash", (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-"), this.spec.folder, path.basename(source));
|
|
5595
5729
|
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
5596
5730
|
await fs.rename(source, target);
|
|
5597
5731
|
return { ok: true };
|
|
5598
5732
|
}
|
|
5599
5733
|
/** Skills seulement : un fichier du skill (modèle, référence…), en texte. */
|
|
5600
5734
|
async readFile(name, file) {
|
|
5601
|
-
if (this.kind !== "skills") throw
|
|
5735
|
+
if (this.kind !== "skills") throw fail8(400, "not_a_skill", "Only skills have files.");
|
|
5602
5736
|
const skill = await this.get(name);
|
|
5603
5737
|
const { fs, path } = await node3();
|
|
5604
5738
|
const full = path.resolve(skill.folder, String(file || "").replace(/\\/g, "/"));
|
|
5605
|
-
if (!full.startsWith(skill.folder + path.sep)) throw
|
|
5739
|
+
if (!full.startsWith(skill.folder + path.sep)) throw fail8(400, "invalid_path", `"${file}" is outside the skill folder.`);
|
|
5606
5740
|
try {
|
|
5607
5741
|
return { name: path.basename(full), path: path.relative(skill.folder, full).split(path.sep).join("/"), content: await fs.readFile(full, "utf8") };
|
|
5608
5742
|
} catch (err) {
|
|
5609
|
-
if (err.code === "ENOENT" || err.code === "EISDIR") throw
|
|
5743
|
+
if (err.code === "ENOENT" || err.code === "EISDIR") throw fail8(404, "path_not_found", `The skill "${name}" has no file "${file}". Files: ${skill.files.join(", ") || "none"}.`);
|
|
5610
5744
|
throw err;
|
|
5611
5745
|
}
|
|
5612
5746
|
}
|
|
@@ -5681,13 +5815,13 @@ var AgentLibrary = class {
|
|
|
5681
5815
|
if (err.status !== 404 || !this.computer) throw err;
|
|
5682
5816
|
const onDisk = await this.computer.get(name).catch(() => null);
|
|
5683
5817
|
if (!onDisk) throw err;
|
|
5684
|
-
throw
|
|
5818
|
+
throw fail8(409, "item_on_computer", `\xAB ${name} \xBB est un fichier de cet ordinateur (~/.iagenify/${this.spec.folder}) : supprimez-le sur le disque.`);
|
|
5685
5819
|
}
|
|
5686
5820
|
}
|
|
5687
5821
|
/** Skills seulement : un fichier annexe. Ceux du compte n'en ont pas — le contenu est le document. */
|
|
5688
5822
|
async readFile(name, file) {
|
|
5689
|
-
if (this.kind !== "skills") throw
|
|
5690
|
-
if (!this.computer) throw
|
|
5823
|
+
if (this.kind !== "skills") throw fail8(400, "not_a_skill", "Only skills have files.");
|
|
5824
|
+
if (!this.computer) throw fail8(404, "path_not_found", `\xAB ${name} \xBB n'a pas de fichiers : les skills du compte sont un seul document.`);
|
|
5691
5825
|
return this.computer.readFile(name, file);
|
|
5692
5826
|
}
|
|
5693
5827
|
};
|
|
@@ -5703,11 +5837,11 @@ var MAX_OUTPUT2 = 6e4;
|
|
|
5703
5837
|
var CALL_TIMEOUT_MS = 6e4;
|
|
5704
5838
|
var LIST_TIMEOUT_MS = 3e4;
|
|
5705
5839
|
var MAX_PAGES = 20;
|
|
5706
|
-
var
|
|
5840
|
+
var fail9 = (status, code, message) => new IaGenifyError(status, code, message);
|
|
5707
5841
|
var CODE_VERSION_NON_SUPPORTEE = -32022;
|
|
5708
5842
|
var estErreurModerne = (code) => typeof code === "number" && code <= -32020 && code >= -32099;
|
|
5709
5843
|
var REPLI_ANCIENNE_POIGNEE = /* @__PURE__ */ new Set(["mcp_error", "mcp_http_error", "mcp_bad_response"]);
|
|
5710
|
-
var
|
|
5844
|
+
var clip5 = (text2, max = MAX_OUTPUT2) => text2.length > max ? `${text2.slice(0, max)}
|
|
5711
5845
|
\u2026[truncated ${text2.length - max} characters]` : text2;
|
|
5712
5846
|
var SCHEMA_TYPES = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "array", "object"]);
|
|
5713
5847
|
var SCHEMA_KEYS = /* @__PURE__ */ new Set(["type", "description", "properties", "required", "items", "enum", "nullable"]);
|
|
@@ -5764,7 +5898,7 @@ function cleanToken(value) {
|
|
|
5764
5898
|
token = token.replace(/^authorization\s*:\s*/i, "").replace(/^bearer\b\s*/i, "").replace(/^token\s*=\s*/i, "").trim().replace(quotes, "").trim();
|
|
5765
5899
|
if (!token) return null;
|
|
5766
5900
|
if (/\s/.test(token)) {
|
|
5767
|
-
throw
|
|
5901
|
+
throw fail9(400, "mcp_token_malformed", "Ce jeton contient une espace : collez le jeton seul, sans \xAB Bearer \xBB, sans guillemets et sans retour \xE0 la ligne.");
|
|
5768
5902
|
}
|
|
5769
5903
|
return token;
|
|
5770
5904
|
}
|
|
@@ -5840,7 +5974,7 @@ function mirroredParams(schema, args) {
|
|
|
5840
5974
|
}
|
|
5841
5975
|
var McpClient = class {
|
|
5842
5976
|
constructor({ url, token = null, name = "mcp", fetchImpl = null } = {}) {
|
|
5843
|
-
if (!url) throw
|
|
5977
|
+
if (!url) throw fail9(400, "url_required", "An MCP server needs its address.");
|
|
5844
5978
|
this.url = String(url);
|
|
5845
5979
|
this.token = cleanToken(token);
|
|
5846
5980
|
this.name = name;
|
|
@@ -5902,8 +6036,8 @@ var McpClient = class {
|
|
|
5902
6036
|
redirect: "manual"
|
|
5903
6037
|
});
|
|
5904
6038
|
} catch (err) {
|
|
5905
|
-
if (controller.signal.aborted) throw
|
|
5906
|
-
throw
|
|
6039
|
+
if (controller.signal.aborted) throw fail9(504, "mcp_timeout", `\xAB ${this.name} \xBB n'a pas r\xE9pondu en ${Math.round(timeout / 1e3)} s.`);
|
|
6040
|
+
throw fail9(502, "mcp_unreachable", `\xAB ${this.name} \xBB est injoignable : ${err.message}`);
|
|
5907
6041
|
} finally {
|
|
5908
6042
|
clearTimeout(timer);
|
|
5909
6043
|
signal?.removeEventListener?.("abort", abort);
|
|
@@ -5912,17 +6046,17 @@ var McpClient = class {
|
|
|
5912
6046
|
const detail = this._detail(brut);
|
|
5913
6047
|
if (response.status === 401 || response.status === 403) {
|
|
5914
6048
|
if (!this.token) {
|
|
5915
|
-
throw
|
|
6049
|
+
throw fail9(401, "mcp_token_required", `\xAB ${this.name} \xBB demande un jeton : ce serveur ne r\xE9pond pas sans authentification.${detail}`);
|
|
5916
6050
|
}
|
|
5917
|
-
throw
|
|
6051
|
+
throw fail9(401, "mcp_unauthorized", `\xAB ${this.name} \xBB refuse le jeton (${response.status}). V\xE9rifiez-le, ou recr\xE9ez-en un.${detail}`);
|
|
5918
6052
|
}
|
|
5919
6053
|
if (response.status >= 300 && response.status < 400) {
|
|
5920
|
-
throw
|
|
6054
|
+
throw fail9(502, "mcp_redirect", `\xAB ${this.name} \xBB redirige vers une autre adresse : reconnectez-le avec l'adresse d\xE9finitive.`);
|
|
5921
6055
|
}
|
|
5922
|
-
if (!response.ok) throw this._rpcError(
|
|
6056
|
+
if (!response.ok) throw this._rpcError(fail9(502, "mcp_http_error", `\xAB ${this.name} \xBB a r\xE9pondu ${response.status}.${detail}`), brut);
|
|
5923
6057
|
const message = await this._readMessage(response, id);
|
|
5924
6058
|
if (message?.error) {
|
|
5925
|
-
const err =
|
|
6059
|
+
const err = fail9(502, "mcp_error", `\xAB ${this.name} \xBB refuse : ${String(message.error.message || message.error.code || "erreur").slice(0, 500)}`);
|
|
5926
6060
|
err.rpc = { code: message.error.code, data: message.error.data };
|
|
5927
6061
|
throw err;
|
|
5928
6062
|
}
|
|
@@ -5952,12 +6086,12 @@ var McpClient = class {
|
|
|
5952
6086
|
/** La réponse, qu'elle arrive en JSON ou en flux d'événements (`text/event-stream`). */
|
|
5953
6087
|
async _readMessage(response, id) {
|
|
5954
6088
|
const type = String(response.headers.get("content-type") || "");
|
|
5955
|
-
const body =
|
|
6089
|
+
const body = clip5(await response.text(), 2e6);
|
|
5956
6090
|
if (!type.includes("text/event-stream")) {
|
|
5957
6091
|
try {
|
|
5958
6092
|
return JSON.parse(body);
|
|
5959
6093
|
} catch {
|
|
5960
|
-
throw
|
|
6094
|
+
throw fail9(502, "mcp_bad_response", `\xAB ${this.name} \xBB n'a pas r\xE9pondu en JSON.`);
|
|
5961
6095
|
}
|
|
5962
6096
|
}
|
|
5963
6097
|
let last = null;
|
|
@@ -5972,7 +6106,7 @@ var McpClient = class {
|
|
|
5972
6106
|
}
|
|
5973
6107
|
}
|
|
5974
6108
|
if (last) return last;
|
|
5975
|
-
throw
|
|
6109
|
+
throw fail9(502, "mcp_bad_response", `\xAB ${this.name} \xBB n'a renvoy\xE9 aucune r\xE9ponse exploitable.`);
|
|
5976
6110
|
}
|
|
5977
6111
|
/**
|
|
5978
6112
|
* La poignée de main, dans les deux révisions. Elle dit quelle version le serveur a acceptée.
|
|
@@ -5994,7 +6128,7 @@ var McpClient = class {
|
|
|
5994
6128
|
const propose = err.rpc?.data?.supportedVersions || err.rpc?.data?.supported;
|
|
5995
6129
|
const version = negotiateVersion(propose);
|
|
5996
6130
|
if (!version) {
|
|
5997
|
-
throw
|
|
6131
|
+
throw fail9(
|
|
5998
6132
|
502,
|
|
5999
6133
|
"mcp_protocol_unsupported",
|
|
6000
6134
|
`\xAB ${this.name} \xBB ne parle aucune r\xE9vision que ce client conna\xEEt (il propose ${[].concat(propose || []).join(", ") || "rien"}).`
|
|
@@ -6025,7 +6159,7 @@ var McpClient = class {
|
|
|
6025
6159
|
const found = await this._rpc("server/discover", {}, { signal });
|
|
6026
6160
|
const version = negotiateVersion(found.supportedVersions);
|
|
6027
6161
|
if (found.supportedVersions && !version) {
|
|
6028
|
-
throw
|
|
6162
|
+
throw fail9(
|
|
6029
6163
|
502,
|
|
6030
6164
|
"mcp_protocol_unsupported",
|
|
6031
6165
|
`\xAB ${this.name} \xBB ne parle aucune r\xE9vision que ce client conna\xEEt (il propose ${[].concat(found.supportedVersions).join(", ")}).`
|
|
@@ -6077,7 +6211,7 @@ var McpClient = class {
|
|
|
6077
6211
|
return part?.text ? String(part.text) : "";
|
|
6078
6212
|
}).filter(Boolean).join("\n");
|
|
6079
6213
|
const output = text2 || (result.structuredContent ? JSON.stringify(result.structuredContent) : "(aucun contenu)");
|
|
6080
|
-
return { output:
|
|
6214
|
+
return { output: clip5(output), isError: Boolean(result.isError) };
|
|
6081
6215
|
}
|
|
6082
6216
|
};
|
|
6083
6217
|
var McpResource = class {
|
|
@@ -6487,6 +6621,7 @@ var TOOL_FAMILIES = [
|
|
|
6487
6621
|
["Storages", ["query_storage", "write_storage"]],
|
|
6488
6622
|
["The account", ["account", "cloud"]],
|
|
6489
6623
|
["Put online and communicate", ["deploy", "domain", "mail", "send_mail"]],
|
|
6624
|
+
["Design", ["design_read", "design_apply", "design_render", "design_check", "design_template"]],
|
|
6490
6625
|
["The platform itself", ["iagenify_docs", "workflow", "mcp"]],
|
|
6491
6626
|
["Ask another model", ["generate"]],
|
|
6492
6627
|
["This conversation", ["todo_write", "ask_user", "memory", "recall", "skill", "task"]]
|
|
@@ -6666,9 +6801,9 @@ var SUBAGENT_MAX_STEPS = 40;
|
|
|
6666
6801
|
var MAX_SKILL_OUTPUT = 6e4;
|
|
6667
6802
|
var withoutAttachments = (messages) => messages.map(({ attachments, images, ...m }) => attachments?.length || images?.length ? { ...m, content: `${m.content || ""} [${(attachments || images).length} file(s) attached]` } : m);
|
|
6668
6803
|
var estimateTokens = (messages) => Math.ceil(JSON.stringify(withoutAttachments(messages)).length / 4);
|
|
6669
|
-
var
|
|
6804
|
+
var clip6 = (text2, max) => text2.length > max ? `${text2.slice(0, max)}
|
|
6670
6805
|
\u2026[truncated ${text2.length - max} characters]` : text2;
|
|
6671
|
-
var
|
|
6806
|
+
var fail10 = (message) => {
|
|
6672
6807
|
throw new IaGenifyError(400, "tool_error", message);
|
|
6673
6808
|
};
|
|
6674
6809
|
var KEEP_ATTACHMENTS_FOR = 6;
|
|
@@ -7019,11 +7154,11 @@ var LocalAgent = class _LocalAgent {
|
|
|
7019
7154
|
const notes = await this.api.memory.list();
|
|
7020
7155
|
return { output: notes.length ? notes.map((n) => `- ${n.name}: ${n.description || n.content.slice(0, 80)}`).join("\n") : "(no memory yet)", summary: `${notes.length} notes` };
|
|
7021
7156
|
}
|
|
7022
|
-
if (!name)
|
|
7157
|
+
if (!name) fail10("memory needs a name.");
|
|
7023
7158
|
if (action === "read") {
|
|
7024
7159
|
const notes = await this.api.memory.list();
|
|
7025
7160
|
const note = notes.find((n) => n.name === name);
|
|
7026
|
-
if (!note)
|
|
7161
|
+
if (!note) fail10(`No memory called "${name}". Listed names: ${notes.map((n) => n.name).join(", ") || "none"}.`);
|
|
7027
7162
|
return { output: `# ${note.name}
|
|
7028
7163
|
${note.description}
|
|
7029
7164
|
|
|
@@ -7034,7 +7169,7 @@ ${note.content}`, summary: note.name, meta: { memory: note.name } };
|
|
|
7034
7169
|
this.memories = this.memories.filter((n) => n.name !== name);
|
|
7035
7170
|
return { output: `Memory "${name}" deleted.`, summary: name, meta: { memory: name, deleted: true } };
|
|
7036
7171
|
}
|
|
7037
|
-
if (!content.trim())
|
|
7172
|
+
if (!content.trim()) fail10("memory save needs content.");
|
|
7038
7173
|
const saved = await this.api.memory.save({ name, description, content, type, source: "agent", ...this.memory ? { sessionId: this.id } : {} });
|
|
7039
7174
|
this.memories = [saved, ...this.memories.filter((n) => n.name !== saved.name)];
|
|
7040
7175
|
return { output: `Remembered as "${saved.name}". It will be in your memory index from now on.`, summary: saved.name, meta: { memory: saved.name, saved: true } };
|
|
@@ -7068,19 +7203,19 @@ ${note.content}`, summary: note.name, meta: { memory: note.name } };
|
|
|
7068
7203
|
file: { type: "string", description: "Optional: one of the skill's files, as listed when it is loaded" }
|
|
7069
7204
|
}),
|
|
7070
7205
|
run: async ({ name, file }) => {
|
|
7071
|
-
if (!this.library.skills.some((s) => s.name === name))
|
|
7206
|
+
if (!this.library.skills.some((s) => s.name === name)) fail10(`Unknown skill "${name}". Available: ${this.library.skills.map((s) => s.name).join(", ")}.`);
|
|
7072
7207
|
const library = this._library("skills");
|
|
7073
|
-
if (!library)
|
|
7208
|
+
if (!library) fail10("No skills are available here.");
|
|
7074
7209
|
if (file) {
|
|
7075
7210
|
const read = await library.readFile(name, file);
|
|
7076
|
-
return { output:
|
|
7211
|
+
return { output: clip6(read.content, MAX_SKILL_OUTPUT) || "(empty file)", summary: `${name} \xB7 ${read.path}`, meta: { skill: name, file: read.path } };
|
|
7077
7212
|
}
|
|
7078
7213
|
const skill = await library.get(name);
|
|
7079
7214
|
const files = skill.files?.length ? `
|
|
7080
7215
|
|
|
7081
7216
|
Files in this skill (read one with skill + file): ${skill.files.join(", ")}${skill.folder ? `
|
|
7082
7217
|
Folder on this computer, for commands: ${skill.folder}` : ""}` : "";
|
|
7083
|
-
return { output:
|
|
7218
|
+
return { output: clip6(`# Skill: ${name}
|
|
7084
7219
|
|
|
7085
7220
|
${skill.content}${files}`, MAX_SKILL_OUTPUT), summary: `Loaded ${name}`, meta: { skill: name, files: skill.files?.length || 0 } };
|
|
7086
7221
|
}
|
|
@@ -7099,8 +7234,8 @@ ${skill.content}${files}`, MAX_SKILL_OUTPUT), summary: `Loaded ${name}`, meta: {
|
|
|
7099
7234
|
}
|
|
7100
7235
|
/** Lance un sous-agent : même machine, même mode, mêmes permissions, budget et crédits partagés avec ce run. */
|
|
7101
7236
|
async _runSubagent({ agent: name, description = "", prompt }, call) {
|
|
7102
|
-
if (!this.library.subagents.some((a) => a.name === name))
|
|
7103
|
-
if (!String(prompt || "").trim())
|
|
7237
|
+
if (!this.library.subagents.some((a) => a.name === name)) fail10(`Unknown subagent "${name}". Available: ${this.library.subagents.map((a) => a.name).join(", ")}.`);
|
|
7238
|
+
if (!String(prompt || "").trim()) fail10("task needs a prompt: the subagent sees nothing of this conversation.");
|
|
7104
7239
|
const definition = await this._definition("subagents", name);
|
|
7105
7240
|
const wanted = !definition.tools || definition.tools === "all" ? WORKSPACE_TOOL_NAMES : definition.tools;
|
|
7106
7241
|
const tools = wanted.filter((t) => this.toolNames.includes(t) && !PARENT_ONLY_TOOLS.has(t));
|
|
@@ -7150,7 +7285,7 @@ ${skill.content}${files}`, MAX_SKILL_OUTPUT), summary: `Loaded ${name}`, meta: {
|
|
|
7150
7285
|
|
|
7151
7286
|
[${name} subagent \xB7 ${turns} turns \xB7 ${toolCalls} tool calls \xB7 ${credits} credits${ended}]`,
|
|
7152
7287
|
summary: description || name,
|
|
7153
|
-
meta: { agent: name, description, model: child.model, turns, toolCalls, credits, stopReason: result.stopReason, report:
|
|
7288
|
+
meta: { agent: name, description, model: child.model, turns, toolCalls, credits, stopReason: result.stopReason, report: clip6(result.text || "", 4e3) }
|
|
7154
7289
|
};
|
|
7155
7290
|
} finally {
|
|
7156
7291
|
this.children.delete(child);
|
|
@@ -7181,7 +7316,7 @@ Files in this skill (read one with skill + file): ${skill.files.join(", ")}` : "
|
|
|
7181
7316
|
|
|
7182
7317
|
# Skill: ${name}
|
|
7183
7318
|
|
|
7184
|
-
${
|
|
7319
|
+
${clip6(skill.content, MAX_SKILL_OUTPUT)}${files}
|
|
7185
7320
|
|
|
7186
7321
|
# Request
|
|
7187
7322
|
${args || "Apply this skill."}`;
|
|
@@ -7244,13 +7379,13 @@ ${args || "Apply this skill."}`;
|
|
|
7244
7379
|
const read = await this.catalog.read.run({ path }, { files });
|
|
7245
7380
|
if (read.attachments?.length) images.push(...read.attachments.map((a) => ({ mime: a.mime, data: a.data })));
|
|
7246
7381
|
sections.push(`## @${read.meta?.path || path}
|
|
7247
|
-
${read.attachments?.length ? read.output :
|
|
7382
|
+
${read.attachments?.length ? read.output : clip6(read.output, 3e4)}`);
|
|
7248
7383
|
emit({ type: "mention", kind: "file", path: read.meta?.path || path });
|
|
7249
7384
|
} catch {
|
|
7250
7385
|
try {
|
|
7251
7386
|
const list = await this.catalog.list.run({ path }, { files });
|
|
7252
7387
|
sections.push(`## @${path} (folder)
|
|
7253
|
-
${
|
|
7388
|
+
${clip6(list.output, 8e3)}`);
|
|
7254
7389
|
emit({ type: "mention", kind: "folder", path });
|
|
7255
7390
|
} catch {
|
|
7256
7391
|
}
|
|
@@ -7261,7 +7396,7 @@ ${clip5(list.output, 8e3)}`);
|
|
|
7261
7396
|
try {
|
|
7262
7397
|
const read = await this.catalog.query_storage.run({ storage: s.name, action, ...action === "schema" ? { collection: s.collection } : {}, ...action === "objects" && s.collection ? { prefix: s.collection } : {} }, { api: this.api });
|
|
7263
7398
|
sections.push(`## #${s.name}${s.collection ? ` \xB7 ${s.collection}` : ""}
|
|
7264
|
-
${
|
|
7399
|
+
${clip6(read.output, 8e3)}`);
|
|
7265
7400
|
emit({ type: "mention", kind: "storage", storage: s.name, collection: s.collection });
|
|
7266
7401
|
} catch (err) {
|
|
7267
7402
|
sections.push(`## #${s.name}${s.collection ? ` \xB7 ${s.collection}` : ""}
|
|
@@ -8897,10 +9032,16 @@ var Host = class {
|
|
|
8897
9032
|
if (files !== void 0) throw new IaGenifyError(400, "invalid_deploy", "An edge host deploys code, not a folder.");
|
|
8898
9033
|
if (typeof code !== "string" || !code.trim()) throw new IaGenifyError(400, "nothing_to_deploy", "An edge host needs a code module.");
|
|
8899
9034
|
}
|
|
8900
|
-
const
|
|
8901
|
-
if (code !== void 0)
|
|
8902
|
-
if (files
|
|
8903
|
-
|
|
9035
|
+
const withServer = this.runtime === "node" && server !== void 0;
|
|
9036
|
+
if (files !== void 0 && code !== void 0) throw new IaGenifyError(400, "invalid_deploy", "Pass files or code, not both.");
|
|
9037
|
+
if (files === void 0) {
|
|
9038
|
+
return (await this.client.post(`/api/hosting/${this.id}/deploy`, { code, ...withServer ? { server } : {} })).deploy;
|
|
9039
|
+
}
|
|
9040
|
+
const entries = await collectFiles(files);
|
|
9041
|
+
const total = entries.reduce((sum, file) => sum + file.size, 0);
|
|
9042
|
+
if (total > DIRECT_UPLOAD_ABOVE) return deployDirect(this.client, this.id, entries, withServer ? server : void 0);
|
|
9043
|
+
const body = { files: await Promise.all(entries.map(async (file) => ({ path: file.path, content: toBase64(await file.load()) }))) };
|
|
9044
|
+
if (withServer) body.server = server;
|
|
8904
9045
|
return (await this.client.post(`/api/hosting/${this.id}/deploy`, body)).deploy;
|
|
8905
9046
|
}
|
|
8906
9047
|
async update({ label } = {}) {
|
|
@@ -8921,14 +9062,18 @@ var Host = class {
|
|
|
8921
9062
|
return this.client.delete(`/api/hosting/${this.id}`);
|
|
8922
9063
|
}
|
|
8923
9064
|
};
|
|
8924
|
-
|
|
9065
|
+
var DIRECT_UPLOAD_ABOVE = 8 * 1024 * 1024;
|
|
9066
|
+
var PACKS_IN_FLIGHT = 3;
|
|
9067
|
+
var PACK_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
9068
|
+
var FINISH_TIMEOUT_MS = 10 * 60 * 1e3;
|
|
9069
|
+
async function collectFiles(input) {
|
|
8925
9070
|
if (Array.isArray(input)) {
|
|
8926
9071
|
const files = input.map((file) => {
|
|
8927
9072
|
const path2 = String(file?.path ?? "").replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "");
|
|
8928
9073
|
if (!path2) throw new IaGenifyError(400, "nothing_to_deploy", "Every file needs a path.");
|
|
8929
9074
|
if (NEVER_DEPLOY2.some((rule) => rule.test(path2))) return null;
|
|
8930
9075
|
const bytes = typeof file?.content === "string" ? new TextEncoder().encode(file.content) : new Uint8Array(file?.content ?? []);
|
|
8931
|
-
return { path: path2,
|
|
9076
|
+
return { path: path2, size: bytes.length, load: async () => bytes };
|
|
8932
9077
|
}).filter(Boolean);
|
|
8933
9078
|
if (!files.length) throw new IaGenifyError(400, "nothing_to_deploy", "No deployable files were provided.");
|
|
8934
9079
|
return files;
|
|
@@ -8950,7 +9095,10 @@ async function readFiles(input) {
|
|
|
8950
9095
|
const relative = path.relative(root, full).split(path.sep).join("/");
|
|
8951
9096
|
if (NEVER_DEPLOY2.some((rule) => rule.test(relative))) continue;
|
|
8952
9097
|
if (entry.isDirectory()) await visit(full);
|
|
8953
|
-
else if (entry.isFile())
|
|
9098
|
+
else if (entry.isFile()) {
|
|
9099
|
+
const { size } = await fs.stat(full);
|
|
9100
|
+
result.push({ path: relative, size, load: async () => new Uint8Array(await fs.readFile(full)) });
|
|
9101
|
+
}
|
|
8954
9102
|
}
|
|
8955
9103
|
};
|
|
8956
9104
|
try {
|
|
@@ -8962,6 +9110,80 @@ async function readFiles(input) {
|
|
|
8962
9110
|
if (!result.length) throw new IaGenifyError(400, "nothing_to_deploy", `The folder "${input}" contains no deployable files.`);
|
|
8963
9111
|
return result;
|
|
8964
9112
|
}
|
|
9113
|
+
async function hashBytes(bytes) {
|
|
9114
|
+
const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", bytes));
|
|
9115
|
+
let hex = "";
|
|
9116
|
+
for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
|
|
9117
|
+
return hex.slice(0, 32);
|
|
9118
|
+
}
|
|
9119
|
+
function planPacks(hashes, sizeOf, { maxBytes, maxFiles }) {
|
|
9120
|
+
const packs = [];
|
|
9121
|
+
let current = [];
|
|
9122
|
+
let bytes = 0;
|
|
9123
|
+
for (const hash of hashes) {
|
|
9124
|
+
const size = sizeOf(hash);
|
|
9125
|
+
if (current.length && (bytes + size > maxBytes || current.length >= maxFiles)) {
|
|
9126
|
+
packs.push(current);
|
|
9127
|
+
current = [];
|
|
9128
|
+
bytes = 0;
|
|
9129
|
+
}
|
|
9130
|
+
current.push(hash);
|
|
9131
|
+
bytes += size;
|
|
9132
|
+
}
|
|
9133
|
+
if (current.length) packs.push(current);
|
|
9134
|
+
return packs;
|
|
9135
|
+
}
|
|
9136
|
+
async function deployDirect(client, hostId, entries, server) {
|
|
9137
|
+
const base2 = `/api/hosting/${hostId}/uploads`;
|
|
9138
|
+
const byHash = /* @__PURE__ */ new Map();
|
|
9139
|
+
const manifest = [];
|
|
9140
|
+
for (const entry of entries) {
|
|
9141
|
+
const hash = await hashBytes(await entry.load());
|
|
9142
|
+
manifest.push({ path: entry.path, size: entry.size, hash });
|
|
9143
|
+
if (!byHash.has(hash)) byHash.set(hash, entry);
|
|
9144
|
+
}
|
|
9145
|
+
const { upload } = await client.post(base2, { files: manifest, ...server !== void 0 ? { server } : {} });
|
|
9146
|
+
const send = async (missing2) => {
|
|
9147
|
+
const packs = planPacks(
|
|
9148
|
+
missing2.filter((hash) => byHash.has(hash)),
|
|
9149
|
+
(hash) => byHash.get(hash).size,
|
|
9150
|
+
{ maxBytes: upload.packBytes, maxFiles: upload.packFiles }
|
|
9151
|
+
);
|
|
9152
|
+
let next = 0;
|
|
9153
|
+
const worker = async () => {
|
|
9154
|
+
while (next < packs.length) {
|
|
9155
|
+
const pack = packs[next++];
|
|
9156
|
+
const parts = await Promise.all(pack.map((hash) => byHash.get(hash).load()));
|
|
9157
|
+
const body = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
|
|
9158
|
+
let offset = 0;
|
|
9159
|
+
for (const part of parts) {
|
|
9160
|
+
body.set(part, offset);
|
|
9161
|
+
offset += part.length;
|
|
9162
|
+
}
|
|
9163
|
+
const header = pack.map((hash) => `${hash}:${byHash.get(hash).size}`).join(",");
|
|
9164
|
+
for (let attempt = 1; ; attempt++) {
|
|
9165
|
+
try {
|
|
9166
|
+
await client.put(`${base2}/${upload.id}/parts`, body, { headers: { "X-IaGenify-Parts": header }, timeout: PACK_TIMEOUT_MS });
|
|
9167
|
+
break;
|
|
9168
|
+
} catch (error) {
|
|
9169
|
+
const transient = !error?.status || error.status >= 500 || error.status === 429;
|
|
9170
|
+
if (!transient || attempt >= 3) throw error;
|
|
9171
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3 * attempt));
|
|
9172
|
+
}
|
|
9173
|
+
}
|
|
9174
|
+
}
|
|
9175
|
+
};
|
|
9176
|
+
await Promise.all(Array.from({ length: Math.min(PACKS_IN_FLIGHT, packs.length) }, worker));
|
|
9177
|
+
};
|
|
9178
|
+
await send(upload.missing || []);
|
|
9179
|
+
try {
|
|
9180
|
+
return (await client.post(`${base2}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
|
|
9181
|
+
} catch (error) {
|
|
9182
|
+
if (error?.code !== "upload_incomplete" || !Array.isArray(error.details?.missing)) throw error;
|
|
9183
|
+
await send(error.details.missing);
|
|
9184
|
+
return (await client.post(`${base2}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
|
|
9185
|
+
}
|
|
9186
|
+
}
|
|
8965
9187
|
function toBase64(bytes) {
|
|
8966
9188
|
if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
|
|
8967
9189
|
let binary = "";
|
|
@@ -8973,10 +9195,10 @@ var HostsResource = class {
|
|
|
8973
9195
|
this.client = client;
|
|
8974
9196
|
}
|
|
8975
9197
|
/** `runtime` is the public contract. `kind` remains accepted for one upgrade cycle. */
|
|
8976
|
-
async create({ runtime, framework, label, slug, kind } = {}) {
|
|
9198
|
+
async create({ runtime, framework, label, slug: slug2, kind } = {}) {
|
|
8977
9199
|
const rule = assertRuntime(runtime || LEGACY_RUNTIME[kind], framework);
|
|
8978
9200
|
const resolvedRuntime = runtime || LEGACY_RUNTIME[kind];
|
|
8979
|
-
const res = await this.client.post("/api/hosting", { runtime: resolvedRuntime, framework, label, slug });
|
|
9201
|
+
const res = await this.client.post("/api/hosting", { runtime: resolvedRuntime, framework, label, slug: slug2 });
|
|
8980
9202
|
return new Host(this.client, res.host, { framework });
|
|
8981
9203
|
}
|
|
8982
9204
|
async list() {
|
|
@@ -9370,8 +9592,8 @@ var Contacts = class {
|
|
|
9370
9592
|
/** `avatar` est rendu absolu ici : l'API rend un chemin, elle ignore sous quel nom on l'atteint. */
|
|
9371
9593
|
_absolu(contact) {
|
|
9372
9594
|
if (!contact) return contact;
|
|
9373
|
-
const
|
|
9374
|
-
return contact.avatar?.startsWith("/") &&
|
|
9595
|
+
const base2 = typeof this.client?.baseUrl === "string" ? this.client.baseUrl : "";
|
|
9596
|
+
return contact.avatar?.startsWith("/") && base2 ? { ...contact, avatar: `${base2}${contact.avatar}` } : contact;
|
|
9375
9597
|
}
|
|
9376
9598
|
async list() {
|
|
9377
9599
|
const res = await this.client.get("/api/mail/contacts");
|
|
@@ -9462,6 +9684,955 @@ var MailResource = class {
|
|
|
9462
9684
|
}
|
|
9463
9685
|
};
|
|
9464
9686
|
|
|
9687
|
+
// src/studio/errors.js
|
|
9688
|
+
var StudioError = class extends Error {
|
|
9689
|
+
constructor(code, message, details = void 0, status = 400) {
|
|
9690
|
+
super(message);
|
|
9691
|
+
this.name = "StudioError";
|
|
9692
|
+
this.status = status;
|
|
9693
|
+
this.code = code;
|
|
9694
|
+
if (details !== void 0) this.details = details;
|
|
9695
|
+
}
|
|
9696
|
+
};
|
|
9697
|
+
|
|
9698
|
+
// src/studio/format.js
|
|
9699
|
+
var FORMAT = "iagenify.design";
|
|
9700
|
+
var FORMAT_VERSION = 1;
|
|
9701
|
+
var NODE_TYPES = ["frame", "text", "image", "shape"];
|
|
9702
|
+
var CONTENEURS = /* @__PURE__ */ new Set(["frame"]);
|
|
9703
|
+
var TAGS = {
|
|
9704
|
+
frame: ["div", "section", "header", "footer", "nav", "main", "article", "aside", "figure", "ul", "li", "a", "button"],
|
|
9705
|
+
text: ["p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "a", "button", "li", "small", "strong", "em", "label"],
|
|
9706
|
+
image: ["img"],
|
|
9707
|
+
shape: ["div"]
|
|
9708
|
+
};
|
|
9709
|
+
var DEFAULT_TAG = { frame: "div", text: "p", image: "img", shape: "div" };
|
|
9710
|
+
var CHAMPS_NOEUD = /* @__PURE__ */ new Set(["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"]);
|
|
9711
|
+
var CHAMPS = {
|
|
9712
|
+
layout: { mode: ["flex", "grid", "free"], direction: ["row", "column"], gap: "longueur", padding: "padding", align: ["start", "center", "end", "stretch"], justify: ["start", "center", "end", "between"], wrap: "booleen", columns: "entier" },
|
|
9713
|
+
size: { w: "dimension", h: "dimension", minW: "longueur", minH: "longueur", maxW: "longueur", maxH: "longueur" },
|
|
9714
|
+
position: { x: "nombre", y: "nombre", absolute: "booleen" },
|
|
9715
|
+
style: { fill: "remplissage", stroke: "trait", radius: "rayon", shadow: "ombres", opacity: "opacite", clip: "booleen" },
|
|
9716
|
+
text: { content: "texte", font: "police", size: "longueur", weight: "graisse", lineHeight: "interligne", align: ["left", "center", "right", "justify"], color: "couleur", letterSpacing: "nombre", transform: ["none", "uppercase", "lowercase", "capitalize"] },
|
|
9717
|
+
image: { src: "source", fit: ["cover", "contain", "fill"] },
|
|
9718
|
+
shape: { kind: ["rect", "ellipse", "line"] }
|
|
9719
|
+
};
|
|
9720
|
+
var COULEUR = /^(#[0-9a-f]{3}|#[0-9a-f]{4}|#[0-9a-f]{6}|#[0-9a-f]{8}|transparent|rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,\s*(0|1|0?\.\d+)\s*)?\))$/i;
|
|
9721
|
+
var POLICE = /^[A-Za-z0-9 \-]{1,64}$/;
|
|
9722
|
+
var SOURCE = /^asset:[A-Za-z0-9_\-]{1,64}$/;
|
|
9723
|
+
var fini = (v) => typeof v === "number" && Number.isFinite(v);
|
|
9724
|
+
function isColor(v) {
|
|
9725
|
+
return typeof v === "string" && COULEUR.test(v.trim());
|
|
9726
|
+
}
|
|
9727
|
+
function verifierValeur(regle, v) {
|
|
9728
|
+
if (Array.isArray(regle)) return regle.includes(v) ? null : `valeur_non_permise (${regle.join(", ")})`;
|
|
9729
|
+
switch (regle) {
|
|
9730
|
+
case "booleen":
|
|
9731
|
+
return typeof v === "boolean" ? null : "booleen_attendu";
|
|
9732
|
+
case "nombre":
|
|
9733
|
+
return fini(v) ? null : "nombre_attendu";
|
|
9734
|
+
case "entier":
|
|
9735
|
+
return Number.isInteger(v) && v >= 1 && v <= 24 ? null : "entier_1_24_attendu";
|
|
9736
|
+
case "longueur":
|
|
9737
|
+
return fini(v) && v >= 0 && v <= 1e5 ? null : "longueur_positive_attendue";
|
|
9738
|
+
case "dimension":
|
|
9739
|
+
return v === "hug" || v === "fill" || fini(v) && v >= 0 && v <= 1e5 ? null : "hug_fill_ou_longueur_attendu";
|
|
9740
|
+
case "padding":
|
|
9741
|
+
if (fini(v) && v >= 0) return null;
|
|
9742
|
+
if (Array.isArray(v) && (v.length === 2 || v.length === 4) && v.every((x) => fini(x) && x >= 0)) return null;
|
|
9743
|
+
return "padding_nombre_ou_liste_2_4";
|
|
9744
|
+
case "rayon":
|
|
9745
|
+
if (fini(v) && v >= 0) return null;
|
|
9746
|
+
if (Array.isArray(v) && v.length === 4 && v.every((x) => fini(x) && x >= 0)) return null;
|
|
9747
|
+
return "rayon_nombre_ou_liste_4";
|
|
9748
|
+
case "opacite":
|
|
9749
|
+
return fini(v) && v >= 0 && v <= 1 ? null : "opacite_0_1";
|
|
9750
|
+
case "couleur":
|
|
9751
|
+
return isColor(v) ? null : "couleur_invalide";
|
|
9752
|
+
case "remplissage":
|
|
9753
|
+
if (isColor(v)) return null;
|
|
9754
|
+
if (v && typeof v === "object" && v.type === "linear") {
|
|
9755
|
+
const cles = Object.keys(v).filter((k) => !["type", "angle", "stops"].includes(k));
|
|
9756
|
+
if (cles.length) return `champ_inconnu (${cles[0]})`;
|
|
9757
|
+
if (!fini(v.angle)) return "angle_attendu";
|
|
9758
|
+
if (!Array.isArray(v.stops) || v.stops.length < 2 || v.stops.length > 8) return "2_a_8_arrets";
|
|
9759
|
+
for (const s of v.stops) if (!s || !isColor(s.color) || !fini(s.at) || s.at < 0 || s.at > 1 || Object.keys(s).length !== 2) return "arret_invalide";
|
|
9760
|
+
return null;
|
|
9761
|
+
}
|
|
9762
|
+
return "couleur_ou_degrade_attendu";
|
|
9763
|
+
case "trait":
|
|
9764
|
+
if (v && typeof v === "object" && isColor(v.color) && fini(v.width) && v.width >= 0 && v.width <= 100 && Object.keys(v).length === 2) return null;
|
|
9765
|
+
return "trait_{color,width}_attendu";
|
|
9766
|
+
case "ombres":
|
|
9767
|
+
if (!Array.isArray(v) || v.length > 4) return "liste_de_4_ombres_max";
|
|
9768
|
+
for (const o of v) {
|
|
9769
|
+
if (!o || typeof o !== "object") return "ombre_invalide";
|
|
9770
|
+
const cles = Object.keys(o).filter((k) => !["x", "y", "blur", "spread", "color", "inset"].includes(k));
|
|
9771
|
+
if (cles.length) return `champ_inconnu (${cles[0]})`;
|
|
9772
|
+
if (![o.x, o.y, o.blur].every(fini) || !isColor(o.color) || o.spread !== void 0 && !fini(o.spread) || o.inset !== void 0 && typeof o.inset !== "boolean") return "ombre_invalide";
|
|
9773
|
+
}
|
|
9774
|
+
return null;
|
|
9775
|
+
case "texte":
|
|
9776
|
+
return typeof v === "string" && v.length <= 2e4 ? null : "texte_attendu";
|
|
9777
|
+
case "police":
|
|
9778
|
+
return typeof v === "string" && POLICE.test(v) ? null : "nom_de_police_invalide";
|
|
9779
|
+
case "graisse":
|
|
9780
|
+
return Number.isInteger(v) && v >= 100 && v <= 900 && v % 100 === 0 ? null : "graisse_100_a_900";
|
|
9781
|
+
case "interligne":
|
|
9782
|
+
return fini(v) && v > 0 && v <= 10 ? null : "interligne_0_10";
|
|
9783
|
+
case "source":
|
|
9784
|
+
return typeof v === "string" && SOURCE.test(v) ? null : "source_asset:<id>_attendue";
|
|
9785
|
+
default:
|
|
9786
|
+
return "regle_inconnue";
|
|
9787
|
+
}
|
|
9788
|
+
}
|
|
9789
|
+
function verifierGroupe(groupe, objet, chemin, erreurs) {
|
|
9790
|
+
if (objet === void 0) return;
|
|
9791
|
+
if (!objet || typeof objet !== "object" || Array.isArray(objet)) {
|
|
9792
|
+
erreurs.push({ path: chemin, reason: "objet_attendu" });
|
|
9793
|
+
return;
|
|
9794
|
+
}
|
|
9795
|
+
const regles = CHAMPS[groupe];
|
|
9796
|
+
for (const [cle, valeur] of Object.entries(objet)) {
|
|
9797
|
+
if (!(cle in regles)) {
|
|
9798
|
+
erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
|
|
9799
|
+
continue;
|
|
9800
|
+
}
|
|
9801
|
+
if (valeur === null && ["stroke", "shadow"].includes(cle)) continue;
|
|
9802
|
+
const motif = verifierValeur(regles[cle], valeur);
|
|
9803
|
+
if (motif) erreurs.push({ path: `${chemin}.${cle}`, reason: motif });
|
|
9804
|
+
}
|
|
9805
|
+
}
|
|
9806
|
+
function validateNode(node4, chemin = "node") {
|
|
9807
|
+
const erreurs = [];
|
|
9808
|
+
if (!node4 || typeof node4 !== "object" || Array.isArray(node4)) return [{ path: chemin, reason: "objet_attendu" }];
|
|
9809
|
+
for (const cle of Object.keys(node4)) if (!CHAMPS_NOEUD.has(cle)) erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
|
|
9810
|
+
if (!NODE_TYPES.includes(node4.type)) erreurs.push({ path: `${chemin}.type`, reason: `type_inconnu (${NODE_TYPES.join(", ")})` });
|
|
9811
|
+
if (typeof node4.name !== "string" || !node4.name.trim() || node4.name.length > 120) erreurs.push({ path: `${chemin}.name`, reason: "nom_1_a_120_caracteres" });
|
|
9812
|
+
if (node4.as !== void 0 && !(TAGS[node4.type] || []).includes(node4.as)) erreurs.push({ path: `${chemin}.as`, reason: "balise_non_permise" });
|
|
9813
|
+
if (node4.alt !== void 0 && (typeof node4.alt !== "string" || node4.alt.length > 500)) erreurs.push({ path: `${chemin}.alt`, reason: "texte_500_max" });
|
|
9814
|
+
for (const groupe of ["layout", "size", "position", "style", "text", "image", "shape"]) verifierGroupe(groupe, node4[groupe], `${chemin}.${groupe}`, erreurs);
|
|
9815
|
+
if (node4.type !== "frame" && node4.layout !== void 0) erreurs.push({ path: `${chemin}.layout`, reason: "seul_un_cadre_a_une_mise_en_page" });
|
|
9816
|
+
if (node4.type !== "text" && node4.text !== void 0) erreurs.push({ path: `${chemin}.text`, reason: "seul_un_texte_a_du_texte" });
|
|
9817
|
+
if (node4.type === "text" && typeof node4.text?.content !== "string") erreurs.push({ path: `${chemin}.text.content`, reason: "texte_attendu" });
|
|
9818
|
+
if (node4.type !== "image" && node4.image !== void 0) erreurs.push({ path: `${chemin}.image`, reason: "seule_une_image_a_une_source" });
|
|
9819
|
+
if (node4.type === "image" && typeof node4.image?.src !== "string") erreurs.push({ path: `${chemin}.image.src`, reason: "source_asset:<id>_attendue" });
|
|
9820
|
+
if (node4.type !== "shape" && node4.shape !== void 0) erreurs.push({ path: `${chemin}.shape`, reason: "seule_une_forme_a_un_genre" });
|
|
9821
|
+
if (CONTENEURS.has(node4.type)) {
|
|
9822
|
+
if (!Array.isArray(node4.children)) erreurs.push({ path: `${chemin}.children`, reason: "liste_attendue" });
|
|
9823
|
+
} else if (node4.children !== void 0) erreurs.push({ path: `${chemin}.children`, reason: "ce_type_n_a_pas_d_enfants" });
|
|
9824
|
+
return erreurs;
|
|
9825
|
+
}
|
|
9826
|
+
function isContainer(node4) {
|
|
9827
|
+
return CONTENEURS.has(node4?.type);
|
|
9828
|
+
}
|
|
9829
|
+
function createDocument() {
|
|
9830
|
+
return { format: FORMAT, version: FORMAT_VERSION, meta: { nextId: 1 }, pages: [{ id: "p_1", name: "Page 1", frames: [] }], nodes: {} };
|
|
9831
|
+
}
|
|
9832
|
+
function validate(doc) {
|
|
9833
|
+
const erreurs = [];
|
|
9834
|
+
const err = (path, reason) => erreurs.push({ path, reason });
|
|
9835
|
+
if (!doc || typeof doc !== "object" || Array.isArray(doc)) return { ok: false, errors: [{ path: "", reason: "objet_attendu" }] };
|
|
9836
|
+
for (const cle of Object.keys(doc)) if (!["format", "version", "meta", "pages", "nodes"].includes(cle)) err(cle, "champ_inconnu");
|
|
9837
|
+
if (doc.format !== FORMAT) err("format", `attendu_${FORMAT}`);
|
|
9838
|
+
if (doc.version !== FORMAT_VERSION) err("version", `version_${FORMAT_VERSION}_attendue`);
|
|
9839
|
+
if (!doc.meta || !Number.isInteger(doc.meta.nextId) || doc.meta.nextId < 1 || Object.keys(doc.meta).length !== 1) err("meta", "meta_{nextId}_attendu");
|
|
9840
|
+
if (!doc.nodes || typeof doc.nodes !== "object" || Array.isArray(doc.nodes)) {
|
|
9841
|
+
err("nodes", "objet_attendu");
|
|
9842
|
+
return { ok: false, errors: erreurs };
|
|
9843
|
+
}
|
|
9844
|
+
if (!Array.isArray(doc.pages) || doc.pages.length === 0) {
|
|
9845
|
+
err("pages", "au_moins_une_page");
|
|
9846
|
+
return { ok: false, errors: erreurs };
|
|
9847
|
+
}
|
|
9848
|
+
const parents = /* @__PURE__ */ new Map();
|
|
9849
|
+
const cite = (id, path) => {
|
|
9850
|
+
if (typeof id !== "string" || !Object.hasOwn(doc.nodes, id)) {
|
|
9851
|
+
err(path, "enfant_inexistant");
|
|
9852
|
+
return;
|
|
9853
|
+
}
|
|
9854
|
+
parents.set(id, (parents.get(id) || 0) + 1);
|
|
9855
|
+
};
|
|
9856
|
+
const idsPages = /* @__PURE__ */ new Set();
|
|
9857
|
+
doc.pages.forEach((p, i) => {
|
|
9858
|
+
const c = `pages[${i}]`;
|
|
9859
|
+
if (!p || typeof p !== "object") return err(c, "objet_attendu");
|
|
9860
|
+
for (const cle of Object.keys(p)) if (!["id", "name", "route", "frames"].includes(cle)) err(`${c}.${cle}`, "champ_inconnu");
|
|
9861
|
+
if (typeof p.id !== "string" || !/^p_[a-z0-9]+$/.test(p.id) || idsPages.has(p.id)) err(`${c}.id`, "id_de_page_invalide_ou_double");
|
|
9862
|
+
idsPages.add(p.id);
|
|
9863
|
+
if (typeof p.name !== "string" || !p.name.trim() || p.name.length > 120) err(`${c}.name`, "nom_1_a_120_caracteres");
|
|
9864
|
+
if (p.route !== void 0 && (typeof p.route !== "string" || !/^\/[a-z0-9\-/[\]]*$/.test(p.route))) err(`${c}.route`, "route_invalide");
|
|
9865
|
+
if (!Array.isArray(p.frames)) return err(`${c}.frames`, "liste_attendue");
|
|
9866
|
+
p.frames.forEach((id, k) => {
|
|
9867
|
+
cite(id, `${c}.frames[${k}]`);
|
|
9868
|
+
if (typeof id === "string" && Object.hasOwn(doc.nodes, id) && doc.nodes[id]?.type !== "frame") {
|
|
9869
|
+
err(`${c}.frames[${k}]`, "une_page_ne_contient_que_des_cadres");
|
|
9870
|
+
}
|
|
9871
|
+
});
|
|
9872
|
+
});
|
|
9873
|
+
const limite = doc.meta?.nextId ?? 1;
|
|
9874
|
+
for (const [id, node4] of Object.entries(doc.nodes)) {
|
|
9875
|
+
const c = `nodes.${id}`;
|
|
9876
|
+
if (!/^n_[0-9a-z]+$/.test(id)) err(c, "id_invalide");
|
|
9877
|
+
else if (parseInt(id.slice(2), 36) >= limite) err(c, "id_au_dela_du_compteur");
|
|
9878
|
+
if (node4?.id !== id) err(`${c}.id`, "id_different_de_la_cle");
|
|
9879
|
+
erreurs.push(...validateNode(node4, c));
|
|
9880
|
+
if (Array.isArray(node4?.children)) node4.children.forEach((enfant, k) => cite(enfant, `${c}.children[${k}]`));
|
|
9881
|
+
}
|
|
9882
|
+
for (const id of Object.keys(doc.nodes)) {
|
|
9883
|
+
const n = parents.get(id) || 0;
|
|
9884
|
+
if (n === 0) err(`nodes.${id}`, "noeud_orphelin");
|
|
9885
|
+
if (n > 1) err(`nodes.${id}`, "noeud_a_plusieurs_parents");
|
|
9886
|
+
}
|
|
9887
|
+
if (erreurs.length) return { ok: false, errors: erreurs };
|
|
9888
|
+
const vus = /* @__PURE__ */ new Set();
|
|
9889
|
+
const pile = doc.pages.flatMap((p) => p.frames);
|
|
9890
|
+
while (pile.length) {
|
|
9891
|
+
const id = pile.pop();
|
|
9892
|
+
vus.add(id);
|
|
9893
|
+
for (const enfant of doc.nodes[id].children || []) pile.push(enfant);
|
|
9894
|
+
}
|
|
9895
|
+
for (const id of Object.keys(doc.nodes)) if (!vus.has(id)) err(`nodes.${id}`, "cycle");
|
|
9896
|
+
return { ok: erreurs.length === 0, errors: erreurs };
|
|
9897
|
+
}
|
|
9898
|
+
function assertValid(doc) {
|
|
9899
|
+
const r = validate(doc);
|
|
9900
|
+
if (!r.ok) throw new StudioError("studio_document_invalid", `Document invalide : ${r.errors[0].path} \u2014 ${r.errors[0].reason}`, { errors: r.errors.slice(0, 20) });
|
|
9901
|
+
return doc;
|
|
9902
|
+
}
|
|
9903
|
+
var ORDRE_NOEUD = ["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"];
|
|
9904
|
+
var ordonner = (objet, ordre) => {
|
|
9905
|
+
const out = {};
|
|
9906
|
+
for (const k of ordre) if (objet[k] !== void 0) out[k] = objet[k];
|
|
9907
|
+
return out;
|
|
9908
|
+
};
|
|
9909
|
+
function canonical(doc) {
|
|
9910
|
+
const nodes = {};
|
|
9911
|
+
const ids = Object.keys(doc.nodes).sort((a, b) => parseInt(a.slice(2), 36) - parseInt(b.slice(2), 36));
|
|
9912
|
+
for (const id of ids) {
|
|
9913
|
+
const n = ordonner(doc.nodes[id], ORDRE_NOEUD);
|
|
9914
|
+
for (const g of Object.keys(CHAMPS)) if (n[g] && typeof n[g] === "object") n[g] = ordonner(n[g], Object.keys(CHAMPS[g]));
|
|
9915
|
+
nodes[id] = n;
|
|
9916
|
+
}
|
|
9917
|
+
return {
|
|
9918
|
+
format: doc.format,
|
|
9919
|
+
version: doc.version,
|
|
9920
|
+
meta: { nextId: doc.meta.nextId },
|
|
9921
|
+
pages: doc.pages.map((p) => ordonner({ ...p, frames: [...p.frames] }, ["id", "name", "route", "frames"])),
|
|
9922
|
+
nodes
|
|
9923
|
+
};
|
|
9924
|
+
}
|
|
9925
|
+
function migrate(doc) {
|
|
9926
|
+
if (doc && doc.version === FORMAT_VERSION) return doc;
|
|
9927
|
+
throw new StudioError("studio_document_invalid", `Version de document non prise en charge : ${doc?.version}`, { errors: [{ path: "version", reason: `version_${FORMAT_VERSION}_attendue` }] });
|
|
9928
|
+
}
|
|
9929
|
+
|
|
9930
|
+
// src/studio/ops.js
|
|
9931
|
+
var GROUPES = /* @__PURE__ */ new Set(["layout", "size", "position", "style", "text", "image", "shape"]);
|
|
9932
|
+
var SIMPLES = /* @__PURE__ */ new Set(["name", "as", "alt"]);
|
|
9933
|
+
var refus = (index, reason, message) => {
|
|
9934
|
+
throw new StudioError("studio_op_invalid", message || `Op\xE9ration ${index} refus\xE9e : ${reason}`, { index, reason });
|
|
9935
|
+
};
|
|
9936
|
+
function nouvelId(doc) {
|
|
9937
|
+
const id = `n_${doc.meta.nextId.toString(36)}`;
|
|
9938
|
+
doc.meta.nextId += 1;
|
|
9939
|
+
return id;
|
|
9940
|
+
}
|
|
9941
|
+
function emplacement(doc, id) {
|
|
9942
|
+
for (const p of doc.pages) {
|
|
9943
|
+
const i = p.frames.indexOf(id);
|
|
9944
|
+
if (i >= 0) return { parent: p.id, liste: p.frames, index: i };
|
|
9945
|
+
}
|
|
9946
|
+
for (const n of Object.values(doc.nodes)) if (n.children) {
|
|
9947
|
+
const i = n.children.indexOf(id);
|
|
9948
|
+
if (i >= 0) return { parent: n.id, liste: n.children, index: i };
|
|
9949
|
+
}
|
|
9950
|
+
return null;
|
|
9951
|
+
}
|
|
9952
|
+
function listeDuParent(doc, parent, type, index) {
|
|
9953
|
+
const page = doc.pages.find((p) => p.id === parent);
|
|
9954
|
+
if (page) {
|
|
9955
|
+
if (type !== "frame") refus(index, "une_page_ne_contient_que_des_cadres");
|
|
9956
|
+
return page.frames;
|
|
9957
|
+
}
|
|
9958
|
+
const n = doc.nodes[parent];
|
|
9959
|
+
if (!n) refus(index, "parent_introuvable");
|
|
9960
|
+
if (!isContainer(n)) refus(index, "le_parent_n_est_pas_un_cadre");
|
|
9961
|
+
return n.children;
|
|
9962
|
+
}
|
|
9963
|
+
function sousArbre(doc, id, acc = {}) {
|
|
9964
|
+
const n = doc.nodes[id];
|
|
9965
|
+
acc[id] = n;
|
|
9966
|
+
for (const e of n.children || []) sousArbre(doc, e, acc);
|
|
9967
|
+
return acc;
|
|
9968
|
+
}
|
|
9969
|
+
function placer(liste, id, index, iop) {
|
|
9970
|
+
const i = index === void 0 ? liste.length : index;
|
|
9971
|
+
if (!Number.isInteger(i) || i < 0 || i > liste.length) refus(iop, "index_hors_limites");
|
|
9972
|
+
liste.splice(i, 0, id);
|
|
9973
|
+
return i;
|
|
9974
|
+
}
|
|
9975
|
+
function aplatir(doc, brut, iop, acc) {
|
|
9976
|
+
if (!brut || typeof brut !== "object" || Array.isArray(brut)) refus(iop, "noeud_objet_attendu");
|
|
9977
|
+
if ("id" in brut) refus(iop, "un_id_ne_se_choisit_pas");
|
|
9978
|
+
const { children, ...reste } = brut;
|
|
9979
|
+
const id = nouvelId(doc);
|
|
9980
|
+
const node4 = { id, ...reste };
|
|
9981
|
+
if (isContainer(node4)) {
|
|
9982
|
+
if (children !== void 0 && !Array.isArray(children)) refus(iop, "children_liste_attendue");
|
|
9983
|
+
node4.children = (children || []).map((c) => aplatir(doc, c, iop, acc));
|
|
9984
|
+
} else if (children !== void 0) refus(iop, "ce_type_n_a_pas_d_enfants");
|
|
9985
|
+
const erreurs = validateNode(node4, "node");
|
|
9986
|
+
if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
|
|
9987
|
+
acc[id] = node4;
|
|
9988
|
+
return id;
|
|
9989
|
+
}
|
|
9990
|
+
function estDescendant(doc, ancetre, id) {
|
|
9991
|
+
const n = doc.nodes[ancetre];
|
|
9992
|
+
return (n?.children || []).some((e) => e === id || estDescendant(doc, e, id));
|
|
9993
|
+
}
|
|
9994
|
+
function lire(node4, path) {
|
|
9995
|
+
const [a, b] = path.split(".");
|
|
9996
|
+
if (b === void 0) return node4[a];
|
|
9997
|
+
return node4[a]?.[b];
|
|
9998
|
+
}
|
|
9999
|
+
function appliquerUne(doc, op, iop, inverses, created, removed) {
|
|
10000
|
+
if (!op || typeof op !== "object") refus(iop, "operation_objet_attendue");
|
|
10001
|
+
switch (op.op) {
|
|
10002
|
+
case "set": {
|
|
10003
|
+
const node4 = doc.nodes[op.id];
|
|
10004
|
+
if (!node4) refus(iop, "noeud_introuvable");
|
|
10005
|
+
if (typeof op.path !== "string") refus(iop, "chemin_attendu");
|
|
10006
|
+
const [a, b, ...trop] = op.path.split(".");
|
|
10007
|
+
if (trop.length || !(SIMPLES.has(a) && b === void 0) && !GROUPES.has(a)) refus(iop, "chemin_non_modifiable");
|
|
10008
|
+
const avant = lire(node4, op.path);
|
|
10009
|
+
const copie2 = structuredClone(node4);
|
|
10010
|
+
if (b === void 0) {
|
|
10011
|
+
if (op.value === void 0) delete copie2[a];
|
|
10012
|
+
else copie2[a] = structuredClone(op.value);
|
|
10013
|
+
} else {
|
|
10014
|
+
const groupe = { ...copie2[a] || {} };
|
|
10015
|
+
if (op.value === void 0) delete groupe[b];
|
|
10016
|
+
else groupe[b] = structuredClone(op.value);
|
|
10017
|
+
if (Object.keys(groupe).length) copie2[a] = groupe;
|
|
10018
|
+
else delete copie2[a];
|
|
10019
|
+
}
|
|
10020
|
+
const erreurs = validateNode(copie2, op.id);
|
|
10021
|
+
if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
|
|
10022
|
+
doc.nodes[op.id] = copie2;
|
|
10023
|
+
inverses.push({ op: "set", id: op.id, path: op.path, value: avant === void 0 ? void 0 : structuredClone(avant) });
|
|
10024
|
+
return;
|
|
10025
|
+
}
|
|
10026
|
+
case "insert": {
|
|
10027
|
+
const acc = {};
|
|
10028
|
+
const racine = aplatir(doc, op.node, iop, acc);
|
|
10029
|
+
const liste = listeDuParent(doc, op.parent, acc[racine].type, iop);
|
|
10030
|
+
Object.assign(doc.nodes, acc);
|
|
10031
|
+
placer(liste, racine, op.index, iop);
|
|
10032
|
+
created.push(...Object.keys(acc));
|
|
10033
|
+
inverses.push({ op: "remove", id: racine });
|
|
10034
|
+
return;
|
|
10035
|
+
}
|
|
10036
|
+
case "move": {
|
|
10037
|
+
const node4 = doc.nodes[op.id];
|
|
10038
|
+
if (!node4) refus(iop, "noeud_introuvable");
|
|
10039
|
+
if (op.parent === op.id || estDescendant(doc, op.id, op.parent)) refus(iop, "deplacement_dans_son_propre_descendant");
|
|
10040
|
+
const ici = emplacement(doc, op.id);
|
|
10041
|
+
const liste = listeDuParent(doc, op.parent, node4.type, iop);
|
|
10042
|
+
ici.liste.splice(ici.index, 1);
|
|
10043
|
+
placer(liste, op.id, op.index, iop);
|
|
10044
|
+
inverses.push({ op: "move", id: op.id, parent: ici.parent, index: ici.index });
|
|
10045
|
+
return;
|
|
10046
|
+
}
|
|
10047
|
+
case "remove": {
|
|
10048
|
+
if (!doc.nodes[op.id]) refus(iop, "noeud_introuvable");
|
|
10049
|
+
const ici = emplacement(doc, op.id);
|
|
10050
|
+
const arbre = sousArbre(doc, op.id);
|
|
10051
|
+
ici.liste.splice(ici.index, 1);
|
|
10052
|
+
for (const id of Object.keys(arbre)) delete doc.nodes[id];
|
|
10053
|
+
removed.push(...Object.keys(arbre));
|
|
10054
|
+
inverses.push({ op: "restore", parent: ici.parent, index: ici.index, root: op.id, nodes: arbre });
|
|
10055
|
+
return;
|
|
10056
|
+
}
|
|
10057
|
+
case "restore": {
|
|
10058
|
+
if (!op.__interne) refus(iop, "operation_inconnue");
|
|
10059
|
+
const liste = listeDuParent(doc, op.parent, op.nodes[op.root].type, iop);
|
|
10060
|
+
Object.assign(doc.nodes, structuredClone(op.nodes));
|
|
10061
|
+
placer(liste, op.root, op.index, iop);
|
|
10062
|
+
inverses.push({ op: "remove", id: op.root });
|
|
10063
|
+
return;
|
|
10064
|
+
}
|
|
10065
|
+
default:
|
|
10066
|
+
refus(iop, "operation_inconnue");
|
|
10067
|
+
}
|
|
10068
|
+
}
|
|
10069
|
+
function applyOps(doc, ops, { internal = false } = {}) {
|
|
10070
|
+
if (!Array.isArray(ops)) throw new StudioError("studio_op_invalid", "Un lot d'op\xE9rations est une liste.", { index: -1, reason: "liste_attendue" });
|
|
10071
|
+
const copie2 = structuredClone(doc);
|
|
10072
|
+
const inverses = [];
|
|
10073
|
+
const created = [];
|
|
10074
|
+
const removed = [];
|
|
10075
|
+
ops.forEach((op, i) => appliquerUne(copie2, internal && op?.op === "restore" ? { ...op, __interne: true } : op, i, inverses, created, removed));
|
|
10076
|
+
return { doc: copie2, inverse: inverses.reverse(), created, removed };
|
|
10077
|
+
}
|
|
10078
|
+
|
|
10079
|
+
// src/studio/style.js
|
|
10080
|
+
var px = (v) => `${+v.toFixed(3)}px`;
|
|
10081
|
+
var ALIGN = { start: "flex-start", center: "center", end: "flex-end", stretch: "stretch" };
|
|
10082
|
+
var JUSTIFY = { start: "flex-start", center: "center", end: "flex-end", between: "space-between" };
|
|
10083
|
+
function remplissage(f) {
|
|
10084
|
+
if (typeof f === "string") return f;
|
|
10085
|
+
return `linear-gradient(${+f.angle.toFixed(3)}deg, ${f.stops.map((s) => `${s.color} ${+(s.at * 100).toFixed(3)}%`).join(", ")})`;
|
|
10086
|
+
}
|
|
10087
|
+
function padding(p) {
|
|
10088
|
+
if (typeof p === "number") return px(p);
|
|
10089
|
+
return p.map(px).join(" ");
|
|
10090
|
+
}
|
|
10091
|
+
function taille(decl, axe, v, parent) {
|
|
10092
|
+
if (v === void 0) return;
|
|
10093
|
+
const prop = axe === "w" ? "width" : "height";
|
|
10094
|
+
const mode = parent?.layout?.mode;
|
|
10095
|
+
const dir = parent?.layout?.direction || "row";
|
|
10096
|
+
const principal = mode === "flex" && (axe === "w" && dir === "row" || axe === "h" && dir === "column");
|
|
10097
|
+
if (typeof v === "number") {
|
|
10098
|
+
decl.push([prop, px(v)]);
|
|
10099
|
+
if (principal) decl.push(["flex-shrink", "0"]);
|
|
10100
|
+
} else if (v === "fill") {
|
|
10101
|
+
if (principal) decl.push(["flex", "1 1 0"], [axe === "w" ? "min-width" : "min-height", "0"]);
|
|
10102
|
+
else if (mode === "flex") decl.push(["align-self", "stretch"]);
|
|
10103
|
+
else decl.push([prop, "100%"]);
|
|
10104
|
+
} else if (v === "hug") {
|
|
10105
|
+
decl.push([prop, "fit-content"]);
|
|
10106
|
+
}
|
|
10107
|
+
}
|
|
10108
|
+
function nodeCss(node4, parent = null) {
|
|
10109
|
+
const d = [];
|
|
10110
|
+
const pos = node4.position;
|
|
10111
|
+
if (parent?.layout?.mode === "free" || pos?.absolute) {
|
|
10112
|
+
d.push(["position", "absolute"], ["left", px(pos?.x ?? 0)], ["top", px(pos?.y ?? 0)]);
|
|
10113
|
+
}
|
|
10114
|
+
const l = node4.layout;
|
|
10115
|
+
if (node4.type === "frame") {
|
|
10116
|
+
if (l?.mode === "grid") {
|
|
10117
|
+
d.push(["display", "grid"], ["grid-template-columns", `repeat(${l.columns || 2}, minmax(0, 1fr))`]);
|
|
10118
|
+
} else if (l?.mode === "free") {
|
|
10119
|
+
if (!d.some(([p]) => p === "position")) d.push(["position", "relative"]);
|
|
10120
|
+
} else {
|
|
10121
|
+
d.push(["display", "flex"], ["flex-direction", l?.direction || "column"]);
|
|
10122
|
+
if (l?.wrap) d.push(["flex-wrap", "wrap"]);
|
|
10123
|
+
if (l?.align) d.push(["align-items", ALIGN[l.align]]);
|
|
10124
|
+
if (l?.justify) d.push(["justify-content", JUSTIFY[l.justify]]);
|
|
10125
|
+
}
|
|
10126
|
+
if (l?.gap !== void 0 && l.mode !== "free") d.push(["gap", px(l.gap)]);
|
|
10127
|
+
if (l?.padding !== void 0) d.push(["padding", padding(l.padding)]);
|
|
10128
|
+
}
|
|
10129
|
+
taille(d, "w", node4.size?.w, parent);
|
|
10130
|
+
taille(d, "h", node4.size?.h, parent);
|
|
10131
|
+
for (const [k, prop] of [["minW", "min-width"], ["minH", "min-height"], ["maxW", "max-width"], ["maxH", "max-height"]]) {
|
|
10132
|
+
if (node4.size?.[k] !== void 0) d.push([prop, px(node4.size[k])]);
|
|
10133
|
+
}
|
|
10134
|
+
const s = node4.style || {};
|
|
10135
|
+
if (s.fill !== void 0 && node4.type !== "text") d.push(["background", remplissage(s.fill)]);
|
|
10136
|
+
if (s.stroke) d.push(["border", `${px(s.stroke.width)} solid ${s.stroke.color}`]);
|
|
10137
|
+
if (node4.type === "shape" && node4.shape?.kind === "ellipse") d.push(["border-radius", "50%"]);
|
|
10138
|
+
else if (s.radius !== void 0) d.push(["border-radius", typeof s.radius === "number" ? px(s.radius) : s.radius.map(px).join(" ")]);
|
|
10139
|
+
if (s.shadow?.length) d.push(["box-shadow", s.shadow.map((o) => `${o.inset ? "inset " : ""}${px(o.x)} ${px(o.y)} ${px(o.blur)} ${px(o.spread || 0)} ${o.color}`).join(", ")]);
|
|
10140
|
+
if (s.opacity !== void 0 && s.opacity !== 1) d.push(["opacity", String(s.opacity)]);
|
|
10141
|
+
if (s.clip) d.push(["overflow", "hidden"]);
|
|
10142
|
+
if (node4.type === "shape" && node4.shape?.kind === "line") d.push(["height", "0"], ["border-top", `${px(s.stroke?.width ?? 1)} solid ${s.stroke?.color ?? "#000000"}`]);
|
|
10143
|
+
const t = node4.text;
|
|
10144
|
+
if (node4.type === "text") {
|
|
10145
|
+
if (t.font) d.push(["font-family", `"${t.font}", sans-serif`]);
|
|
10146
|
+
if (t.size !== void 0) d.push(["font-size", px(t.size)]);
|
|
10147
|
+
if (t.weight !== void 0) d.push(["font-weight", String(t.weight)]);
|
|
10148
|
+
if (t.lineHeight !== void 0) d.push(["line-height", String(t.lineHeight)]);
|
|
10149
|
+
if (t.letterSpacing !== void 0) d.push(["letter-spacing", px(t.letterSpacing)]);
|
|
10150
|
+
if (t.align) d.push(["text-align", t.align]);
|
|
10151
|
+
if (t.transform && t.transform !== "none") d.push(["text-transform", t.transform]);
|
|
10152
|
+
d.push(["color", t.color || "#000000"]);
|
|
10153
|
+
if (s.fill !== void 0) d.push(["background", remplissage(s.fill)]);
|
|
10154
|
+
d.push(["white-space", "pre-wrap"]);
|
|
10155
|
+
}
|
|
10156
|
+
if (node4.type === "image") d.push(["display", "block"], ["object-fit", node4.image.fit || "cover"]);
|
|
10157
|
+
return d;
|
|
10158
|
+
}
|
|
10159
|
+
function tagOf(node4) {
|
|
10160
|
+
return node4.as || DEFAULT_TAG[node4.type];
|
|
10161
|
+
}
|
|
10162
|
+
var BASE_CSS = "*,*::before,*::after{box-sizing:border-box;margin:0}";
|
|
10163
|
+
function parentsOf(doc) {
|
|
10164
|
+
const m = /* @__PURE__ */ new Map();
|
|
10165
|
+
for (const p of doc.pages) for (const id of p.frames) m.set(id, null);
|
|
10166
|
+
for (const n of Object.values(doc.nodes)) for (const e of n.children || []) m.set(e, n);
|
|
10167
|
+
return m;
|
|
10168
|
+
}
|
|
10169
|
+
|
|
10170
|
+
// src/studio/check.js
|
|
10171
|
+
function parseColor(c) {
|
|
10172
|
+
if (!isColor(c)) return null;
|
|
10173
|
+
const s = c.trim().toLowerCase();
|
|
10174
|
+
if (s === "transparent") return [0, 0, 0, 0];
|
|
10175
|
+
if (s.startsWith("#")) {
|
|
10176
|
+
let h = s.slice(1);
|
|
10177
|
+
if (h.length <= 4) h = [...h].map((x) => x + x).join("");
|
|
10178
|
+
const n = (i) => parseInt(h.slice(i, i + 2), 16);
|
|
10179
|
+
return [n(0), n(2), n(4), h.length === 8 ? n(6) / 255 : 1];
|
|
10180
|
+
}
|
|
10181
|
+
const v = s.match(/[\d.]+/g).map(Number);
|
|
10182
|
+
return [v[0], v[1], v[2], v[3] ?? 1];
|
|
10183
|
+
}
|
|
10184
|
+
function luminance([r, g, b]) {
|
|
10185
|
+
const lin = (x) => {
|
|
10186
|
+
x /= 255;
|
|
10187
|
+
return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
|
|
10188
|
+
};
|
|
10189
|
+
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
|
|
10190
|
+
}
|
|
10191
|
+
var melange = (dessus, fond) => [0, 1, 2].map((i) => dessus[i] * dessus[3] + fond[i] * (1 - dessus[3])).concat(1);
|
|
10192
|
+
function contrastRatio(a, b) {
|
|
10193
|
+
const [l1, l2] = [luminance(a), luminance(b)].sort((x, y) => y - x);
|
|
10194
|
+
return (l1 + 0.05) / (l2 + 0.05);
|
|
10195
|
+
}
|
|
10196
|
+
function fondsSous(doc, id, parents) {
|
|
10197
|
+
const couches = [];
|
|
10198
|
+
let n = doc.nodes[id];
|
|
10199
|
+
if (n.type === "text" && n.style?.fill !== void 0) couches.push(n.style.fill);
|
|
10200
|
+
for (let p = parents.get(id); p; p = parents.get(p.id)) if (p.style?.fill !== void 0) couches.push(p.style.fill);
|
|
10201
|
+
let fonds = [[255, 255, 255, 1]];
|
|
10202
|
+
for (const f of couches.reverse()) {
|
|
10203
|
+
const couleurs = typeof f === "string" ? [parseColor(f)] : f.stops.map((s) => parseColor(s.color));
|
|
10204
|
+
fonds = couleurs.flatMap((c) => fonds.map((base2) => melange(c, base2)));
|
|
10205
|
+
}
|
|
10206
|
+
return fonds;
|
|
10207
|
+
}
|
|
10208
|
+
function check(doc) {
|
|
10209
|
+
const issues = [];
|
|
10210
|
+
const parents = parentsOf(doc);
|
|
10211
|
+
for (const n of Object.values(doc.nodes)) {
|
|
10212
|
+
if (n.type === "text") {
|
|
10213
|
+
const couleur = parseColor(n.text.color || "#000000");
|
|
10214
|
+
const grand = (n.text.size ?? 16) >= 24 || (n.text.size ?? 16) >= 18.66 && (n.text.weight ?? 400) >= 700;
|
|
10215
|
+
const requis = grand ? 3 : 4.5;
|
|
10216
|
+
let pire = null;
|
|
10217
|
+
for (const fond of fondsSous(doc, n.id, parents)) {
|
|
10218
|
+
const ratio = contrastRatio(melange(couleur, fond), fond);
|
|
10219
|
+
if (!pire || ratio < pire.ratio) pire = { ratio, fond };
|
|
10220
|
+
}
|
|
10221
|
+
if (pire && pire.ratio < requis) {
|
|
10222
|
+
const hex = (c) => `#${c.slice(0, 3).map((x) => Math.round(x).toString(16).padStart(2, "0")).join("")}`;
|
|
10223
|
+
issues.push({ rule: "contrast", severity: "error", node: n.id, name: n.name, detail: { ratio: Math.floor(pire.ratio * 100) / 100, required: requis, fg: n.text.color || "#000000", bg: hex(pire.fond) } });
|
|
10224
|
+
}
|
|
10225
|
+
}
|
|
10226
|
+
if (n.type === "frame" && n.children.length === 0 && n.style?.fill === void 0 && !n.style?.stroke) {
|
|
10227
|
+
issues.push({ rule: "empty-frame", severity: "warning", node: n.id, name: n.name });
|
|
10228
|
+
}
|
|
10229
|
+
if (n.type === "image" && !n.alt) issues.push({ rule: "image-alt", severity: "warning", node: n.id, name: n.name });
|
|
10230
|
+
}
|
|
10231
|
+
return { issues };
|
|
10232
|
+
}
|
|
10233
|
+
|
|
10234
|
+
// src/studio/emit/html.js
|
|
10235
|
+
var ECHAPPE = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
|
|
10236
|
+
var escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ECHAPPE[c]);
|
|
10237
|
+
function slug(nom) {
|
|
10238
|
+
const s = String(nom).normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
|
|
10239
|
+
return /^[a-z]/.test(s) ? s : `n-${s || "noeud"}`;
|
|
10240
|
+
}
|
|
10241
|
+
function classNames(doc, page) {
|
|
10242
|
+
const prises = /* @__PURE__ */ new Set();
|
|
10243
|
+
const classes = /* @__PURE__ */ new Map();
|
|
10244
|
+
const unique = (base2) => {
|
|
10245
|
+
let c = base2;
|
|
10246
|
+
let k = 2;
|
|
10247
|
+
while (prises.has(c)) c = `${base2}-${k++}`;
|
|
10248
|
+
prises.add(c);
|
|
10249
|
+
return c;
|
|
10250
|
+
};
|
|
10251
|
+
const visiter = (id, racine) => {
|
|
10252
|
+
const n = doc.nodes[id];
|
|
10253
|
+
const c = racine ? unique(`${racine}__${slug(n.name)}`) : unique(slug(n.name));
|
|
10254
|
+
classes.set(id, c);
|
|
10255
|
+
for (const e of n.children || []) visiter(e, racine || c);
|
|
10256
|
+
};
|
|
10257
|
+
for (const id of page.frames) visiter(id, null);
|
|
10258
|
+
return classes;
|
|
10259
|
+
}
|
|
10260
|
+
function emitHtml(doc, { page: pageId, assets = {}, title, lang = "fr" } = {}) {
|
|
10261
|
+
const page = pageId ? doc.pages.find((p) => p.id === pageId) : doc.pages[0];
|
|
10262
|
+
if (!page) throw new StudioError("studio_page_not_found", `Page introuvable : ${pageId}`, void 0, 404);
|
|
10263
|
+
const parents = parentsOf(doc);
|
|
10264
|
+
const classes = classNames(doc, page);
|
|
10265
|
+
const warnings = [];
|
|
10266
|
+
const regles = [BASE_CSS];
|
|
10267
|
+
const html = (id, profondeur) => {
|
|
10268
|
+
const n = doc.nodes[id];
|
|
10269
|
+
const c = classes.get(id);
|
|
10270
|
+
const decl = nodeCss(n, parents.get(id));
|
|
10271
|
+
if (decl.length) regles.push(`.${c}{${decl.map(([p, v]) => `${p}:${v}`).join(";")}}`);
|
|
10272
|
+
const tag = tagOf(n);
|
|
10273
|
+
const pad2 = " ".repeat(profondeur);
|
|
10274
|
+
if (n.type === "image") {
|
|
10275
|
+
const asset = n.image.src.slice("asset:".length);
|
|
10276
|
+
if (n.alt === void 0) warnings.push(`image-alt : \xAB ${n.name} \xBB n'a pas de texte alternatif`);
|
|
10277
|
+
return `${pad2}<img class="${c}" src="${escapeHtml(assets[asset] || `assets/${asset}`)}" alt="${escapeHtml(n.alt ?? "")}">`;
|
|
10278
|
+
}
|
|
10279
|
+
if (n.type === "text") return `${pad2}<${tag} class="${c}">${escapeHtml(n.text.content)}</${tag}>`;
|
|
10280
|
+
const enfants = (n.children || []).map((e) => html(e, profondeur + 1));
|
|
10281
|
+
return enfants.length ? `${pad2}<${tag} class="${c}">
|
|
10282
|
+
${enfants.join("\n")}
|
|
10283
|
+
${pad2}</${tag}>` : `${pad2}<${tag} class="${c}"></${tag}>`;
|
|
10284
|
+
};
|
|
10285
|
+
const corps = page.frames.map((id) => html(id, 2)).join("\n");
|
|
10286
|
+
const index = `<!doctype html>
|
|
10287
|
+
<html lang="${escapeHtml(lang)}">
|
|
10288
|
+
<head>
|
|
10289
|
+
<meta charset="utf-8">
|
|
10290
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
10291
|
+
<title>${escapeHtml(title || page.name)}</title>
|
|
10292
|
+
<link rel="stylesheet" href="styles.css">
|
|
10293
|
+
</head>
|
|
10294
|
+
<body>
|
|
10295
|
+
${corps}
|
|
10296
|
+
</body>
|
|
10297
|
+
</html>
|
|
10298
|
+
`;
|
|
10299
|
+
const css = `${regles.join("\n")}
|
|
10300
|
+
`;
|
|
10301
|
+
const octets = (s) => new TextEncoder().encode(s).length;
|
|
10302
|
+
return {
|
|
10303
|
+
target: "html",
|
|
10304
|
+
files: [
|
|
10305
|
+
{ path: "index.html", content: index, bytes: octets(index) },
|
|
10306
|
+
{ path: "styles.css", content: css, bytes: octets(css) }
|
|
10307
|
+
],
|
|
10308
|
+
warnings
|
|
10309
|
+
};
|
|
10310
|
+
}
|
|
10311
|
+
|
|
10312
|
+
// src/studio/render.js
|
|
10313
|
+
function renderNode(doc, nodeId, { document: d = globalThis.document, assets = {}, parents = parentsOf(doc) } = {}) {
|
|
10314
|
+
if (!d || typeof d.createElement !== "function") {
|
|
10315
|
+
throw new StudioError("studio_render_unavailable", "Le rendu demande un navigateur (aucun DOM ici).");
|
|
10316
|
+
}
|
|
10317
|
+
const creer = (id) => {
|
|
10318
|
+
const n = doc.nodes[id];
|
|
10319
|
+
const el = d.createElement(tagOf(n));
|
|
10320
|
+
el.setAttribute("data-node-id", id);
|
|
10321
|
+
for (const [prop, valeur] of nodeCss(n, parents.get(id))) el.style.setProperty(prop, valeur);
|
|
10322
|
+
if (n.type === "image") {
|
|
10323
|
+
const asset = n.image.src.slice("asset:".length);
|
|
10324
|
+
el.setAttribute("src", assets[asset] || `assets/${asset}`);
|
|
10325
|
+
el.setAttribute("alt", n.alt ?? "");
|
|
10326
|
+
} else if (n.type === "text") {
|
|
10327
|
+
el.textContent = n.text.content;
|
|
10328
|
+
} else {
|
|
10329
|
+
for (const e of n.children || []) el.appendChild(creer(e));
|
|
10330
|
+
}
|
|
10331
|
+
return el;
|
|
10332
|
+
};
|
|
10333
|
+
if (!doc.nodes[nodeId]) throw new StudioError("studio_node_not_found", `N\u0153ud introuvable : ${nodeId}`, void 0, 404);
|
|
10334
|
+
return creer(nodeId);
|
|
10335
|
+
}
|
|
10336
|
+
|
|
10337
|
+
// src/studio/raster.js
|
|
10338
|
+
var XHTML = "http://www.w3.org/1999/xhtml";
|
|
10339
|
+
async function enData(url) {
|
|
10340
|
+
const reponse = await fetch(url);
|
|
10341
|
+
if (!reponse.ok) throw new StudioError("studio_asset_unavailable", `Ressource illisible pour l'export : ${url} (${reponse.status})`);
|
|
10342
|
+
const blob = await reponse.blob();
|
|
10343
|
+
return await new Promise((ok, ko) => {
|
|
10344
|
+
const f = new FileReader();
|
|
10345
|
+
f.onload = () => ok(f.result);
|
|
10346
|
+
f.onerror = ko;
|
|
10347
|
+
f.readAsDataURL(blob);
|
|
10348
|
+
});
|
|
10349
|
+
}
|
|
10350
|
+
async function policesIncorporees(d) {
|
|
10351
|
+
const regles = [];
|
|
10352
|
+
for (const feuille of d.styleSheets) {
|
|
10353
|
+
let liste;
|
|
10354
|
+
try {
|
|
10355
|
+
liste = feuille.cssRules;
|
|
10356
|
+
} catch {
|
|
10357
|
+
continue;
|
|
10358
|
+
}
|
|
10359
|
+
for (const r of liste) {
|
|
10360
|
+
if (r.type !== 5) continue;
|
|
10361
|
+
let css = r.cssText;
|
|
10362
|
+
const base2 = feuille.href || d.baseURI;
|
|
10363
|
+
for (const [, brut] of css.matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)/g)) {
|
|
10364
|
+
if (brut.startsWith("data:")) continue;
|
|
10365
|
+
css = css.replace(brut, await enData(new URL(brut, base2).href));
|
|
10366
|
+
}
|
|
10367
|
+
regles.push(css);
|
|
10368
|
+
}
|
|
10369
|
+
}
|
|
10370
|
+
return regles.join("\n");
|
|
10371
|
+
}
|
|
10372
|
+
function figerLignes(racine, d) {
|
|
10373
|
+
for (const el of racine.querySelectorAll("[data-node-id]")) {
|
|
10374
|
+
const texte = el.firstChild;
|
|
10375
|
+
if (!texte || texte.nodeType !== 3 || el.childNodes.length !== 1) continue;
|
|
10376
|
+
const t = texte.textContent;
|
|
10377
|
+
const r = d.createRange();
|
|
10378
|
+
let haut = null;
|
|
10379
|
+
let sortie = "";
|
|
10380
|
+
for (let i = 0; i < t.length; i++) {
|
|
10381
|
+
r.setStart(texte, i);
|
|
10382
|
+
r.setEnd(texte, i + 1);
|
|
10383
|
+
const rect = r.getClientRects()[0];
|
|
10384
|
+
if (rect && haut !== null && rect.top > haut + 1 && t[i] !== " " && t[i] !== "\n") sortie = `${sortie.replace(/ +$/, "")}
|
|
10385
|
+
`;
|
|
10386
|
+
if (rect) haut = rect.top;
|
|
10387
|
+
sortie += t[i];
|
|
10388
|
+
}
|
|
10389
|
+
texte.textContent = sortie;
|
|
10390
|
+
el.style.setProperty("white-space", "pre");
|
|
10391
|
+
}
|
|
10392
|
+
}
|
|
10393
|
+
async function renderPng(doc, { frame, scale = 1, assets = {}, document: d = globalThis.document } = {}) {
|
|
10394
|
+
const W = globalThis;
|
|
10395
|
+
if (!d?.body || typeof W.XMLSerializer !== "function" || typeof W.Image !== "function" || typeof W.fetch !== "function") {
|
|
10396
|
+
throw new StudioError("studio_render_unavailable", "L'export d'image se fait dans un navigateur (aucun DOM ici).");
|
|
10397
|
+
}
|
|
10398
|
+
if (![1, 2, 3, 4].includes(scale)) throw new StudioError("studio_render_invalid", "scale vaut 1, 2, 3 ou 4.", { reason: "scale_1_a_4" });
|
|
10399
|
+
const id = doc.nodes[frame]?.type === "frame" ? frame : Object.values(doc.nodes).find((n) => n.type === "frame" && n.name === frame)?.id;
|
|
10400
|
+
if (!id) throw new StudioError("studio_node_not_found", `Cadre introuvable : ${frame}`, void 0, 404);
|
|
10401
|
+
const hote = d.createElement("div");
|
|
10402
|
+
hote.setAttribute("aria-hidden", "true");
|
|
10403
|
+
hote.setAttribute("data-studio-raster", "");
|
|
10404
|
+
hote.style.cssText = "position:fixed;left:-100000px;top:0;contain:layout style;pointer-events:none";
|
|
10405
|
+
const base2 = d.createElement("style");
|
|
10406
|
+
base2.textContent = "[data-studio-raster] *,[data-studio-raster] *::before,[data-studio-raster] *::after{box-sizing:border-box;margin:0}";
|
|
10407
|
+
hote.append(base2, renderNode(doc, id, { document: d, assets }));
|
|
10408
|
+
d.body.appendChild(hote);
|
|
10409
|
+
try {
|
|
10410
|
+
const el = hote.lastChild;
|
|
10411
|
+
await d.fonts?.ready;
|
|
10412
|
+
await Promise.all([...el.querySelectorAll("img")].map((img) => img.decode().catch(() => {
|
|
10413
|
+
})));
|
|
10414
|
+
figerLignes(el, d);
|
|
10415
|
+
const rect = el.getBoundingClientRect();
|
|
10416
|
+
const width = Math.ceil(rect.width);
|
|
10417
|
+
const height = Math.ceil(rect.height);
|
|
10418
|
+
const copie2 = el.cloneNode(true);
|
|
10419
|
+
for (const img of copie2.querySelectorAll("img")) img.setAttribute("src", await enData(new URL(img.getAttribute("src"), d.baseURI).href));
|
|
10420
|
+
const polices = await policesIncorporees(d);
|
|
10421
|
+
const xhtml = new W.XMLSerializer().serializeToString(copie2);
|
|
10422
|
+
const style = `${BASE_CSS}
|
|
10423
|
+
${polices}`.replace(/]]>/g, "]]>");
|
|
10424
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width * scale}" height="${height * scale}" viewBox="0 0 ${width} ${height}"><foreignObject x="0" y="0" width="${width}" height="${height}"><div xmlns="${XHTML}"><style><![CDATA[${style}]]></style>${xhtml}</div></foreignObject></svg>`;
|
|
10425
|
+
const image = new W.Image();
|
|
10426
|
+
image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
|
10427
|
+
await image.decode();
|
|
10428
|
+
const canvas = d.createElement("canvas");
|
|
10429
|
+
canvas.width = Math.round(width * scale);
|
|
10430
|
+
canvas.height = Math.round(height * scale);
|
|
10431
|
+
canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
|
|
10432
|
+
const blob = await new Promise((ok) => canvas.toBlob(ok, "image/png"));
|
|
10433
|
+
return { bytes: new Uint8Array(await blob.arrayBuffer()), mime: "image/png", width: canvas.width, height: canvas.height };
|
|
10434
|
+
} finally {
|
|
10435
|
+
hote.remove();
|
|
10436
|
+
}
|
|
10437
|
+
}
|
|
10438
|
+
|
|
10439
|
+
// src/studio/targets.js
|
|
10440
|
+
var TARGETS = Object.freeze([
|
|
10441
|
+
Object.freeze({ target: "html", status: "available" }),
|
|
10442
|
+
Object.freeze({ target: "email", status: "planned", phase: 3 }),
|
|
10443
|
+
Object.freeze({ target: "react", status: "planned", phase: 6 })
|
|
10444
|
+
]);
|
|
10445
|
+
|
|
10446
|
+
// src/studio/document.js
|
|
10447
|
+
var copie = (v) => v === void 0 ? void 0 : structuredClone(v);
|
|
10448
|
+
var StudioDocument = class {
|
|
10449
|
+
#doc;
|
|
10450
|
+
#passe = [];
|
|
10451
|
+
// lots qui défont, du plus ancien au plus récent
|
|
10452
|
+
#futur = [];
|
|
10453
|
+
// lots qui refont
|
|
10454
|
+
#ecoutes = /* @__PURE__ */ new Set();
|
|
10455
|
+
/** @param {object} [json] un document enregistré ; absent : un document vide */
|
|
10456
|
+
constructor(json) {
|
|
10457
|
+
this.#doc = json === void 0 ? createDocument() : assertValid(migrate(structuredClone(json)));
|
|
10458
|
+
}
|
|
10459
|
+
/* ── Lire ────────────────────────────────────────────────────────────────────────────────── */
|
|
10460
|
+
get pages() {
|
|
10461
|
+
return this.#doc.pages.map((p) => ({ ...p, frames: [...p.frames] }));
|
|
10462
|
+
}
|
|
10463
|
+
/** Une copie du nœud : la modifier ne change pas le document (seules les opérations le font). */
|
|
10464
|
+
node(id) {
|
|
10465
|
+
return copie(this.#doc.nodes[id]) ?? null;
|
|
10466
|
+
}
|
|
10467
|
+
/** Premier nœud qui correspond, dans l'ordre des pages puis de l'arbre. `{ name, type }` */
|
|
10468
|
+
find(critere = {}) {
|
|
10469
|
+
return this.findAll(critere)[0] ?? null;
|
|
10470
|
+
}
|
|
10471
|
+
findAll({ name, type } = {}) {
|
|
10472
|
+
const out = [];
|
|
10473
|
+
const visiter = (id) => {
|
|
10474
|
+
const n = this.#doc.nodes[id];
|
|
10475
|
+
if ((name === void 0 || n.name === name) && (type === void 0 || n.type === type)) out.push(copie(n));
|
|
10476
|
+
for (const e of n.children || []) visiter(e);
|
|
10477
|
+
};
|
|
10478
|
+
for (const p of this.#doc.pages) for (const id of p.frames) visiter(id);
|
|
10479
|
+
return out;
|
|
10480
|
+
}
|
|
10481
|
+
/** Le document en forme canonique : deux documents égaux donnent les mêmes octets. */
|
|
10482
|
+
toJSON() {
|
|
10483
|
+
return structuredClone(canonical(this.#doc));
|
|
10484
|
+
}
|
|
10485
|
+
/* ── Vérifier, émettre, rendre (P85) ─────────────────────────────────────────────────────── */
|
|
10486
|
+
/** → `{ issues: [{ rule, severity, node, name, detail? }] }` */
|
|
10487
|
+
check() {
|
|
10488
|
+
return check(this.#doc);
|
|
10489
|
+
}
|
|
10490
|
+
/** → `{ target, files: [{ path, content, bytes }], warnings }`. Phase 1 : `target: "html"` seulement. */
|
|
10491
|
+
emit({ target = "html", ...options } = {}) {
|
|
10492
|
+
if (target !== "html") {
|
|
10493
|
+
const prevue = TARGETS.find((t) => t.target === target);
|
|
10494
|
+
throw new StudioError("studio_target_unavailable", prevue ? `La cible \xAB ${target} \xBB arrive en phase ${prevue.phase}.` : `Cible inconnue : ${target}`, { target, available: TARGETS.filter((t) => t.status === "available").map((t) => t.target) }, 501);
|
|
10495
|
+
}
|
|
10496
|
+
return emitHtml(this.#doc, options);
|
|
10497
|
+
}
|
|
10498
|
+
/** Un cadre en PNG, dans le navigateur. → `{ bytes, mime, width, height }` ; hors navigateur : `studio_render_unavailable`. */
|
|
10499
|
+
async render({ frame, format = "png", scale = 1, assets, document } = {}) {
|
|
10500
|
+
if (format !== "png") throw new StudioError("studio_target_unavailable", `Le format \xAB ${format} \xBB n'est pas encore livr\xE9 (phase 2) ; png l'est.`, { format, available: ["png"] }, 501);
|
|
10501
|
+
return renderPng(this.#doc, { frame, scale, assets, document });
|
|
10502
|
+
}
|
|
10503
|
+
/* ── Modifier ────────────────────────────────────────────────────────────────────────────── */
|
|
10504
|
+
/** Applique un lot, en entier ou pas du tout. → `{ applied, created, removed }` */
|
|
10505
|
+
apply(ops, { source = "user" } = {}) {
|
|
10506
|
+
const r = applyOps(this.#doc, ops);
|
|
10507
|
+
this.#doc = r.doc;
|
|
10508
|
+
this.#passe.push(r.inverse);
|
|
10509
|
+
this.#futur = [];
|
|
10510
|
+
this.#emettre(ops, source);
|
|
10511
|
+
return { applied: ops.length, created: r.created, removed: r.removed };
|
|
10512
|
+
}
|
|
10513
|
+
set(id, path, value) {
|
|
10514
|
+
return this.apply([{ op: "set", id, path, value }]);
|
|
10515
|
+
}
|
|
10516
|
+
/** Insère un nœud et rend son id. `parent` : id d'un cadre, ou d'une page. */
|
|
10517
|
+
insert(parent, node4, { index } = {}) {
|
|
10518
|
+
return this.apply([{ op: "insert", parent, node: node4, index }]).created[0];
|
|
10519
|
+
}
|
|
10520
|
+
move(id, { parent, index } = {}) {
|
|
10521
|
+
return this.apply([{ op: "move", id, parent, index }]);
|
|
10522
|
+
}
|
|
10523
|
+
remove(id) {
|
|
10524
|
+
return this.apply([{ op: "remove", id }]);
|
|
10525
|
+
}
|
|
10526
|
+
undo() {
|
|
10527
|
+
return this.#deplacer(this.#passe, this.#futur, "undo");
|
|
10528
|
+
}
|
|
10529
|
+
redo() {
|
|
10530
|
+
return this.#deplacer(this.#futur, this.#passe, "redo");
|
|
10531
|
+
}
|
|
10532
|
+
history() {
|
|
10533
|
+
return { undo: this.#passe.length, redo: this.#futur.length };
|
|
10534
|
+
}
|
|
10535
|
+
/** Écoute les changements ; rend la fonction qui arrête l'écoute. `e = { ops, source }` */
|
|
10536
|
+
on(evenement, fn) {
|
|
10537
|
+
if (evenement !== "change") throw new StudioError("studio_event_unknown", `\xC9v\xE9nement inconnu : ${evenement}`);
|
|
10538
|
+
this.#ecoutes.add(fn);
|
|
10539
|
+
return () => this.#ecoutes.delete(fn);
|
|
10540
|
+
}
|
|
10541
|
+
#deplacer(depuis, vers, source) {
|
|
10542
|
+
const lot = depuis.pop();
|
|
10543
|
+
if (!lot) return false;
|
|
10544
|
+
const r = applyOps(this.#doc, lot, { internal: true });
|
|
10545
|
+
this.#doc = r.doc;
|
|
10546
|
+
vers.push(r.inverse);
|
|
10547
|
+
this.#emettre(lot, source);
|
|
10548
|
+
return true;
|
|
10549
|
+
}
|
|
10550
|
+
#emettre(ops, source) {
|
|
10551
|
+
for (const fn of this.#ecoutes) {
|
|
10552
|
+
try {
|
|
10553
|
+
fn({ ops: copie(ops), source });
|
|
10554
|
+
} catch {
|
|
10555
|
+
}
|
|
10556
|
+
}
|
|
10557
|
+
}
|
|
10558
|
+
};
|
|
10559
|
+
|
|
10560
|
+
// src/resources/design.js
|
|
10561
|
+
var base = "/api/design";
|
|
10562
|
+
var projectPath = (id) => `${base}/projects/${encodeURIComponent(id)}`;
|
|
10563
|
+
var byType = (path, type) => type === void 0 ? path : `${path}?type=${encodeURIComponent(type)}`;
|
|
10564
|
+
var StudioProject = class _StudioProject {
|
|
10565
|
+
#client;
|
|
10566
|
+
constructor(client, data) {
|
|
10567
|
+
this.#client = client;
|
|
10568
|
+
Object.assign(this, data);
|
|
10569
|
+
}
|
|
10570
|
+
async open() {
|
|
10571
|
+
const path = projectPath(this.id);
|
|
10572
|
+
const { document, version } = await this.#client.get(`${path}/document`);
|
|
10573
|
+
const doc = new StudioDocument(document);
|
|
10574
|
+
let current = version;
|
|
10575
|
+
let pending = Promise.resolve();
|
|
10576
|
+
doc.save = ({ version: name } = {}) => {
|
|
10577
|
+
const document2 = doc.toJSON();
|
|
10578
|
+
const request = pending.then(async () => {
|
|
10579
|
+
const result = await this.#client.post(`${path}/document`, { document: document2, baseVersion: current, name });
|
|
10580
|
+
current = result.version;
|
|
10581
|
+
this.version = { id: current, name: name ?? null };
|
|
10582
|
+
this.bytes = result.bytes;
|
|
10583
|
+
return { version: current, bytes: result.bytes };
|
|
10584
|
+
});
|
|
10585
|
+
pending = request.catch(() => {
|
|
10586
|
+
});
|
|
10587
|
+
return request;
|
|
10588
|
+
};
|
|
10589
|
+
return doc;
|
|
10590
|
+
}
|
|
10591
|
+
async update(data) {
|
|
10592
|
+
const { project } = await this.#client.post(projectPath(this.id), data);
|
|
10593
|
+
Object.assign(this, project);
|
|
10594
|
+
return this;
|
|
10595
|
+
}
|
|
10596
|
+
async duplicate(data) {
|
|
10597
|
+
const { project } = await this.#client.post(`${projectPath(this.id)}/duplicate`, data);
|
|
10598
|
+
return new _StudioProject(this.#client, project);
|
|
10599
|
+
}
|
|
10600
|
+
async versions() {
|
|
10601
|
+
return (await this.#client.get(`${projectPath(this.id)}/versions`)).versions;
|
|
10602
|
+
}
|
|
10603
|
+
async restore(version) {
|
|
10604
|
+
const { project } = await this.#client.post(`${projectPath(this.id)}/restore`, { version });
|
|
10605
|
+
Object.assign(this, project);
|
|
10606
|
+
return this;
|
|
10607
|
+
}
|
|
10608
|
+
async render({ frame, width, height } = {}) {
|
|
10609
|
+
return this.#client.post(`${projectPath(this.id)}/render`, { frame, width, height }, { timeout: 0 });
|
|
10610
|
+
}
|
|
10611
|
+
};
|
|
10612
|
+
var DesignResource = class {
|
|
10613
|
+
constructor(client) {
|
|
10614
|
+
const wrap = (data) => new StudioProject(client, data);
|
|
10615
|
+
this.templates = {
|
|
10616
|
+
list: async ({ type } = {}) => (await client.get(byType(`${base}/templates`, type))).templates,
|
|
10617
|
+
get: async (id) => (await client.get(`${base}/templates/${encodeURIComponent(id)}`)).template
|
|
10618
|
+
};
|
|
10619
|
+
this.projects = {
|
|
10620
|
+
create: async (data) => wrap((await client.post(`${base}/projects`, data)).project),
|
|
10621
|
+
list: async ({ type } = {}) => (await client.get(byType(`${base}/projects`, type))).projects.map(wrap),
|
|
10622
|
+
get: async (id) => wrap((await client.get(projectPath(id))).project),
|
|
10623
|
+
remove: async (id) => client.delete(projectPath(id))
|
|
10624
|
+
};
|
|
10625
|
+
}
|
|
10626
|
+
/** Un document vide, ou rouvert depuis son JSON (validé ; invalide → `studio_document_invalid`). */
|
|
10627
|
+
document(json) {
|
|
10628
|
+
return new StudioDocument(json);
|
|
10629
|
+
}
|
|
10630
|
+
/** Les cibles d'émission et leur état : `[{ target, status: "available" | "planned", phase? }]` */
|
|
10631
|
+
targets() {
|
|
10632
|
+
return TARGETS.map((t) => ({ ...t }));
|
|
10633
|
+
}
|
|
10634
|
+
};
|
|
10635
|
+
|
|
9465
10636
|
// src/index.js
|
|
9466
10637
|
var DEFAULT_BASE_URL = typeof process !== "undefined" && process?.env?.IAGENIFY_API_URL || "https://api.iagenify.com";
|
|
9467
10638
|
var IaGenify = class {
|
|
@@ -9550,6 +10721,7 @@ var IaGenify = class {
|
|
|
9550
10721
|
this.mail = new MailResource(this._client);
|
|
9551
10722
|
this.hosts = new HostsResource(this._client);
|
|
9552
10723
|
this.compute = new ComputeResource(this._client);
|
|
10724
|
+
this.design = new DesignResource(this._client);
|
|
9553
10725
|
}
|
|
9554
10726
|
async getUser() {
|
|
9555
10727
|
const res = await this._client.get("/api/auth/me");
|