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/dist/index.js CHANGED
@@ -522,11 +522,15 @@ function createHttpClient({ baseUrl, sessionManager, appName = "", timeout = DEF
522
522
  async function request(method, path, body, opts = {}) {
523
523
  const url = `${baseUrl}${path}`;
524
524
  const isFormData = typeof FormData !== "undefined" && body instanceof FormData;
525
+ const isBinary = body instanceof Uint8Array;
525
526
  const headers = {
526
527
  "X-IaGenify-Version": SDK_VERSION,
527
- ...appName ? { "X-IaGenify-App-Name": appName } : {}
528
+ ...appName ? { "X-IaGenify-App-Name": appName } : {},
529
+ ...opts.headers || {}
528
530
  };
529
- if (!isFormData) {
531
+ if (isBinary) {
532
+ headers["Content-Type"] = "application/octet-stream";
533
+ } else if (!isFormData) {
530
534
  headers["Content-Type"] = "application/json";
531
535
  }
532
536
  if (opts.skipAuth !== true) {
@@ -546,7 +550,7 @@ function createHttpClient({ baseUrl, sessionManager, appName = "", timeout = DEF
546
550
  const res = await doFetch(url, {
547
551
  method,
548
552
  headers,
549
- body: body !== void 0 ? isFormData ? body : JSON.stringify(body) : void 0
553
+ body: body !== void 0 ? isFormData || isBinary ? body : JSON.stringify(body) : void 0
550
554
  }, { timeout: opts.timeout ?? timeout, signal: opts.signal });
551
555
  const text2 = await res.text();
552
556
  let data;
@@ -1661,10 +1665,10 @@ function cloudUsageLine(storage, usage) {
1661
1665
  const u = usage?.[storage?.service];
1662
1666
  if (!u) return "";
1663
1667
  const mine = storage.limits?.usedBytes || 0;
1664
- const base = (u.storages || []).find((b) => String(b.id) === String(storage.id));
1665
- const plafond = base ? base.quotaBytes : u.perBaseBytes;
1668
+ const base2 = (u.storages || []).find((b) => String(b.id) === String(storage.id));
1669
+ const plafond = base2 ? base2.quotaBytes : u.perBaseBytes;
1666
1670
  const plan = `(${PLAN_NAMES[usage.pack] || usage.pack} plan)`;
1667
- const plein = base?.overQuota || !base && u.overQuota;
1671
+ const plein = base2?.overQuota || !base2 && u.overQuota;
1668
1672
  if (plafond == null) {
1669
1673
  return `${formatBytes(mine)} used, ${SERVICE_NAMES[storage.service]} space ${formatBytes(u.usedBytes)} of ${formatBytes(u.quotaBytes)} ${plan}${u.overQuota ? " \u2014 FULL: writes are refused" : ""}`;
1670
1674
  }
@@ -4115,6 +4119,135 @@ function createServiceTools() {
4115
4119
  };
4116
4120
  }
4117
4121
 
4122
+ // src/resources/designTools.js
4123
+ var DESIGN_TOOL_NAMES = ["design_read", "design_apply", "design_render", "design_check", "design_template"];
4124
+ var fail5 = (message) => {
4125
+ throw Object.assign(new Error(message), { code: "tool_error" });
4126
+ };
4127
+ var clip3 = (value, max = 48e3) => String(value || "").length > max ? `${String(value).slice(0, max)}
4128
+ \u2026[truncated]` : String(value || "");
4129
+ var projectId = (value) => {
4130
+ const id = String(value || "").trim();
4131
+ if (!id) fail5('"projectId" is required. Use the design project currently open in the editor.');
4132
+ return id;
4133
+ };
4134
+ var parseOperations = (value) => {
4135
+ let operations = value;
4136
+ if (typeof value === "string") {
4137
+ try {
4138
+ operations = JSON.parse(value);
4139
+ } catch (error) {
4140
+ fail5(`"operations" is not valid JSON (${error.message}).`);
4141
+ }
4142
+ }
4143
+ if (!Array.isArray(operations) || operations.length < 1 || operations.length > 100) {
4144
+ fail5('"operations" must be a JSON array with 1 to 100 document operations.');
4145
+ }
4146
+ return operations;
4147
+ };
4148
+ function createDesignTools() {
4149
+ return {
4150
+ design_read: {
4151
+ category: "read",
4152
+ 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.",
4153
+ parameters: {
4154
+ projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" },
4155
+ node: { type: "string", description: "An existing node id from this document" }
4156
+ },
4157
+ async run({ projectId: id, node: node4 }, { api }) {
4158
+ const project = await api.design.projects.get(projectId(id));
4159
+ const doc = await project.open();
4160
+ const json = doc.toJSON();
4161
+ const describe = (nodeId) => {
4162
+ const item = json.nodes[nodeId];
4163
+ if (!item) return null;
4164
+ return {
4165
+ id: nodeId,
4166
+ type: item.type,
4167
+ name: item.name,
4168
+ size: item.size,
4169
+ position: item.position,
4170
+ text: item.text,
4171
+ style: item.style,
4172
+ layout: item.layout,
4173
+ children: (item.children || []).map(describe)
4174
+ };
4175
+ };
4176
+ if (node4) {
4177
+ const item = json.nodes[node4];
4178
+ if (!item) fail5(`Unknown design node id "${node4}".`);
4179
+ return { output: clip3(JSON.stringify(describe(node4))), summary: `Read ${item.name || node4}`, meta: { projectId: project.id, node: node4 } };
4180
+ }
4181
+ const pages = json.pages.map((page) => ({ id: page.id, name: page.name, frames: page.frames.map(describe) }));
4182
+ 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 } };
4183
+ }
4184
+ },
4185
+ design_apply: {
4186
+ category: "write",
4187
+ 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.",
4188
+ parameters: {
4189
+ projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" },
4190
+ operations: { type: "string", required: true, description: "JSON array of 1\u2013100 valid document operations" }
4191
+ },
4192
+ async run({ projectId: id, operations: raw }, { api }) {
4193
+ const operations = parseOperations(raw);
4194
+ const project = await api.design.projects.get(projectId(id));
4195
+ const doc = await project.open();
4196
+ const applied = doc.apply(operations, { source: "agent" });
4197
+ const saved = await doc.save();
4198
+ return {
4199
+ output: `Applied and saved ${applied.applied} design operation${applied.applied === 1 ? "" : "s"} to ${project.label}. The open editor will receive this exact batch.`,
4200
+ summary: `Updated ${project.label}`,
4201
+ meta: { projectId: project.id, version: saved.version, operations, created: applied.created }
4202
+ };
4203
+ }
4204
+ },
4205
+ design_render: {
4206
+ category: "read",
4207
+ 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.",
4208
+ parameters: {
4209
+ projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" },
4210
+ frame: { type: "string", description: "Frame id from design_read; omit to render the first frame" }
4211
+ },
4212
+ async run({ projectId: id, frame }, { api }) {
4213
+ const project = await api.design.projects.get(projectId(id));
4214
+ const result = await project.render({ frame });
4215
+ if (!result?.image?.data) fail5("The design preview returned no image.");
4216
+ return {
4217
+ 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.`,
4218
+ summary: "Rendered the design for visual review",
4219
+ meta: { projectId: project.id, frame: result.image.frame, width: result.image.width, height: result.image.height },
4220
+ attachments: [{ mime: result.image.mime || "image/png", data: result.image.data }]
4221
+ };
4222
+ }
4223
+ },
4224
+ design_check: {
4225
+ category: "read",
4226
+ description: "Run deterministic design checks on a saved project and report every issue with rule, severity, node and measured details.",
4227
+ parameters: { projectId: { type: "string", required: true, description: "The design project id currently open in the user's editor" } },
4228
+ async run({ projectId: id }, { api }) {
4229
+ const project = await api.design.projects.get(projectId(id));
4230
+ const doc = await project.open();
4231
+ const result = doc.check();
4232
+ return { output: clip3(JSON.stringify(result)), summary: `${result.issues.length} design checks reported`, meta: { projectId: project.id, issues: result.issues.length } };
4233
+ }
4234
+ },
4235
+ design_template: {
4236
+ category: "read",
4237
+ description: "List available Design templates, or read one template by id including its starting document.",
4238
+ parameters: { id: { type: "string", description: "Template id; omit to list templates" } },
4239
+ async run({ id }, { api }) {
4240
+ if (!id) {
4241
+ const templates2 = await api.design.templates.list({ type: "design" });
4242
+ return { output: clip3(JSON.stringify(templates2)), summary: `${templates2.length} design templates`, meta: { count: templates2.length } };
4243
+ }
4244
+ const template = await api.design.templates.get(id);
4245
+ return { output: clip3(JSON.stringify(template)), summary: `Read template ${id}`, meta: { template: id } };
4246
+ }
4247
+ }
4248
+ };
4249
+ }
4250
+
4118
4251
  // src/resources/workspaceTools.js
4119
4252
  var MAX_OUTPUT = 6e4;
4120
4253
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", "__pycache__", ".venv"]);
@@ -4137,12 +4270,12 @@ var MEDIA_MIME = {
4137
4270
  };
4138
4271
  var EXT_FOR = { markdown: "md", text: "txt", jpeg: "jpg", base64: "txt" };
4139
4272
  var ATTACHMENT_MAX = 15 * 1024 * 1024;
4140
- var fail5 = (message) => {
4273
+ var fail6 = (message) => {
4141
4274
  throw new IaGenifyError(400, "tool_error", message);
4142
4275
  };
4143
4276
  var short = (text2 = "", max = 80) => String(text2).length > max ? `${String(text2).slice(0, max)}\u2026` : String(text2);
4144
4277
  var filled2 = (value) => typeof value === "string" && value.trim() !== "";
4145
- var clip3 = (text2, max = MAX_OUTPUT) => text2.length > max ? `${text2.slice(0, max)}
4278
+ var clip4 = (text2, max = MAX_OUTPUT) => text2.length > max ? `${text2.slice(0, max)}
4146
4279
  \u2026[truncated ${text2.length - max} characters]` : text2;
4147
4280
  var stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
4148
4281
  var isTextMime = (mime) => mime.startsWith("text/") || /json|xml|yaml|javascript|typescript/.test(mime);
@@ -4216,7 +4349,7 @@ async function backup(files, path) {
4216
4349
  }
4217
4350
  async function readText(files, path) {
4218
4351
  const file = await files.read(path);
4219
- if (typeof file.content !== "string") fail5(`"${path}" is not a text file.`);
4352
+ if (typeof file.content !== "string") fail6(`"${path}" is not a text file.`);
4220
4353
  return file.content;
4221
4354
  }
4222
4355
  var countOf = (text2, needle) => needle ? text2.split(needle).length - 1 : 0;
@@ -4274,11 +4407,11 @@ function storageArgs(args = {}) {
4274
4407
  try {
4275
4408
  parsed = JSON.parse(value);
4276
4409
  } catch (err) {
4277
- fail5(`"${name}" is not valid JSON (${err.message}). Send it as JSON text, e.g. ${shape === "array" ? "[{\u2026}]" : "{\u2026}"}.`);
4410
+ fail6(`"${name}" is not valid JSON (${err.message}). Send it as JSON text, e.g. ${shape === "array" ? "[{\u2026}]" : "{\u2026}"}.`);
4278
4411
  }
4279
4412
  }
4280
4413
  const isArray = Array.isArray(parsed);
4281
- if (shape === "array" ? !isArray : isArray || parsed === null || typeof parsed !== "object") fail5(`"${name}" must be a JSON ${shape}.`);
4414
+ if (shape === "array" ? !isArray : isArray || parsed === null || typeof parsed !== "object") fail6(`"${name}" must be a JSON ${shape}.`);
4282
4415
  return parsed;
4283
4416
  };
4284
4417
  return {
@@ -4291,25 +4424,25 @@ function storageArgs(args = {}) {
4291
4424
  documents: parse("documents", "array")
4292
4425
  };
4293
4426
  }
4294
- var requireText2 = (value, name) => typeof value === "string" && value.trim() ? value.trim() : fail5(`"${name}" is required for this action.`);
4427
+ var requireText2 = (value, name) => typeof value === "string" && value.trim() ? value.trim() : fail6(`"${name}" is required for this action.`);
4295
4428
  async function pickStorage(api, name, providers) {
4296
- if (!providers) fail5("Unknown action for this tool.");
4429
+ if (!providers) fail6("Unknown action for this tool.");
4297
4430
  const connected = (await api.storage.list()).filter((s) => s.type === "database" || s.type === "object");
4298
- if (!connected.length) fail5("No database or bucket is connected. Tell the user to connect one in Cloud.");
4431
+ if (!connected.length) fail6("No database or bucket is connected. Tell the user to connect one in Cloud.");
4299
4432
  const describe = (list) => list.map((s) => `"${s.label}" (${storageKindName(s, PROVIDER_NAMES)})`).join(", ");
4300
4433
  const byName = name ? connected.find((s) => s.id === name || s.label === name) || connected.find((s) => s.label.toLowerCase() === String(name).trim().toLowerCase()) : null;
4301
- if (name && !byName) fail5(`No connected storage named "${name}". Connected: ${describe(connected)}.`);
4434
+ if (name && !byName) fail6(`No connected storage named "${name}". Connected: ${describe(connected)}.`);
4302
4435
  const able = connected.filter((s) => providers.includes(engineOf(s)));
4303
4436
  const storage = byName || (able.length === 1 ? able[0] : null);
4304
- if (!storage) fail5(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)}.`);
4305
- if (!providers.includes(engineOf(storage))) fail5(`"${storage.label}" is ${storageKindName(storage, PROVIDER_NAMES)}; this action needs ${providers.map((p) => PROVIDER_NAMES[p]).join(" or ")}.`);
4437
+ 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)}.`);
4438
+ if (!providers.includes(engineOf(storage))) fail6(`"${storage.label}" is ${storageKindName(storage, PROVIDER_NAMES)}; this action needs ${providers.map((p) => PROVIDER_NAMES[p]).join(" or ")}.`);
4306
4439
  return storage;
4307
4440
  }
4308
4441
  function sqlStatement(input) {
4309
4442
  const sql = String(input || "").trim().replace(/;\s*$/, "");
4310
- if (!sql) fail5('"sql" is required for this action.');
4443
+ if (!sql) fail6('"sql" is required for this action.');
4311
4444
  const bare = sql.replace(/--[^\n]*/g, " ").replace(/\/\*[\s\S]*?\*\//g, " ").replace(/'(?:[^']|'')*'/g, "''").replace(/"(?:[^"]|"")*"/g, '""');
4312
- if (bare.includes(";")) fail5("Send one SQL statement per call.");
4445
+ if (bare.includes(";")) fail6("Send one SQL statement per call.");
4313
4446
  const verb = (bare.match(/^\s*([a-z]+)/i) || [])[1]?.toUpperCase() || "";
4314
4447
  const writesInside = /\b(INSERT|UPDATE|DELETE|REPLACE|CREATE|ALTER|DROP)\b/i.test(bare);
4315
4448
  const read = ["SELECT", "EXPLAIN"].includes(verb) && !writesInside || verb === "WITH" && !writesInside || verb === "PRAGMA" && !bare.includes("=");
@@ -4324,28 +4457,28 @@ async function checkStorageWrite(rawArgs = {}, { api, mode } = {}) {
4324
4457
  const emptyFilter = !args.filter || !Object.keys(args.filter).length;
4325
4458
  let statement = null;
4326
4459
  if (["insert", "update", "delete"].includes(action)) requireText2(args.collection, "collection");
4327
- if (action === "insert" && (!Array.isArray(args.documents) || !args.documents.length || args.documents.length > 500)) fail5("insert needs documents: a list of 1 to 500 objects.");
4460
+ 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.");
4328
4461
  if (action === "update") {
4329
- if (emptyFilter && args.all !== true) fail5("update with an empty filter would change every document. Add a filter, or all: true if that is really what the user wants.");
4330
- if (!args.update || !Object.keys(args.update).length || !Object.keys(args.update).every((k) => k.startsWith("$"))) fail5('update needs operators such as {"$set":{"field":"value"}}, not a whole document.');
4462
+ 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.");
4463
+ 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.');
4331
4464
  }
4332
- if (action === "delete" && emptyFilter && args.all !== true) fail5("delete with an empty filter would remove every document. Add a filter, or all: true if that is really what the user wants.");
4465
+ 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.");
4333
4466
  if (action === "sql") {
4334
4467
  statement = sqlStatement(args.sql);
4335
- if (statement.read) fail5('This statement only reads: use query_storage with action "sql".');
4336
- if (!statement.write) fail5(`write_storage runs INSERT, UPDATE, DELETE, REPLACE, CREATE, ALTER or DROP \u2014 not ${statement.verb || "this statement"}.`);
4337
- if (statement.drop && mode?.() !== "full") fail5("DROP is only allowed in Full access mode. Ask the user to switch mode if they really want to drop it.");
4338
- if (statement.unbounded && args.all !== true) fail5(`${statement.verb} without WHERE would touch every row. Add a WHERE clause, or all: true if that is really what the user wants.`);
4468
+ if (statement.read) fail6('This statement only reads: use query_storage with action "sql".');
4469
+ if (!statement.write) fail6(`write_storage runs INSERT, UPDATE, DELETE, REPLACE, CREATE, ALTER or DROP \u2014 not ${statement.verb || "this statement"}.`);
4470
+ 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.");
4471
+ 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.`);
4339
4472
  }
4340
4473
  if (action === "put") {
4341
4474
  requireText2(args.key, "key");
4342
- if (args.content == null && !args.path) fail5("put needs content (text) or path (a workspace file).");
4475
+ if (args.content == null && !args.path) fail6("put needs content (text) or path (a workspace file).");
4343
4476
  }
4344
4477
  if (action === "remove") requireText2(args.key, "key");
4345
4478
  if (action === "create_collection") requireText2(args.collection, "collection");
4346
4479
  if (action === "drop_collection") {
4347
4480
  requireText2(args.collection, "collection");
4348
- if (mode?.() !== "full") fail5("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.");
4481
+ 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.");
4349
4482
  }
4350
4483
  return { db, statement, args };
4351
4484
  }
@@ -4359,7 +4492,7 @@ function createWorkspaceTools({ client }) {
4359
4492
  if (typeof text2 !== "string" && attachMime) {
4360
4493
  if (file.size > ATTACHMENT_MAX) {
4361
4494
  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.";
4362
- fail5(`"${file.path}" is ${(file.size / 1048576).toFixed(1)} MB; files over ${ATTACHMENT_MAX / 1048576} MB cannot be attached.${advice}`);
4495
+ fail6(`"${file.path}" is ${(file.size / 1048576).toFixed(1)} MB; files over ${ATTACHMENT_MAX / 1048576} MB cannot be attached.${advice}`);
4363
4496
  }
4364
4497
  const kind = attachMime.startsWith("audio/") ? "Listen to it" : attachMime.startsWith("video/") ? "Watch it" : "Read it";
4365
4498
  return {
@@ -4373,7 +4506,7 @@ function createWorkspaceTools({ client }) {
4373
4506
  if (CONVERTIBLE[ext]) {
4374
4507
  const converted = await convert.convert({ from: ext, to: CONVERTIBLE[ext], file: file.content });
4375
4508
  text2 = String(converted.content ?? converted.markdown ?? converted.text ?? "");
4376
- if (!text2) fail5(`Could not extract text from "${path}".`);
4509
+ if (!text2) fail6(`Could not extract text from "${path}".`);
4377
4510
  } else {
4378
4511
  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 } };
4379
4512
  }
@@ -4384,7 +4517,7 @@ function createWorkspaceTools({ client }) {
4384
4517
  const numbered = slice.map((l, i) => `${start + i} ${l.length > 2e3 ? `${l.slice(0, 2e3)}\u2026` : l}`).join("\n");
4385
4518
  const more = start - 1 + slice.length < lines.length ? `
4386
4519
  \u2026[${lines.length - (start - 1 + slice.length)} more lines \u2014 use offset]` : "";
4387
- return { output: clip3(numbered + more) || "(empty file)", summary: `${file.path} \xB7 ${lines.length} lines`, meta: { path: file.path, lines: lines.length } };
4520
+ return { output: clip4(numbered + more) || "(empty file)", summary: `${file.path} \xB7 ${lines.length} lines`, meta: { path: file.path, lines: lines.length } };
4388
4521
  }
4389
4522
  const search = new SearchResource(client);
4390
4523
  const fetchPage = new FetchResource(client);
@@ -4393,6 +4526,7 @@ function createWorkspaceTools({ client }) {
4393
4526
  ...createPlatformTools(),
4394
4527
  // P54 : les services de la plateforme — hébergement, courrier, domaines, compte, documents, second modèle.
4395
4528
  ...createServiceTools(),
4529
+ ...createDesignTools(),
4396
4530
  read: {
4397
4531
  category: "read",
4398
4532
  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.",
@@ -4404,8 +4538,8 @@ function createWorkspaceTools({ client }) {
4404
4538
  },
4405
4539
  async run({ path, paths, offset = 1, limit = 2e3 }, context) {
4406
4540
  const liste = Array.isArray(paths) && paths.length ? paths.map((p) => String(p)) : [String(path ?? "")];
4407
- if (!filled2(liste[0])) fail5('Give "path" (one file) or "paths" (several).');
4408
- if (liste.length > 20) fail5(`A single call reads at most 20 files (got ${liste.length}).`);
4541
+ if (!filled2(liste[0])) fail6('Give "path" (one file) or "paths" (several).');
4542
+ if (liste.length > 20) fail6(`A single call reads at most 20 files (got ${liste.length}).`);
4409
4543
  if (liste.length === 1) return lireFichier(liste[0], { offset, limit }, context);
4410
4544
  const lus = [];
4411
4545
  const pieces2 = [];
@@ -4421,7 +4555,7 @@ Error: ${err.message}`);
4421
4555
  }
4422
4556
  }
4423
4557
  return {
4424
- output: clip3(lus.join("\n\n"), 6e4),
4558
+ output: clip4(lus.join("\n\n"), 6e4),
4425
4559
  summary: `${liste.length} files`,
4426
4560
  meta: { paths: liste, attached: pieces2.length || void 0 },
4427
4561
  ...pieces2.length ? { attachments: pieces2 } : {}
@@ -4458,7 +4592,7 @@ Error: ${err.message}`);
4458
4592
  try {
4459
4593
  re = new RegExp(pattern, ignore_case ? "i" : "");
4460
4594
  } catch (err) {
4461
- fail5(`Invalid regular expression: ${err.message}`);
4595
+ fail6(`Invalid regular expression: ${err.message}`);
4462
4596
  }
4463
4597
  const only = glob ? globToRegExp(glob) : null;
4464
4598
  const hits = [];
@@ -4492,8 +4626,8 @@ Error: ${err.message}`);
4492
4626
  async run({ path, old_string, new_string, replace_all = false }, { files }) {
4493
4627
  const before = await readText(files, path);
4494
4628
  const count = countOf(before, old_string);
4495
- if (!count) fail5(`old_string was not found in "${path}". Read the file and copy the text exactly.`);
4496
- if (count > 1 && !replace_all) fail5(`old_string appears ${count} times in "${path}". Add surrounding lines to make it unique, or set replace_all.`);
4629
+ if (!count) fail6(`old_string was not found in "${path}". Read the file and copy the text exactly.`);
4630
+ if (count > 1 && !replace_all) fail6(`old_string appears ${count} times in "${path}". Add surrounding lines to make it unique, or set replace_all.`);
4497
4631
  const after = replace_all ? before.split(old_string).join(new_string) : before.replace(old_string, () => new_string);
4498
4632
  await backup(files, path);
4499
4633
  await files.write(path, after);
@@ -4517,8 +4651,8 @@ Error: ${err.message}`);
4517
4651
  const diffs = [];
4518
4652
  edits.forEach((e, i) => {
4519
4653
  const count = countOf(text2, e.old_string);
4520
- if (!count) fail5(`Edit ${i + 1}: old_string not found in "${path}". Nothing was changed.`);
4521
- if (count > 1 && !e.replace_all) fail5(`Edit ${i + 1}: old_string appears ${count} times. Nothing was changed.`);
4654
+ if (!count) fail6(`Edit ${i + 1}: old_string not found in "${path}". Nothing was changed.`);
4655
+ if (count > 1 && !e.replace_all) fail6(`Edit ${i + 1}: old_string appears ${count} times. Nothing was changed.`);
4522
4656
  diffs.push(diffOf(text2, e.old_string, e.new_string));
4523
4657
  text2 = e.replace_all ? text2.split(e.old_string).join(e.new_string) : text2.replace(e.old_string, () => e.new_string);
4524
4658
  });
@@ -4562,17 +4696,17 @@ Error: ${err.message}`);
4562
4696
  // Refusé avant toute permission, en disant comment faire.
4563
4697
  check({ command = "", commands, background } = {}, { shell, terminals } = {}) {
4564
4698
  if (commands !== void 0) {
4565
- if (!Array.isArray(commands) || !commands.length) fail5('"commands" must be a list of shell commands, e.g. ["npm ci", "npm run build"].');
4566
- if (commands.some((c) => typeof c !== "string" || !c.trim())) fail5('Every entry of "commands" must be a non-empty command.');
4567
- if (commands.length > 20) fail5(`A single call runs at most 20 commands (got ${commands.length}).`);
4568
- if (background === true) fail5("background: true runs ONE command in a terminal. Use command, not commands \u2014 or run the sequence without background.");
4699
+ if (!Array.isArray(commands) || !commands.length) fail6('"commands" must be a list of shell commands, e.g. ["npm ci", "npm run build"].');
4700
+ if (commands.some((c) => typeof c !== "string" || !c.trim())) fail6('Every entry of "commands" must be a non-empty command.');
4701
+ if (commands.length > 20) fail6(`A single call runs at most 20 commands (got ${commands.length}).`);
4702
+ if (background === true) fail6("background: true runs ONE command in a terminal. Use command, not commands \u2014 or run the sequence without background.");
4569
4703
  } else if (!filled2(command)) {
4570
- fail5('Give "command" (one command) or "commands" (several, run in order).');
4704
+ fail6('Give "command" (one command) or "commands" (several, run in order).');
4571
4705
  }
4572
4706
  if (background === true || !terminals) return;
4573
4707
  const text2 = [command, ...Array.isArray(commands) ? commands : []].filter(Boolean).join("\n");
4574
4708
  if (DETACHED.test(text2) && RUNTIME.test(text2)) {
4575
- fail5(`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" }.`);
4709
+ 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" }.`);
4576
4710
  }
4577
4711
  },
4578
4712
  async run({ command, commands, timeout_ms = 12e4, background = false, stop_on_error = true, port = null }, { root, signal, shell, terminals }) {
@@ -4581,7 +4715,7 @@ Error: ${err.message}`);
4581
4715
  const seule = liste[0];
4582
4716
  const auto = background !== true && Boolean(terminals) && liste.length === 1 && LONG_RUNNING.test(seule);
4583
4717
  if (background === true || auto) {
4584
- if (!terminals) fail5("Background commands need a terminal environment, and there are none here. Run the command without background.");
4718
+ if (!terminals) fail6("Background commands need a terminal environment, and there are none here. Run the command without background.");
4585
4719
  const note = auto ? "This command starts a server that never exits, so it runs in a terminal instead of blocking.\n" : "";
4586
4720
  const terminal = await terminals.create({ name: short(seule, 60), command: seule, by: "agent", ...port ? { port } : {} });
4587
4721
  const first = await settle(terminal, signal);
@@ -4590,9 +4724,9 @@ Error: ${err.message}`);
4590
4724
  const exited = first.status === "exited";
4591
4725
  const output = exited ? `Terminal ${terminal.id} (${seule}) exited with code ${first.exitCode} right away.
4592
4726
  --- output ---
4593
- ${clip3(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.
4727
+ ${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.
4594
4728
  --- first output ---
4595
- ${clip3(text2, 2e4) || "(nothing yet)"}`;
4729
+ ${clip4(text2, 2e4) || "(nothing yet)"}`;
4596
4730
  const adresse = terminal.url ? `
4597
4731
 
4598
4732
  Open it at: ${terminal.url}
@@ -4600,7 +4734,7 @@ If it does not answer, the server is listening on localhost instead of 0.0.0.0 \
4600
4734
  return {
4601
4735
  output: note + output + adresse,
4602
4736
  summary: `${seule.slice(0, 80)} \xB7 ${exited ? `exit ${first.exitCode}` : terminal.url || `terminal ${terminal.id}`}`,
4603
- meta: { command: seule, background: true, terminalId: terminal.id, status: first.status, exitCode: first.exitCode, stdout: clip3(text2, 4e3), url: terminal.url ?? null, port: terminal.port ?? null }
4737
+ 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 }
4604
4738
  };
4605
4739
  }
4606
4740
  const executer = async (cmd) => {
@@ -4652,9 +4786,9 @@ If it does not answer, the server is listening on localhost instead of 0.0.0.0 \
4652
4786
  if (liste.length === 1) {
4653
4787
  const r = await executer(seule);
4654
4788
  const output = [`exit code ${etat(r)}`, r.stdout && `--- stdout ---
4655
- ${clip3(r.stdout, 3e4)}`, r.stderr && `--- stderr ---
4656
- ${clip3(r.stderr, 3e4)}`].filter(Boolean).join("\n");
4657
- return { output, summary: `${seule.slice(0, 80)} \xB7 exit ${etat(r)}`, meta: { command: seule, exitCode: r.code, timedOut: r.timedOut, stdout: clip3(r.stdout, 4e3), stderr: clip3(r.stderr, 4e3) } };
4789
+ ${clip4(r.stdout, 3e4)}`, r.stderr && `--- stderr ---
4790
+ ${clip4(r.stderr, 3e4)}`].filter(Boolean).join("\n");
4791
+ 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) } };
4658
4792
  }
4659
4793
  const faits = [];
4660
4794
  for (const cmd of liste) {
@@ -4667,9 +4801,9 @@ ${clip3(r.stderr, 3e4)}`].filter(Boolean).join("\n");
4667
4801
  const bloc = faits.map((r, i) => [
4668
4802
  `[${i + 1}/${liste.length}] ${r.cmd} \u2014 exit ${etat(r)}`,
4669
4803
  r.stdout && `--- stdout ---
4670
- ${clip3(r.stdout, part)}`,
4804
+ ${clip4(r.stdout, part)}`,
4671
4805
  r.stderr && `--- stderr ---
4672
- ${clip3(r.stderr, part)}`
4806
+ ${clip4(r.stderr, part)}`
4673
4807
  ].filter(Boolean).join("\n")).join("\n\n");
4674
4808
  const dernier = faits.at(-1);
4675
4809
  const rates = faits.filter((r) => r.timedOut || r.code !== 0).length;
@@ -4685,8 +4819,8 @@ Stopped at command ${faits.length} of ${liste.length}: the rest was not run.` :
4685
4819
  exitCode: dernier ? dernier.code : null,
4686
4820
  timedOut: Boolean(dernier?.timedOut),
4687
4821
  results: faits.map((r) => ({ command: r.cmd, exitCode: r.code, timedOut: r.timedOut })),
4688
- stdout: clip3(faits.map((r) => r.stdout).filter(Boolean).join("\n"), 4e3),
4689
- stderr: clip3(faits.map((r) => r.stderr).filter(Boolean).join("\n"), 4e3)
4822
+ stdout: clip4(faits.map((r) => r.stdout).filter(Boolean).join("\n"), 4e3),
4823
+ stderr: clip4(faits.map((r) => r.stderr).filter(Boolean).join("\n"), 4e3)
4690
4824
  }
4691
4825
  };
4692
4826
  }
@@ -4703,14 +4837,14 @@ Stopped at command ${faits.length} of ${liste.length}: the rest was not run.` :
4703
4837
  since: { type: "integer", description: "output: read from this position; 0 = everything kept" }
4704
4838
  },
4705
4839
  async run({ action, id, since }, { terminals }) {
4706
- if (!terminals) fail5("There are no terminals here: they only exist on a computer.");
4840
+ if (!terminals) fail6("There are no terminals here: they only exist on a computer.");
4707
4841
  if (action === "list") {
4708
4842
  const all = await terminals.list();
4709
4843
  if (!all.length) return { output: "No terminals are open.", summary: "No terminals", meta: { terminals: [] } };
4710
4844
  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}`);
4711
4845
  return { output: lines.join("\n"), summary: `${all.filter((t) => t.status === "running").length} running \xB7 ${all.length} terminals`, meta: { terminals: all } };
4712
4846
  }
4713
- if (!id) fail5(`"id" is required for ${action}. Use terminal { action: "list" } to find it.`);
4847
+ if (!id) fail6(`"id" is required for ${action}. Use terminal { action: "list" } to find it.`);
4714
4848
  const terminal = await terminals.get(id);
4715
4849
  if (action === "output") {
4716
4850
  const from = since != null ? Number(since) : terminal.agentCursor || 0;
@@ -4720,16 +4854,16 @@ Stopped at command ${faits.length} of ${liste.length}: the rest was not run.` :
4720
4854
  return {
4721
4855
  output: `${terminal.id} \xB7 ${out.status}${out.status === "exited" ? ` (code ${out.exitCode ?? "stopped"})` : ""}${out.truncated ? " \xB7 older output was dropped" : ""}
4722
4856
  --- output ---
4723
- ${clip3(text2, 3e4) || "(no new output)"}`,
4857
+ ${clip4(text2, 3e4) || "(no new output)"}`,
4724
4858
  summary: `${terminal.name} \xB7 ${out.status}`,
4725
- meta: { terminalId: terminal.id, status: out.status, exitCode: out.exitCode, stdout: clip3(text2, 4e3) }
4859
+ meta: { terminalId: terminal.id, status: out.status, exitCode: out.exitCode, stdout: clip4(text2, 4e3) }
4726
4860
  };
4727
4861
  }
4728
4862
  if (action === "kill") {
4729
4863
  const stopped = await terminal.kill();
4730
4864
  return { output: `Stopped terminal ${stopped.id} (${stopped.command || stopped.name}).`, summary: `Stopped ${stopped.name}`, meta: { terminalId: stopped.id, status: stopped.status } };
4731
4865
  }
4732
- fail5(`Unknown action "${action}": use list, output or kill.`);
4866
+ fail6(`Unknown action "${action}": use list, output or kill.`);
4733
4867
  }
4734
4868
  },
4735
4869
  ask_user: {
@@ -4802,7 +4936,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
4802
4936
  const shot = r.screenshot?.base64 ? { mime: r.screenshot.mimeType || "image/jpeg", data: r.screenshot.base64 } : null;
4803
4937
  if (screenshot === true && !shot) sections.push("--- screenshot ---\n(the page could not be captured as an image)");
4804
4938
  return {
4805
- output: clip3(sections.filter(Boolean).join("\n\n"), 3e4),
4939
+ output: clip4(sections.filter(Boolean).join("\n\n"), 3e4),
4806
4940
  summary: `${r.title || url}${shot ? " \xB7 seen" : ""}`,
4807
4941
  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 } : {} },
4808
4942
  ...shot ? { attachments: [shot] } : {}
@@ -4821,12 +4955,12 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
4821
4955
  },
4822
4956
  async run({ path, url, to, save }, { files }) {
4823
4957
  const target = String(to || "").trim().toLowerCase();
4824
- if (!target) fail5('"to" is required: the format to convert into, e.g. "pdf".');
4825
- if (!filled2(path) && !filled2(url)) fail5('Give "path" (a workspace file) or "url".');
4826
- if (filled2(path) && filled2(url)) fail5('Give "path" or "url", not both.');
4958
+ if (!target) fail6('"to" is required: the format to convert into, e.g. "pdf".');
4959
+ if (!filled2(path) && !filled2(url)) fail6('Give "path" (a workspace file) or "url".');
4960
+ if (filled2(path) && filled2(url)) fail6('Give "path" or "url", not both.');
4827
4961
  const sourceName = filled2(path) ? String(path) : new URL(String(url)).pathname.split("/").filter(Boolean).pop() || "page";
4828
4962
  const from = sourceName.includes(".") ? sourceName.split(".").pop().toLowerCase() : "";
4829
- if (!from) fail5(`Cannot tell the format of "${sourceName}": the name has no extension.`);
4963
+ if (!from) fail6(`Cannot tell the format of "${sourceName}": the name has no extension.`);
4830
4964
  let result;
4831
4965
  if (filled2(path)) {
4832
4966
  const file = await files.read(path);
@@ -4835,11 +4969,11 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
4835
4969
  } else {
4836
4970
  result = await convert.convert({ from, to: target, url: String(url) });
4837
4971
  }
4838
- if (!result?.ok) fail5(result?.message || `Conversion ${from} \u2192 ${target} failed.`);
4972
+ if (!result?.ok) fail6(result?.message || `Conversion ${from} \u2192 ${target} failed.`);
4839
4973
  const data = result.content !== void 0 ? String(result.content) : Buffer.from(result.base64 || "", "base64");
4840
4974
  const ext = EXT_FOR[target] || target;
4841
- const base = sourceName.replace(/\.[^.]+$/, "");
4842
- const destination = filled2(save) ? String(save) : filled2(path) ? `${base}.${ext}` : `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${base}.${ext}`;
4975
+ const base2 = sourceName.replace(/\.[^.]+$/, "");
4976
+ const destination = filled2(save) ? String(save) : filled2(path) ? `${base2}.${ext}` : `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${base2}.${ext}`;
4843
4977
  const written = await files.write(destination, data);
4844
4978
  return {
4845
4979
  output: `Converted ${sourceName} (${from} \u2192 ${target}) to ${written.path} \u2014 ${Math.round(written.size / 1024)} KB, ${result.creditsUsed ?? 1} credit.`,
@@ -4916,7 +5050,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
4916
5050
  const usage = await api.cloud.usage();
4917
5051
  if (!args.storage) return { output: cloudUsageReport(usage), summary: "IaGenify Cloud \xB7 usage", meta: { action, storage: null } };
4918
5052
  const target2 = await pickStorage(api, args.storage, STORAGE_READS.usage);
4919
- if (!target2.service) fail5(`"${target2.label}" is a connected storage: its space is managed by its own provider. usage only reports IaGenify Cloud storages.`);
5053
+ if (!target2.service) fail6(`"${target2.label}" is a connected storage: its space is managed by its own provider. usage only reports IaGenify Cloud storages.`);
4920
5054
  return { output: cloudUsageReport(usage, target2), summary: `${target2.label} \xB7 usage`, meta: { storage: target2.label, provider: target2.provider, action } };
4921
5055
  }
4922
5056
  const db = await pickStorage(api, args.storage, STORAGE_READS[action]);
@@ -4924,7 +5058,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
4924
5058
  if (action === "overview") {
4925
5059
  const seen = await db.run({ action: "overview" });
4926
5060
  return {
4927
- output: clip3(overviewReport(db, seen), 3e4),
5061
+ output: clip4(overviewReport(db, seen), 3e4),
4928
5062
  summary: `${db.label} \xB7 overview`,
4929
5063
  meta: { storage: db.label, provider: db.provider, action, returned: (seen.collections || seen.tables || seen.folders || []).length }
4930
5064
  };
@@ -4940,13 +5074,13 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
4940
5074
  });
4941
5075
  } else if (action === "count") result = await db.run({ action: "count", collection: requireText2(args.collection, "collection"), filter: args.filter || {} });
4942
5076
  else if (action === "aggregate") {
4943
- if (!Array.isArray(args.pipeline) || !args.pipeline.length) fail5('aggregate needs a pipeline: a list of stages such as [{"$group":{"_id":"$model","total":{"$sum":"$credits"}}}].');
4944
- if (/"\$(out|merge)"/.test(JSON.stringify(args.pipeline))) fail5("aggregate is read-only: $out and $merge are not allowed.");
5077
+ 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"}}}].');
5078
+ if (/"\$(out|merge)"/.test(JSON.stringify(args.pipeline))) fail6("aggregate is read-only: $out and $merge are not allowed.");
4945
5079
  result = await db.run({ action: "aggregate", collection: requireText2(args.collection, "collection"), pipeline: args.pipeline });
4946
5080
  } else if (action === "tables") result = await db.run({ action: "tables" });
4947
5081
  else if (action === "sql") {
4948
5082
  const statement = sqlStatement(args.sql);
4949
- if (!statement.read) fail5(`query_storage only runs SELECT, WITH, PRAGMA or EXPLAIN. To change data (${statement.verb || "this statement"}), use write_storage with action "sql".`);
5083
+ 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".`);
4950
5084
  result = await db.run({ sql: statement.sql, params: Array.isArray(args.params) ? args.params : [] });
4951
5085
  } else if (action === "objects") result = await db.run({ action: "list", prefix: String(args.prefix || "") });
4952
5086
  else if (action === "object") result = await db.run({ action: "object", key: requireText2(args.key, "key") });
@@ -4961,7 +5095,7 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
4961
5095
  };
4962
5096
  }
4963
5097
  return {
4964
- output: clip3(results.map((r, i) => `[${i + 1}] ${r.source?.name || "document"} \xB7 ${r.score}
5098
+ output: clip4(results.map((r, i) => `[${i + 1}] ${r.source?.name || "document"} \xB7 ${r.score}
4965
5099
  ${r.text}`).join("\n\n"), 3e4),
4966
5100
  summary: `${db.label} \xB7 ${results.length} extract${results.length === 1 ? "" : "s"}`,
4967
5101
  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))] }
@@ -5015,7 +5149,7 @@ ${r.text}`).join("\n\n"), 3e4),
5015
5149
  else if (action === "drop_collection") result = await db.run({ action: "dropCollection", collection: args.collection.trim() });
5016
5150
  const target = args.collection || args.key || (args.sql ? String(args.sql).trim().split(/\s+/).slice(0, 3).join(" ") : "");
5017
5151
  return {
5018
- output: clip3(JSON.stringify(result, null, 1), 3e4),
5152
+ output: clip4(JSON.stringify(result, null, 1), 3e4),
5019
5153
  summary: `${db.label} \xB7 ${action}${target ? ` ${target}` : ""}`,
5020
5154
  meta: { storage: db.label, provider: db.provider, action, collection: args.collection || null, result }
5021
5155
  };
@@ -5086,28 +5220,28 @@ var MEDIA = {
5086
5220
  // produire doit se dire tout de suite, pas revenir en erreur du fournisseur une fois payé.
5087
5221
  verify: (a, model) => {
5088
5222
  if (OMNI_MODELS.includes(model)) {
5089
- if (a.audio === true) fail5(`"${model}" has no sound option. Use veo-3.1 for sound.`);
5223
+ if (a.audio === true) fail6(`"${model}" has no sound option. Use veo-3.1 for sound.`);
5090
5224
  if (a.duration !== void 0 && a.duration !== null && a.duration !== "") {
5091
5225
  const d = Number(a.duration);
5092
5226
  if (!Number.isFinite(d) || d < OMNI_SECONDS.min || d > OMNI_SECONDS.max) {
5093
- fail5(`"${model}" makes videos of ${OMNI_SECONDS.min} to ${OMNI_SECONDS.max} seconds (the provider's limit); you asked for ${a.duration}.`);
5227
+ fail6(`"${model}" makes videos of ${OMNI_SECONDS.min} to ${OMNI_SECONDS.max} seconds (the provider's limit); you asked for ${a.duration}.`);
5094
5228
  }
5095
5229
  }
5096
5230
  const permises = VIDEO_RESOLUTIONS[model] || [];
5097
5231
  if (filled2(a.resolution) && !permises.includes(a.resolution)) {
5098
- fail5(`"${model}" has no ${a.resolution}. It does ${permises.join(", ")}.`);
5232
+ fail6(`"${model}" has no ${a.resolution}. It does ${permises.join(", ")}.`);
5099
5233
  }
5100
5234
  return;
5101
5235
  }
5102
5236
  if (a.audio === true && !VIDEO_WITH_AUDIO.includes(model)) {
5103
- fail5(`"${model}" makes no sound. Only ${VIDEO_WITH_AUDIO.join(", ")} does \u2014 pass model: "veo-3.1", or leave audio out.`);
5237
+ fail6(`"${model}" makes no sound. Only ${VIDEO_WITH_AUDIO.join(", ")} does \u2014 pass model: "veo-3.1", or leave audio out.`);
5104
5238
  }
5105
5239
  if (a.duration !== void 0 && a.duration !== null && !VIDEO_DURATIONS.includes(Number(a.duration))) {
5106
- fail5(`duration must be ${VIDEO_DURATIONS.join(", ")} seconds; you asked for ${a.duration}.`);
5240
+ fail6(`duration must be ${VIDEO_DURATIONS.join(", ")} seconds; you asked for ${a.duration}.`);
5107
5241
  }
5108
5242
  const allowed = VIDEO_RESOLUTIONS[model] || [];
5109
5243
  if (filled2(a.resolution) && !allowed.includes(a.resolution)) {
5110
- fail5(`"${model}" has no ${a.resolution}. It does ${allowed.join(", ")} \u2014 change the resolution, or pick another model.`);
5244
+ fail6(`"${model}" has no ${a.resolution}. It does ${allowed.join(", ")} \u2014 change the resolution, or pick another model.`);
5111
5245
  }
5112
5246
  },
5113
5247
  // Omni : seulement ce qui a été demandé — sans durée, le modèle fait ses 10 s par défaut, et un
@@ -5196,7 +5330,7 @@ function createMediaTools({ client, media = {} }) {
5196
5330
  const args = fusionner(spec, media[MEDIA_KINDS[name]] || {}, brut);
5197
5331
  const model = filled2(args.model) ? args.model : spec.model;
5198
5332
  if (!spec.models.includes(model)) {
5199
- fail5(`${name} has no model "${args.model}". Available: ${spec.models.join(", ")}.`);
5333
+ fail6(`${name} has no model "${args.model}". Available: ${spec.models.join(", ")}.`);
5200
5334
  }
5201
5335
  if (spec.verify) spec.verify(args, model);
5202
5336
  },
@@ -5208,15 +5342,15 @@ function createMediaTools({ client, media = {} }) {
5208
5342
  if (spec.from && filled2(image)) {
5209
5343
  const source = await files.read(String(image));
5210
5344
  const mime = /^image\//.test(source.mimeType || "") ? source.mimeType : mimeOf(String(image));
5211
- if (!mime || !mime.startsWith("image/")) fail5(`"${source.path}" is not an image (${source.mimeType || "unknown type"}).`);
5212
- if (source.size > ATTACHMENT_MAX) fail5(`"${source.path}" is ${(source.size / 1048576).toFixed(1)} MB; the starting image must be under ${ATTACHMENT_MAX / 1048576} MB.`);
5345
+ if (!mime || !mime.startsWith("image/")) fail6(`"${source.path}" is not an image (${source.mimeType || "unknown type"}).`);
5346
+ 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.`);
5213
5347
  inputs.push({ type: "image", content: Buffer.from(source.content).toString("base64"), mime });
5214
5348
  }
5215
5349
  const session = await models.create({ model, settings: spec.settings(args, model), memory: false });
5216
5350
  try {
5217
5351
  const result = await session.generate({ inputs, outputs: [{ type: spec.output }] });
5218
5352
  const output = result.outputs?.find((o) => o.content);
5219
- if (!output) fail5(`The ${spec.type} model returned nothing.`);
5353
+ if (!output) fail6(`The ${spec.type} model returned nothing.`);
5220
5354
  const ext = output.mime?.split("/")[1]?.split(";")[0]?.replace("mpeg", "mp3") || spec.ext;
5221
5355
  const target = path || `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${Date.now()}.${ext}`;
5222
5356
  const item = await files.write(target, Buffer.from(output.content, "base64"));
@@ -5233,10 +5367,10 @@ function createMediaTools({ client, media = {} }) {
5233
5367
  }
5234
5368
  }]));
5235
5369
  }
5236
- 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)];
5370
+ 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)];
5237
5371
 
5238
5372
  // src/resources/prompt.js
5239
- var fail6 = (code, message) => new IaGenifyError(400, code, message);
5373
+ var fail7 = (code, message) => new IaGenifyError(400, code, message);
5240
5374
  var PROMPT_OPTIONS = {
5241
5375
  model: "text",
5242
5376
  mode: ["ask", "auto", "plan", "full"],
@@ -5259,8 +5393,8 @@ function storageIndex(storages = []) {
5259
5393
  const byProvider = /* @__PURE__ */ new Map();
5260
5394
  for (const s of storages) {
5261
5395
  if (!s) continue;
5262
- const slug = storageSlug(s.label || s.name);
5263
- if (slug) index.set(slug, s);
5396
+ const slug2 = storageSlug(s.label || s.name);
5397
+ if (slug2) index.set(slug2, s);
5264
5398
  if (s.provider) byProvider.set(s.provider, [...byProvider.get(s.provider) || [], s]);
5265
5399
  }
5266
5400
  for (const [provider, list] of byProvider) if (list.length === 1 && !index.has(provider)) index.set(provider, list[0]);
@@ -5277,26 +5411,26 @@ function parsePrompt(input, library = {}) {
5277
5411
  if (!flag) break;
5278
5412
  const key = flag[1].toLowerCase();
5279
5413
  const kind = PROMPT_OPTIONS[key];
5280
- if (!kind) throw fail6("unknown_option", `Unknown option --${key}. Options: ${Object.keys(PROMPT_OPTIONS).map((k) => `--${k}`).join(" ")}. Write \\-- to start a message with "--".`);
5414
+ if (!kind) throw fail7("unknown_option", `Unknown option --${key}. Options: ${Object.keys(PROMPT_OPTIONS).map((k) => `--${k}`).join(" ")}. Write \\-- to start a message with "--".`);
5281
5415
  rest = rest.slice(flag[0].length);
5282
5416
  if (kind === "flag") {
5283
5417
  if (key === "no-memory") options.memory = false;
5284
5418
  continue;
5285
5419
  }
5286
5420
  const found = rest.match(/^(?:=|[ \t]+)("([^"]*)"|'([^']*)'|\S+)/);
5287
- if (!found) throw fail6("option_value_required", `--${key} needs a value.`);
5421
+ if (!found) throw fail7("option_value_required", `--${key} needs a value.`);
5288
5422
  const value = found[2] ?? found[3] ?? found[1];
5289
5423
  rest = rest.slice(found[0].length);
5290
5424
  if (key === "mode") {
5291
- if (!kind.includes(value)) throw fail6("invalid_option", `--mode must be one of ${kind.join(", ")}.`);
5425
+ if (!kind.includes(value)) throw fail7("invalid_option", `--mode must be one of ${kind.join(", ")}.`);
5292
5426
  options.mode = value;
5293
5427
  } else if (key === "budget") {
5294
5428
  if (value === "none") options.budget = null;
5295
5429
  else if (Number(value) > 0) options.budget = Math.round(Number(value));
5296
- else throw fail6("invalid_option", "--budget takes a number of credits, or none.");
5430
+ else throw fail7("invalid_option", "--budget takes a number of credits, or none.");
5297
5431
  } else if (key === "context") {
5298
5432
  const tokens = parseTokenCount(value);
5299
- if (!tokens) throw fail6("invalid_option", "--context takes a number of tokens: 200k, 400k, 1M.");
5433
+ if (!tokens) throw fail7("invalid_option", "--context takes a number of tokens: 200k, 400k, 1M.");
5300
5434
  options.contextTokens = tokens;
5301
5435
  } else {
5302
5436
  options[key] = value;
@@ -5337,7 +5471,7 @@ function parsePrompt(input, library = {}) {
5337
5471
  }
5338
5472
 
5339
5473
  // src/resources/library.js
5340
- var fail7 = (status, code, message) => new IaGenifyError(status, code, message);
5474
+ var fail8 = (status, code, message) => new IaGenifyError(status, code, message);
5341
5475
  var NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
5342
5476
  var MAX_CONTENT = 1e5;
5343
5477
  var CLAUDE_TOOLS = { ls: "list", websearch: "search", webfetch: "fetch", multiedit: "multi_edit", todowrite: "todo_write" };
@@ -5419,34 +5553,34 @@ var LocalLibrary = class {
5419
5553
  }
5420
5554
  async _ready() {
5421
5555
  if (typeof process === "undefined" || !process.versions?.node) {
5422
- throw fail7(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.");
5556
+ 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.");
5423
5557
  }
5424
5558
  if (this.storage && this.storage.type !== "filesystem") {
5425
- throw fail7(400, "storage_not_local", `\xAB ${this.storage.label} \xBB n'est pas un stockage ordinateur : ses ${this.kind} ne sont pas sur un disque.`);
5559
+ 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.`);
5426
5560
  }
5427
5561
  if (this.storage?.machineId && this.storage.machineId !== await getMachineId()) {
5428
- throw fail7(409, "storage_not_on_this_machine", `\xAB ${this.storage.label} \xBB belongs to another computer: its ${this.kind} stay there.`);
5562
+ throw fail8(409, "storage_not_on_this_machine", `\xAB ${this.storage.label} \xBB belongs to another computer: its ${this.kind} stay there.`);
5429
5563
  }
5430
5564
  const { fs, path, os } = await node3();
5431
- const base = this.root || path.join(os.homedir(), ".iagenify");
5432
- const dir = path.join(base, this.spec.folder);
5565
+ const base2 = this.root || path.join(os.homedir(), ".iagenify");
5566
+ const dir = path.join(base2, this.spec.folder);
5433
5567
  await fs.mkdir(dir, { recursive: true, mode: 448 });
5434
- return { fs, path, base, dir };
5568
+ return { fs, path, base: base2, dir };
5435
5569
  }
5436
5570
  _file(path, dir, name) {
5437
5571
  return this.kind === "skills" ? path.join(dir, name, "SKILL.md") : path.join(dir, `${name}.md`);
5438
5572
  }
5439
5573
  _checkName(name) {
5440
5574
  if (typeof name !== "string" || !NAME.test(name)) {
5441
- throw fail7(400, "invalid_name", `A ${this.spec.label} name uses lowercase letters, digits and dashes (e.g. "legal-review"), 64 characters at most.`);
5575
+ throw fail8(400, "invalid_name", `A ${this.spec.label} name uses lowercase letters, digits and dashes (e.g. "legal-review"), 64 characters at most.`);
5442
5576
  }
5443
5577
  }
5444
5578
  /** Un élément lu sur disque : { name, description, …, content, builtIn: false }. */
5445
5579
  _fromFile(name, text2, extra = {}) {
5446
5580
  const { data, body } = parseFrontmatter(text2);
5447
- const base = { name, description: String(data.description || "").trim(), builtIn: false };
5448
- if (this.kind === "subagents") Object.assign(base, { tools: normalizeTools(data.tools), model: normalizeModel(data.model) });
5449
- return { ...base, ...extra, content: body };
5581
+ const base2 = { name, description: String(data.description || "").trim(), builtIn: false };
5582
+ if (this.kind === "subagents") Object.assign(base2, { tools: normalizeTools(data.tools), model: normalizeModel(data.model) });
5583
+ return { ...base2, ...extra, content: body };
5450
5584
  }
5451
5585
  _builtIn(name) {
5452
5586
  const item = this.spec.builtIns[name];
@@ -5482,7 +5616,7 @@ var LocalLibrary = class {
5482
5616
  try {
5483
5617
  text2 = await fs.readFile(file, "utf8");
5484
5618
  } catch (err) {
5485
- if (err.code === "ENOENT") throw fail7(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
5619
+ if (err.code === "ENOENT") throw fail8(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
5486
5620
  throw err;
5487
5621
  }
5488
5622
  if (this.kind !== "skills") return this._fromFile(name, text2);
@@ -5506,10 +5640,10 @@ var LocalLibrary = class {
5506
5640
  async save(item = {}) {
5507
5641
  const { name, description, content } = item;
5508
5642
  this._checkName(name);
5509
- if (this.spec.builtIns[name]) throw fail7(409, "name_reserved", `"${name}" is a built-in ${this.spec.label}; choose another name.`);
5510
- if (typeof description !== "string" || !description.trim()) throw fail7(400, "description_required", `A ${this.spec.label} needs a description: it is how the agent knows when to use it.`);
5511
- if (typeof content !== "string" || !content.trim()) throw fail7(400, "content_required", `A ${this.spec.label} needs instructions (content).`);
5512
- if (content.length > MAX_CONTENT) throw fail7(400, "content_too_long", `Instructions are limited to ${MAX_CONTENT.toLocaleString("en")} characters.`);
5643
+ if (this.spec.builtIns[name]) throw fail8(409, "name_reserved", `"${name}" is a built-in ${this.spec.label}; choose another name.`);
5644
+ 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.`);
5645
+ if (typeof content !== "string" || !content.trim()) throw fail8(400, "content_required", `A ${this.spec.label} needs instructions (content).`);
5646
+ if (content.length > MAX_CONTENT) throw fail8(400, "content_too_long", `Instructions are limited to ${MAX_CONTENT.toLocaleString("en")} characters.`);
5513
5647
  const data = { name, description: description.trim().replace(/\s+/g, " ") };
5514
5648
  if (this.kind === "subagents") {
5515
5649
  const tools = normalizeTools(item.tools);
@@ -5525,30 +5659,30 @@ var LocalLibrary = class {
5525
5659
  /** Met l'élément à la corbeille (~/.iagenify/.trash/<horodatage>/…), d'où on peut le récupérer. */
5526
5660
  async remove(name) {
5527
5661
  this._checkName(name);
5528
- if (this.spec.builtIns[name]) throw fail7(400, "builtin_item", `"${name}" is built in and cannot be removed.`);
5529
- const { fs, path, base, dir } = await this._ready();
5662
+ if (this.spec.builtIns[name]) throw fail8(400, "builtin_item", `"${name}" is built in and cannot be removed.`);
5663
+ const { fs, path, base: base2, dir } = await this._ready();
5530
5664
  const source = this.kind === "skills" ? path.join(dir, name) : this._file(path, dir, name);
5531
5665
  try {
5532
5666
  await fs.access(source);
5533
5667
  } catch {
5534
- throw fail7(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
5668
+ throw fail8(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
5535
5669
  }
5536
- const target = path.join(base, ".trash", (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-"), this.spec.folder, path.basename(source));
5670
+ const target = path.join(base2, ".trash", (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-"), this.spec.folder, path.basename(source));
5537
5671
  await fs.mkdir(path.dirname(target), { recursive: true });
5538
5672
  await fs.rename(source, target);
5539
5673
  return { ok: true };
5540
5674
  }
5541
5675
  /** Skills seulement : un fichier du skill (modèle, référence…), en texte. */
5542
5676
  async readFile(name, file) {
5543
- if (this.kind !== "skills") throw fail7(400, "not_a_skill", "Only skills have files.");
5677
+ if (this.kind !== "skills") throw fail8(400, "not_a_skill", "Only skills have files.");
5544
5678
  const skill = await this.get(name);
5545
5679
  const { fs, path } = await node3();
5546
5680
  const full = path.resolve(skill.folder, String(file || "").replace(/\\/g, "/"));
5547
- if (!full.startsWith(skill.folder + path.sep)) throw fail7(400, "invalid_path", `"${file}" is outside the skill folder.`);
5681
+ if (!full.startsWith(skill.folder + path.sep)) throw fail8(400, "invalid_path", `"${file}" is outside the skill folder.`);
5548
5682
  try {
5549
5683
  return { name: path.basename(full), path: path.relative(skill.folder, full).split(path.sep).join("/"), content: await fs.readFile(full, "utf8") };
5550
5684
  } catch (err) {
5551
- if (err.code === "ENOENT" || err.code === "EISDIR") throw fail7(404, "path_not_found", `The skill "${name}" has no file "${file}". Files: ${skill.files.join(", ") || "none"}.`);
5685
+ 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"}.`);
5552
5686
  throw err;
5553
5687
  }
5554
5688
  }
@@ -5623,13 +5757,13 @@ var AgentLibrary = class {
5623
5757
  if (err.status !== 404 || !this.computer) throw err;
5624
5758
  const onDisk = await this.computer.get(name).catch(() => null);
5625
5759
  if (!onDisk) throw err;
5626
- throw fail7(409, "item_on_computer", `\xAB ${name} \xBB est un fichier de cet ordinateur (~/.iagenify/${this.spec.folder}) : supprimez-le sur le disque.`);
5760
+ throw fail8(409, "item_on_computer", `\xAB ${name} \xBB est un fichier de cet ordinateur (~/.iagenify/${this.spec.folder}) : supprimez-le sur le disque.`);
5627
5761
  }
5628
5762
  }
5629
5763
  /** Skills seulement : un fichier annexe. Ceux du compte n'en ont pas — le contenu est le document. */
5630
5764
  async readFile(name, file) {
5631
- if (this.kind !== "skills") throw fail7(400, "not_a_skill", "Only skills have files.");
5632
- if (!this.computer) throw fail7(404, "path_not_found", `\xAB ${name} \xBB n'a pas de fichiers : les skills du compte sont un seul document.`);
5765
+ if (this.kind !== "skills") throw fail8(400, "not_a_skill", "Only skills have files.");
5766
+ 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.`);
5633
5767
  return this.computer.readFile(name, file);
5634
5768
  }
5635
5769
  };
@@ -5645,11 +5779,11 @@ var MAX_OUTPUT2 = 6e4;
5645
5779
  var CALL_TIMEOUT_MS = 6e4;
5646
5780
  var LIST_TIMEOUT_MS = 3e4;
5647
5781
  var MAX_PAGES = 20;
5648
- var fail8 = (status, code, message) => new IaGenifyError(status, code, message);
5782
+ var fail9 = (status, code, message) => new IaGenifyError(status, code, message);
5649
5783
  var CODE_VERSION_NON_SUPPORTEE = -32022;
5650
5784
  var estErreurModerne = (code) => typeof code === "number" && code <= -32020 && code >= -32099;
5651
5785
  var REPLI_ANCIENNE_POIGNEE = /* @__PURE__ */ new Set(["mcp_error", "mcp_http_error", "mcp_bad_response"]);
5652
- var clip4 = (text2, max = MAX_OUTPUT2) => text2.length > max ? `${text2.slice(0, max)}
5786
+ var clip5 = (text2, max = MAX_OUTPUT2) => text2.length > max ? `${text2.slice(0, max)}
5653
5787
  \u2026[truncated ${text2.length - max} characters]` : text2;
5654
5788
  var SCHEMA_TYPES = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "array", "object"]);
5655
5789
  var SCHEMA_KEYS = /* @__PURE__ */ new Set(["type", "description", "properties", "required", "items", "enum", "nullable"]);
@@ -5706,7 +5840,7 @@ function cleanToken(value) {
5706
5840
  token = token.replace(/^authorization\s*:\s*/i, "").replace(/^bearer\b\s*/i, "").replace(/^token\s*=\s*/i, "").trim().replace(quotes, "").trim();
5707
5841
  if (!token) return null;
5708
5842
  if (/\s/.test(token)) {
5709
- throw fail8(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.");
5843
+ 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.");
5710
5844
  }
5711
5845
  return token;
5712
5846
  }
@@ -5782,7 +5916,7 @@ function mirroredParams(schema, args) {
5782
5916
  }
5783
5917
  var McpClient = class {
5784
5918
  constructor({ url, token = null, name = "mcp", fetchImpl = null } = {}) {
5785
- if (!url) throw fail8(400, "url_required", "An MCP server needs its address.");
5919
+ if (!url) throw fail9(400, "url_required", "An MCP server needs its address.");
5786
5920
  this.url = String(url);
5787
5921
  this.token = cleanToken(token);
5788
5922
  this.name = name;
@@ -5844,8 +5978,8 @@ var McpClient = class {
5844
5978
  redirect: "manual"
5845
5979
  });
5846
5980
  } catch (err) {
5847
- if (controller.signal.aborted) throw fail8(504, "mcp_timeout", `\xAB ${this.name} \xBB n'a pas r\xE9pondu en ${Math.round(timeout / 1e3)} s.`);
5848
- throw fail8(502, "mcp_unreachable", `\xAB ${this.name} \xBB est injoignable : ${err.message}`);
5981
+ if (controller.signal.aborted) throw fail9(504, "mcp_timeout", `\xAB ${this.name} \xBB n'a pas r\xE9pondu en ${Math.round(timeout / 1e3)} s.`);
5982
+ throw fail9(502, "mcp_unreachable", `\xAB ${this.name} \xBB est injoignable : ${err.message}`);
5849
5983
  } finally {
5850
5984
  clearTimeout(timer);
5851
5985
  signal?.removeEventListener?.("abort", abort);
@@ -5854,17 +5988,17 @@ var McpClient = class {
5854
5988
  const detail = this._detail(brut);
5855
5989
  if (response.status === 401 || response.status === 403) {
5856
5990
  if (!this.token) {
5857
- throw fail8(401, "mcp_token_required", `\xAB ${this.name} \xBB demande un jeton : ce serveur ne r\xE9pond pas sans authentification.${detail}`);
5991
+ throw fail9(401, "mcp_token_required", `\xAB ${this.name} \xBB demande un jeton : ce serveur ne r\xE9pond pas sans authentification.${detail}`);
5858
5992
  }
5859
- throw fail8(401, "mcp_unauthorized", `\xAB ${this.name} \xBB refuse le jeton (${response.status}). V\xE9rifiez-le, ou recr\xE9ez-en un.${detail}`);
5993
+ throw fail9(401, "mcp_unauthorized", `\xAB ${this.name} \xBB refuse le jeton (${response.status}). V\xE9rifiez-le, ou recr\xE9ez-en un.${detail}`);
5860
5994
  }
5861
5995
  if (response.status >= 300 && response.status < 400) {
5862
- throw fail8(502, "mcp_redirect", `\xAB ${this.name} \xBB redirige vers une autre adresse : reconnectez-le avec l'adresse d\xE9finitive.`);
5996
+ throw fail9(502, "mcp_redirect", `\xAB ${this.name} \xBB redirige vers une autre adresse : reconnectez-le avec l'adresse d\xE9finitive.`);
5863
5997
  }
5864
- if (!response.ok) throw this._rpcError(fail8(502, "mcp_http_error", `\xAB ${this.name} \xBB a r\xE9pondu ${response.status}.${detail}`), brut);
5998
+ if (!response.ok) throw this._rpcError(fail9(502, "mcp_http_error", `\xAB ${this.name} \xBB a r\xE9pondu ${response.status}.${detail}`), brut);
5865
5999
  const message = await this._readMessage(response, id);
5866
6000
  if (message?.error) {
5867
- const err = fail8(502, "mcp_error", `\xAB ${this.name} \xBB refuse : ${String(message.error.message || message.error.code || "erreur").slice(0, 500)}`);
6001
+ const err = fail9(502, "mcp_error", `\xAB ${this.name} \xBB refuse : ${String(message.error.message || message.error.code || "erreur").slice(0, 500)}`);
5868
6002
  err.rpc = { code: message.error.code, data: message.error.data };
5869
6003
  throw err;
5870
6004
  }
@@ -5894,12 +6028,12 @@ var McpClient = class {
5894
6028
  /** La réponse, qu'elle arrive en JSON ou en flux d'événements (`text/event-stream`). */
5895
6029
  async _readMessage(response, id) {
5896
6030
  const type = String(response.headers.get("content-type") || "");
5897
- const body = clip4(await response.text(), 2e6);
6031
+ const body = clip5(await response.text(), 2e6);
5898
6032
  if (!type.includes("text/event-stream")) {
5899
6033
  try {
5900
6034
  return JSON.parse(body);
5901
6035
  } catch {
5902
- throw fail8(502, "mcp_bad_response", `\xAB ${this.name} \xBB n'a pas r\xE9pondu en JSON.`);
6036
+ throw fail9(502, "mcp_bad_response", `\xAB ${this.name} \xBB n'a pas r\xE9pondu en JSON.`);
5903
6037
  }
5904
6038
  }
5905
6039
  let last = null;
@@ -5914,7 +6048,7 @@ var McpClient = class {
5914
6048
  }
5915
6049
  }
5916
6050
  if (last) return last;
5917
- throw fail8(502, "mcp_bad_response", `\xAB ${this.name} \xBB n'a renvoy\xE9 aucune r\xE9ponse exploitable.`);
6051
+ throw fail9(502, "mcp_bad_response", `\xAB ${this.name} \xBB n'a renvoy\xE9 aucune r\xE9ponse exploitable.`);
5918
6052
  }
5919
6053
  /**
5920
6054
  * La poignée de main, dans les deux révisions. Elle dit quelle version le serveur a acceptée.
@@ -5936,7 +6070,7 @@ var McpClient = class {
5936
6070
  const propose = err.rpc?.data?.supportedVersions || err.rpc?.data?.supported;
5937
6071
  const version = negotiateVersion(propose);
5938
6072
  if (!version) {
5939
- throw fail8(
6073
+ throw fail9(
5940
6074
  502,
5941
6075
  "mcp_protocol_unsupported",
5942
6076
  `\xAB ${this.name} \xBB ne parle aucune r\xE9vision que ce client conna\xEEt (il propose ${[].concat(propose || []).join(", ") || "rien"}).`
@@ -5967,7 +6101,7 @@ var McpClient = class {
5967
6101
  const found = await this._rpc("server/discover", {}, { signal });
5968
6102
  const version = negotiateVersion(found.supportedVersions);
5969
6103
  if (found.supportedVersions && !version) {
5970
- throw fail8(
6104
+ throw fail9(
5971
6105
  502,
5972
6106
  "mcp_protocol_unsupported",
5973
6107
  `\xAB ${this.name} \xBB ne parle aucune r\xE9vision que ce client conna\xEEt (il propose ${[].concat(found.supportedVersions).join(", ")}).`
@@ -6019,7 +6153,7 @@ var McpClient = class {
6019
6153
  return part?.text ? String(part.text) : "";
6020
6154
  }).filter(Boolean).join("\n");
6021
6155
  const output = text2 || (result.structuredContent ? JSON.stringify(result.structuredContent) : "(aucun contenu)");
6022
- return { output: clip4(output), isError: Boolean(result.isError) };
6156
+ return { output: clip5(output), isError: Boolean(result.isError) };
6023
6157
  }
6024
6158
  };
6025
6159
  var McpResource = class {
@@ -6429,6 +6563,7 @@ var TOOL_FAMILIES = [
6429
6563
  ["Storages", ["query_storage", "write_storage"]],
6430
6564
  ["The account", ["account", "cloud"]],
6431
6565
  ["Put online and communicate", ["deploy", "domain", "mail", "send_mail"]],
6566
+ ["Design", ["design_read", "design_apply", "design_render", "design_check", "design_template"]],
6432
6567
  ["The platform itself", ["iagenify_docs", "workflow", "mcp"]],
6433
6568
  ["Ask another model", ["generate"]],
6434
6569
  ["This conversation", ["todo_write", "ask_user", "memory", "recall", "skill", "task"]]
@@ -6608,9 +6743,9 @@ var SUBAGENT_MAX_STEPS = 40;
6608
6743
  var MAX_SKILL_OUTPUT = 6e4;
6609
6744
  var withoutAttachments = (messages) => messages.map(({ attachments, images, ...m }) => attachments?.length || images?.length ? { ...m, content: `${m.content || ""} [${(attachments || images).length} file(s) attached]` } : m);
6610
6745
  var estimateTokens = (messages) => Math.ceil(JSON.stringify(withoutAttachments(messages)).length / 4);
6611
- var clip5 = (text2, max) => text2.length > max ? `${text2.slice(0, max)}
6746
+ var clip6 = (text2, max) => text2.length > max ? `${text2.slice(0, max)}
6612
6747
  \u2026[truncated ${text2.length - max} characters]` : text2;
6613
- var fail9 = (message) => {
6748
+ var fail10 = (message) => {
6614
6749
  throw new IaGenifyError(400, "tool_error", message);
6615
6750
  };
6616
6751
  var KEEP_ATTACHMENTS_FOR = 6;
@@ -6961,11 +7096,11 @@ var LocalAgent = class _LocalAgent {
6961
7096
  const notes = await this.api.memory.list();
6962
7097
  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` };
6963
7098
  }
6964
- if (!name) fail9("memory needs a name.");
7099
+ if (!name) fail10("memory needs a name.");
6965
7100
  if (action === "read") {
6966
7101
  const notes = await this.api.memory.list();
6967
7102
  const note = notes.find((n) => n.name === name);
6968
- if (!note) fail9(`No memory called "${name}". Listed names: ${notes.map((n) => n.name).join(", ") || "none"}.`);
7103
+ if (!note) fail10(`No memory called "${name}". Listed names: ${notes.map((n) => n.name).join(", ") || "none"}.`);
6969
7104
  return { output: `# ${note.name}
6970
7105
  ${note.description}
6971
7106
 
@@ -6976,7 +7111,7 @@ ${note.content}`, summary: note.name, meta: { memory: note.name } };
6976
7111
  this.memories = this.memories.filter((n) => n.name !== name);
6977
7112
  return { output: `Memory "${name}" deleted.`, summary: name, meta: { memory: name, deleted: true } };
6978
7113
  }
6979
- if (!content.trim()) fail9("memory save needs content.");
7114
+ if (!content.trim()) fail10("memory save needs content.");
6980
7115
  const saved = await this.api.memory.save({ name, description, content, type, source: "agent", ...this.memory ? { sessionId: this.id } : {} });
6981
7116
  this.memories = [saved, ...this.memories.filter((n) => n.name !== saved.name)];
6982
7117
  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 } };
@@ -7010,19 +7145,19 @@ ${note.content}`, summary: note.name, meta: { memory: note.name } };
7010
7145
  file: { type: "string", description: "Optional: one of the skill's files, as listed when it is loaded" }
7011
7146
  }),
7012
7147
  run: async ({ name, file }) => {
7013
- if (!this.library.skills.some((s) => s.name === name)) fail9(`Unknown skill "${name}". Available: ${this.library.skills.map((s) => s.name).join(", ")}.`);
7148
+ if (!this.library.skills.some((s) => s.name === name)) fail10(`Unknown skill "${name}". Available: ${this.library.skills.map((s) => s.name).join(", ")}.`);
7014
7149
  const library = this._library("skills");
7015
- if (!library) fail9("No skills are available here.");
7150
+ if (!library) fail10("No skills are available here.");
7016
7151
  if (file) {
7017
7152
  const read = await library.readFile(name, file);
7018
- return { output: clip5(read.content, MAX_SKILL_OUTPUT) || "(empty file)", summary: `${name} \xB7 ${read.path}`, meta: { skill: name, file: read.path } };
7153
+ return { output: clip6(read.content, MAX_SKILL_OUTPUT) || "(empty file)", summary: `${name} \xB7 ${read.path}`, meta: { skill: name, file: read.path } };
7019
7154
  }
7020
7155
  const skill = await library.get(name);
7021
7156
  const files = skill.files?.length ? `
7022
7157
 
7023
7158
  Files in this skill (read one with skill + file): ${skill.files.join(", ")}${skill.folder ? `
7024
7159
  Folder on this computer, for commands: ${skill.folder}` : ""}` : "";
7025
- return { output: clip5(`# Skill: ${name}
7160
+ return { output: clip6(`# Skill: ${name}
7026
7161
 
7027
7162
  ${skill.content}${files}`, MAX_SKILL_OUTPUT), summary: `Loaded ${name}`, meta: { skill: name, files: skill.files?.length || 0 } };
7028
7163
  }
@@ -7041,8 +7176,8 @@ ${skill.content}${files}`, MAX_SKILL_OUTPUT), summary: `Loaded ${name}`, meta: {
7041
7176
  }
7042
7177
  /** Lance un sous-agent : même machine, même mode, mêmes permissions, budget et crédits partagés avec ce run. */
7043
7178
  async _runSubagent({ agent: name, description = "", prompt }, call) {
7044
- if (!this.library.subagents.some((a) => a.name === name)) fail9(`Unknown subagent "${name}". Available: ${this.library.subagents.map((a) => a.name).join(", ")}.`);
7045
- if (!String(prompt || "").trim()) fail9("task needs a prompt: the subagent sees nothing of this conversation.");
7179
+ if (!this.library.subagents.some((a) => a.name === name)) fail10(`Unknown subagent "${name}". Available: ${this.library.subagents.map((a) => a.name).join(", ")}.`);
7180
+ if (!String(prompt || "").trim()) fail10("task needs a prompt: the subagent sees nothing of this conversation.");
7046
7181
  const definition = await this._definition("subagents", name);
7047
7182
  const wanted = !definition.tools || definition.tools === "all" ? WORKSPACE_TOOL_NAMES : definition.tools;
7048
7183
  const tools = wanted.filter((t) => this.toolNames.includes(t) && !PARENT_ONLY_TOOLS.has(t));
@@ -7092,7 +7227,7 @@ ${skill.content}${files}`, MAX_SKILL_OUTPUT), summary: `Loaded ${name}`, meta: {
7092
7227
 
7093
7228
  [${name} subagent \xB7 ${turns} turns \xB7 ${toolCalls} tool calls \xB7 ${credits} credits${ended}]`,
7094
7229
  summary: description || name,
7095
- meta: { agent: name, description, model: child.model, turns, toolCalls, credits, stopReason: result.stopReason, report: clip5(result.text || "", 4e3) }
7230
+ meta: { agent: name, description, model: child.model, turns, toolCalls, credits, stopReason: result.stopReason, report: clip6(result.text || "", 4e3) }
7096
7231
  };
7097
7232
  } finally {
7098
7233
  this.children.delete(child);
@@ -7123,7 +7258,7 @@ Files in this skill (read one with skill + file): ${skill.files.join(", ")}` : "
7123
7258
 
7124
7259
  # Skill: ${name}
7125
7260
 
7126
- ${clip5(skill.content, MAX_SKILL_OUTPUT)}${files}
7261
+ ${clip6(skill.content, MAX_SKILL_OUTPUT)}${files}
7127
7262
 
7128
7263
  # Request
7129
7264
  ${args || "Apply this skill."}`;
@@ -7186,13 +7321,13 @@ ${args || "Apply this skill."}`;
7186
7321
  const read = await this.catalog.read.run({ path }, { files });
7187
7322
  if (read.attachments?.length) images.push(...read.attachments.map((a) => ({ mime: a.mime, data: a.data })));
7188
7323
  sections.push(`## @${read.meta?.path || path}
7189
- ${read.attachments?.length ? read.output : clip5(read.output, 3e4)}`);
7324
+ ${read.attachments?.length ? read.output : clip6(read.output, 3e4)}`);
7190
7325
  emit({ type: "mention", kind: "file", path: read.meta?.path || path });
7191
7326
  } catch {
7192
7327
  try {
7193
7328
  const list = await this.catalog.list.run({ path }, { files });
7194
7329
  sections.push(`## @${path} (folder)
7195
- ${clip5(list.output, 8e3)}`);
7330
+ ${clip6(list.output, 8e3)}`);
7196
7331
  emit({ type: "mention", kind: "folder", path });
7197
7332
  } catch {
7198
7333
  }
@@ -7203,7 +7338,7 @@ ${clip5(list.output, 8e3)}`);
7203
7338
  try {
7204
7339
  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 });
7205
7340
  sections.push(`## #${s.name}${s.collection ? ` \xB7 ${s.collection}` : ""}
7206
- ${clip5(read.output, 8e3)}`);
7341
+ ${clip6(read.output, 8e3)}`);
7207
7342
  emit({ type: "mention", kind: "storage", storage: s.name, collection: s.collection });
7208
7343
  } catch (err) {
7209
7344
  sections.push(`## #${s.name}${s.collection ? ` \xB7 ${s.collection}` : ""}
@@ -8839,10 +8974,16 @@ var Host = class {
8839
8974
  if (files !== void 0) throw new IaGenifyError(400, "invalid_deploy", "An edge host deploys code, not a folder.");
8840
8975
  if (typeof code !== "string" || !code.trim()) throw new IaGenifyError(400, "nothing_to_deploy", "An edge host needs a code module.");
8841
8976
  }
8842
- const body = {};
8843
- if (code !== void 0) body.code = code;
8844
- if (files !== void 0) body.files = await readFiles(files);
8845
- if (this.runtime === "node" && server !== void 0) body.server = server;
8977
+ const withServer = this.runtime === "node" && server !== void 0;
8978
+ if (files !== void 0 && code !== void 0) throw new IaGenifyError(400, "invalid_deploy", "Pass files or code, not both.");
8979
+ if (files === void 0) {
8980
+ return (await this.client.post(`/api/hosting/${this.id}/deploy`, { code, ...withServer ? { server } : {} })).deploy;
8981
+ }
8982
+ const entries = await collectFiles(files);
8983
+ const total = entries.reduce((sum, file) => sum + file.size, 0);
8984
+ if (total > DIRECT_UPLOAD_ABOVE) return deployDirect(this.client, this.id, entries, withServer ? server : void 0);
8985
+ const body = { files: await Promise.all(entries.map(async (file) => ({ path: file.path, content: toBase64(await file.load()) }))) };
8986
+ if (withServer) body.server = server;
8846
8987
  return (await this.client.post(`/api/hosting/${this.id}/deploy`, body)).deploy;
8847
8988
  }
8848
8989
  async update({ label } = {}) {
@@ -8863,14 +9004,18 @@ var Host = class {
8863
9004
  return this.client.delete(`/api/hosting/${this.id}`);
8864
9005
  }
8865
9006
  };
8866
- async function readFiles(input) {
9007
+ var DIRECT_UPLOAD_ABOVE = 8 * 1024 * 1024;
9008
+ var PACKS_IN_FLIGHT = 3;
9009
+ var PACK_TIMEOUT_MS = 5 * 60 * 1e3;
9010
+ var FINISH_TIMEOUT_MS = 10 * 60 * 1e3;
9011
+ async function collectFiles(input) {
8867
9012
  if (Array.isArray(input)) {
8868
9013
  const files = input.map((file) => {
8869
9014
  const path2 = String(file?.path ?? "").replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "");
8870
9015
  if (!path2) throw new IaGenifyError(400, "nothing_to_deploy", "Every file needs a path.");
8871
9016
  if (NEVER_DEPLOY2.some((rule) => rule.test(path2))) return null;
8872
9017
  const bytes = typeof file?.content === "string" ? new TextEncoder().encode(file.content) : new Uint8Array(file?.content ?? []);
8873
- return { path: path2, content: toBase64(bytes) };
9018
+ return { path: path2, size: bytes.length, load: async () => bytes };
8874
9019
  }).filter(Boolean);
8875
9020
  if (!files.length) throw new IaGenifyError(400, "nothing_to_deploy", "No deployable files were provided.");
8876
9021
  return files;
@@ -8892,7 +9037,10 @@ async function readFiles(input) {
8892
9037
  const relative = path.relative(root, full).split(path.sep).join("/");
8893
9038
  if (NEVER_DEPLOY2.some((rule) => rule.test(relative))) continue;
8894
9039
  if (entry.isDirectory()) await visit(full);
8895
- else if (entry.isFile()) result.push({ path: relative, content: (await fs.readFile(full)).toString("base64") });
9040
+ else if (entry.isFile()) {
9041
+ const { size } = await fs.stat(full);
9042
+ result.push({ path: relative, size, load: async () => new Uint8Array(await fs.readFile(full)) });
9043
+ }
8896
9044
  }
8897
9045
  };
8898
9046
  try {
@@ -8904,6 +9052,80 @@ async function readFiles(input) {
8904
9052
  if (!result.length) throw new IaGenifyError(400, "nothing_to_deploy", `The folder "${input}" contains no deployable files.`);
8905
9053
  return result;
8906
9054
  }
9055
+ async function hashBytes(bytes) {
9056
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", bytes));
9057
+ let hex = "";
9058
+ for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
9059
+ return hex.slice(0, 32);
9060
+ }
9061
+ function planPacks(hashes, sizeOf, { maxBytes, maxFiles }) {
9062
+ const packs = [];
9063
+ let current = [];
9064
+ let bytes = 0;
9065
+ for (const hash of hashes) {
9066
+ const size = sizeOf(hash);
9067
+ if (current.length && (bytes + size > maxBytes || current.length >= maxFiles)) {
9068
+ packs.push(current);
9069
+ current = [];
9070
+ bytes = 0;
9071
+ }
9072
+ current.push(hash);
9073
+ bytes += size;
9074
+ }
9075
+ if (current.length) packs.push(current);
9076
+ return packs;
9077
+ }
9078
+ async function deployDirect(client, hostId, entries, server) {
9079
+ const base2 = `/api/hosting/${hostId}/uploads`;
9080
+ const byHash = /* @__PURE__ */ new Map();
9081
+ const manifest = [];
9082
+ for (const entry of entries) {
9083
+ const hash = await hashBytes(await entry.load());
9084
+ manifest.push({ path: entry.path, size: entry.size, hash });
9085
+ if (!byHash.has(hash)) byHash.set(hash, entry);
9086
+ }
9087
+ const { upload } = await client.post(base2, { files: manifest, ...server !== void 0 ? { server } : {} });
9088
+ const send = async (missing2) => {
9089
+ const packs = planPacks(
9090
+ missing2.filter((hash) => byHash.has(hash)),
9091
+ (hash) => byHash.get(hash).size,
9092
+ { maxBytes: upload.packBytes, maxFiles: upload.packFiles }
9093
+ );
9094
+ let next = 0;
9095
+ const worker = async () => {
9096
+ while (next < packs.length) {
9097
+ const pack = packs[next++];
9098
+ const parts = await Promise.all(pack.map((hash) => byHash.get(hash).load()));
9099
+ const body = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
9100
+ let offset = 0;
9101
+ for (const part of parts) {
9102
+ body.set(part, offset);
9103
+ offset += part.length;
9104
+ }
9105
+ const header = pack.map((hash) => `${hash}:${byHash.get(hash).size}`).join(",");
9106
+ for (let attempt = 1; ; attempt++) {
9107
+ try {
9108
+ await client.put(`${base2}/${upload.id}/parts`, body, { headers: { "X-IaGenify-Parts": header }, timeout: PACK_TIMEOUT_MS });
9109
+ break;
9110
+ } catch (error) {
9111
+ const transient = !error?.status || error.status >= 500 || error.status === 429;
9112
+ if (!transient || attempt >= 3) throw error;
9113
+ await new Promise((resolve) => setTimeout(resolve, 1e3 * attempt));
9114
+ }
9115
+ }
9116
+ }
9117
+ };
9118
+ await Promise.all(Array.from({ length: Math.min(PACKS_IN_FLIGHT, packs.length) }, worker));
9119
+ };
9120
+ await send(upload.missing || []);
9121
+ try {
9122
+ return (await client.post(`${base2}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
9123
+ } catch (error) {
9124
+ if (error?.code !== "upload_incomplete" || !Array.isArray(error.details?.missing)) throw error;
9125
+ await send(error.details.missing);
9126
+ return (await client.post(`${base2}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
9127
+ }
9128
+ }
8907
9129
  function toBase64(bytes) {
8908
9130
  if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
8909
9131
  let binary = "";
@@ -8915,10 +9137,10 @@ var HostsResource = class {
8915
9137
  this.client = client;
8916
9138
  }
8917
9139
  /** `runtime` is the public contract. `kind` remains accepted for one upgrade cycle. */
8918
- async create({ runtime, framework, label, slug, kind } = {}) {
9140
+ async create({ runtime, framework, label, slug: slug2, kind } = {}) {
8919
9141
  const rule = assertRuntime(runtime || LEGACY_RUNTIME[kind], framework);
8920
9142
  const resolvedRuntime = runtime || LEGACY_RUNTIME[kind];
8921
- const res = await this.client.post("/api/hosting", { runtime: resolvedRuntime, framework, label, slug });
9143
+ const res = await this.client.post("/api/hosting", { runtime: resolvedRuntime, framework, label, slug: slug2 });
8922
9144
  return new Host(this.client, res.host, { framework });
8923
9145
  }
8924
9146
  async list() {
@@ -9312,8 +9534,8 @@ var Contacts = class {
9312
9534
  /** `avatar` est rendu absolu ici : l'API rend un chemin, elle ignore sous quel nom on l'atteint. */
9313
9535
  _absolu(contact) {
9314
9536
  if (!contact) return contact;
9315
- const base = typeof this.client?.baseUrl === "string" ? this.client.baseUrl : "";
9316
- return contact.avatar?.startsWith("/") && base ? { ...contact, avatar: `${base}${contact.avatar}` } : contact;
9537
+ const base2 = typeof this.client?.baseUrl === "string" ? this.client.baseUrl : "";
9538
+ return contact.avatar?.startsWith("/") && base2 ? { ...contact, avatar: `${base2}${contact.avatar}` } : contact;
9317
9539
  }
9318
9540
  async list() {
9319
9541
  const res = await this.client.get("/api/mail/contacts");
@@ -9404,6 +9626,955 @@ var MailResource = class {
9404
9626
  }
9405
9627
  };
9406
9628
 
9629
+ // src/studio/errors.js
9630
+ var StudioError = class extends Error {
9631
+ constructor(code, message, details = void 0, status = 400) {
9632
+ super(message);
9633
+ this.name = "StudioError";
9634
+ this.status = status;
9635
+ this.code = code;
9636
+ if (details !== void 0) this.details = details;
9637
+ }
9638
+ };
9639
+
9640
+ // src/studio/format.js
9641
+ var FORMAT = "iagenify.design";
9642
+ var FORMAT_VERSION = 1;
9643
+ var NODE_TYPES = ["frame", "text", "image", "shape"];
9644
+ var CONTENEURS = /* @__PURE__ */ new Set(["frame"]);
9645
+ var TAGS = {
9646
+ frame: ["div", "section", "header", "footer", "nav", "main", "article", "aside", "figure", "ul", "li", "a", "button"],
9647
+ text: ["p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "a", "button", "li", "small", "strong", "em", "label"],
9648
+ image: ["img"],
9649
+ shape: ["div"]
9650
+ };
9651
+ var DEFAULT_TAG = { frame: "div", text: "p", image: "img", shape: "div" };
9652
+ var CHAMPS_NOEUD = /* @__PURE__ */ new Set(["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"]);
9653
+ var CHAMPS = {
9654
+ 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" },
9655
+ size: { w: "dimension", h: "dimension", minW: "longueur", minH: "longueur", maxW: "longueur", maxH: "longueur" },
9656
+ position: { x: "nombre", y: "nombre", absolute: "booleen" },
9657
+ style: { fill: "remplissage", stroke: "trait", radius: "rayon", shadow: "ombres", opacity: "opacite", clip: "booleen" },
9658
+ 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"] },
9659
+ image: { src: "source", fit: ["cover", "contain", "fill"] },
9660
+ shape: { kind: ["rect", "ellipse", "line"] }
9661
+ };
9662
+ 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;
9663
+ var POLICE = /^[A-Za-z0-9 \-]{1,64}$/;
9664
+ var SOURCE = /^asset:[A-Za-z0-9_\-]{1,64}$/;
9665
+ var fini = (v) => typeof v === "number" && Number.isFinite(v);
9666
+ function isColor(v) {
9667
+ return typeof v === "string" && COULEUR.test(v.trim());
9668
+ }
9669
+ function verifierValeur(regle, v) {
9670
+ if (Array.isArray(regle)) return regle.includes(v) ? null : `valeur_non_permise (${regle.join(", ")})`;
9671
+ switch (regle) {
9672
+ case "booleen":
9673
+ return typeof v === "boolean" ? null : "booleen_attendu";
9674
+ case "nombre":
9675
+ return fini(v) ? null : "nombre_attendu";
9676
+ case "entier":
9677
+ return Number.isInteger(v) && v >= 1 && v <= 24 ? null : "entier_1_24_attendu";
9678
+ case "longueur":
9679
+ return fini(v) && v >= 0 && v <= 1e5 ? null : "longueur_positive_attendue";
9680
+ case "dimension":
9681
+ return v === "hug" || v === "fill" || fini(v) && v >= 0 && v <= 1e5 ? null : "hug_fill_ou_longueur_attendu";
9682
+ case "padding":
9683
+ if (fini(v) && v >= 0) return null;
9684
+ if (Array.isArray(v) && (v.length === 2 || v.length === 4) && v.every((x) => fini(x) && x >= 0)) return null;
9685
+ return "padding_nombre_ou_liste_2_4";
9686
+ case "rayon":
9687
+ if (fini(v) && v >= 0) return null;
9688
+ if (Array.isArray(v) && v.length === 4 && v.every((x) => fini(x) && x >= 0)) return null;
9689
+ return "rayon_nombre_ou_liste_4";
9690
+ case "opacite":
9691
+ return fini(v) && v >= 0 && v <= 1 ? null : "opacite_0_1";
9692
+ case "couleur":
9693
+ return isColor(v) ? null : "couleur_invalide";
9694
+ case "remplissage":
9695
+ if (isColor(v)) return null;
9696
+ if (v && typeof v === "object" && v.type === "linear") {
9697
+ const cles = Object.keys(v).filter((k) => !["type", "angle", "stops"].includes(k));
9698
+ if (cles.length) return `champ_inconnu (${cles[0]})`;
9699
+ if (!fini(v.angle)) return "angle_attendu";
9700
+ if (!Array.isArray(v.stops) || v.stops.length < 2 || v.stops.length > 8) return "2_a_8_arrets";
9701
+ 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";
9702
+ return null;
9703
+ }
9704
+ return "couleur_ou_degrade_attendu";
9705
+ case "trait":
9706
+ if (v && typeof v === "object" && isColor(v.color) && fini(v.width) && v.width >= 0 && v.width <= 100 && Object.keys(v).length === 2) return null;
9707
+ return "trait_{color,width}_attendu";
9708
+ case "ombres":
9709
+ if (!Array.isArray(v) || v.length > 4) return "liste_de_4_ombres_max";
9710
+ for (const o of v) {
9711
+ if (!o || typeof o !== "object") return "ombre_invalide";
9712
+ const cles = Object.keys(o).filter((k) => !["x", "y", "blur", "spread", "color", "inset"].includes(k));
9713
+ if (cles.length) return `champ_inconnu (${cles[0]})`;
9714
+ 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";
9715
+ }
9716
+ return null;
9717
+ case "texte":
9718
+ return typeof v === "string" && v.length <= 2e4 ? null : "texte_attendu";
9719
+ case "police":
9720
+ return typeof v === "string" && POLICE.test(v) ? null : "nom_de_police_invalide";
9721
+ case "graisse":
9722
+ return Number.isInteger(v) && v >= 100 && v <= 900 && v % 100 === 0 ? null : "graisse_100_a_900";
9723
+ case "interligne":
9724
+ return fini(v) && v > 0 && v <= 10 ? null : "interligne_0_10";
9725
+ case "source":
9726
+ return typeof v === "string" && SOURCE.test(v) ? null : "source_asset:<id>_attendue";
9727
+ default:
9728
+ return "regle_inconnue";
9729
+ }
9730
+ }
9731
+ function verifierGroupe(groupe, objet, chemin, erreurs) {
9732
+ if (objet === void 0) return;
9733
+ if (!objet || typeof objet !== "object" || Array.isArray(objet)) {
9734
+ erreurs.push({ path: chemin, reason: "objet_attendu" });
9735
+ return;
9736
+ }
9737
+ const regles = CHAMPS[groupe];
9738
+ for (const [cle, valeur] of Object.entries(objet)) {
9739
+ if (!(cle in regles)) {
9740
+ erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
9741
+ continue;
9742
+ }
9743
+ if (valeur === null && ["stroke", "shadow"].includes(cle)) continue;
9744
+ const motif = verifierValeur(regles[cle], valeur);
9745
+ if (motif) erreurs.push({ path: `${chemin}.${cle}`, reason: motif });
9746
+ }
9747
+ }
9748
+ function validateNode(node4, chemin = "node") {
9749
+ const erreurs = [];
9750
+ if (!node4 || typeof node4 !== "object" || Array.isArray(node4)) return [{ path: chemin, reason: "objet_attendu" }];
9751
+ for (const cle of Object.keys(node4)) if (!CHAMPS_NOEUD.has(cle)) erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
9752
+ if (!NODE_TYPES.includes(node4.type)) erreurs.push({ path: `${chemin}.type`, reason: `type_inconnu (${NODE_TYPES.join(", ")})` });
9753
+ if (typeof node4.name !== "string" || !node4.name.trim() || node4.name.length > 120) erreurs.push({ path: `${chemin}.name`, reason: "nom_1_a_120_caracteres" });
9754
+ if (node4.as !== void 0 && !(TAGS[node4.type] || []).includes(node4.as)) erreurs.push({ path: `${chemin}.as`, reason: "balise_non_permise" });
9755
+ if (node4.alt !== void 0 && (typeof node4.alt !== "string" || node4.alt.length > 500)) erreurs.push({ path: `${chemin}.alt`, reason: "texte_500_max" });
9756
+ for (const groupe of ["layout", "size", "position", "style", "text", "image", "shape"]) verifierGroupe(groupe, node4[groupe], `${chemin}.${groupe}`, erreurs);
9757
+ if (node4.type !== "frame" && node4.layout !== void 0) erreurs.push({ path: `${chemin}.layout`, reason: "seul_un_cadre_a_une_mise_en_page" });
9758
+ if (node4.type !== "text" && node4.text !== void 0) erreurs.push({ path: `${chemin}.text`, reason: "seul_un_texte_a_du_texte" });
9759
+ if (node4.type === "text" && typeof node4.text?.content !== "string") erreurs.push({ path: `${chemin}.text.content`, reason: "texte_attendu" });
9760
+ if (node4.type !== "image" && node4.image !== void 0) erreurs.push({ path: `${chemin}.image`, reason: "seule_une_image_a_une_source" });
9761
+ if (node4.type === "image" && typeof node4.image?.src !== "string") erreurs.push({ path: `${chemin}.image.src`, reason: "source_asset:<id>_attendue" });
9762
+ if (node4.type !== "shape" && node4.shape !== void 0) erreurs.push({ path: `${chemin}.shape`, reason: "seule_une_forme_a_un_genre" });
9763
+ if (CONTENEURS.has(node4.type)) {
9764
+ if (!Array.isArray(node4.children)) erreurs.push({ path: `${chemin}.children`, reason: "liste_attendue" });
9765
+ } else if (node4.children !== void 0) erreurs.push({ path: `${chemin}.children`, reason: "ce_type_n_a_pas_d_enfants" });
9766
+ return erreurs;
9767
+ }
9768
+ function isContainer(node4) {
9769
+ return CONTENEURS.has(node4?.type);
9770
+ }
9771
+ function createDocument() {
9772
+ return { format: FORMAT, version: FORMAT_VERSION, meta: { nextId: 1 }, pages: [{ id: "p_1", name: "Page 1", frames: [] }], nodes: {} };
9773
+ }
9774
+ function validate(doc) {
9775
+ const erreurs = [];
9776
+ const err = (path, reason) => erreurs.push({ path, reason });
9777
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) return { ok: false, errors: [{ path: "", reason: "objet_attendu" }] };
9778
+ for (const cle of Object.keys(doc)) if (!["format", "version", "meta", "pages", "nodes"].includes(cle)) err(cle, "champ_inconnu");
9779
+ if (doc.format !== FORMAT) err("format", `attendu_${FORMAT}`);
9780
+ if (doc.version !== FORMAT_VERSION) err("version", `version_${FORMAT_VERSION}_attendue`);
9781
+ if (!doc.meta || !Number.isInteger(doc.meta.nextId) || doc.meta.nextId < 1 || Object.keys(doc.meta).length !== 1) err("meta", "meta_{nextId}_attendu");
9782
+ if (!doc.nodes || typeof doc.nodes !== "object" || Array.isArray(doc.nodes)) {
9783
+ err("nodes", "objet_attendu");
9784
+ return { ok: false, errors: erreurs };
9785
+ }
9786
+ if (!Array.isArray(doc.pages) || doc.pages.length === 0) {
9787
+ err("pages", "au_moins_une_page");
9788
+ return { ok: false, errors: erreurs };
9789
+ }
9790
+ const parents = /* @__PURE__ */ new Map();
9791
+ const cite = (id, path) => {
9792
+ if (typeof id !== "string" || !Object.hasOwn(doc.nodes, id)) {
9793
+ err(path, "enfant_inexistant");
9794
+ return;
9795
+ }
9796
+ parents.set(id, (parents.get(id) || 0) + 1);
9797
+ };
9798
+ const idsPages = /* @__PURE__ */ new Set();
9799
+ doc.pages.forEach((p, i) => {
9800
+ const c = `pages[${i}]`;
9801
+ if (!p || typeof p !== "object") return err(c, "objet_attendu");
9802
+ for (const cle of Object.keys(p)) if (!["id", "name", "route", "frames"].includes(cle)) err(`${c}.${cle}`, "champ_inconnu");
9803
+ 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");
9804
+ idsPages.add(p.id);
9805
+ if (typeof p.name !== "string" || !p.name.trim() || p.name.length > 120) err(`${c}.name`, "nom_1_a_120_caracteres");
9806
+ if (p.route !== void 0 && (typeof p.route !== "string" || !/^\/[a-z0-9\-/[\]]*$/.test(p.route))) err(`${c}.route`, "route_invalide");
9807
+ if (!Array.isArray(p.frames)) return err(`${c}.frames`, "liste_attendue");
9808
+ p.frames.forEach((id, k) => {
9809
+ cite(id, `${c}.frames[${k}]`);
9810
+ if (typeof id === "string" && Object.hasOwn(doc.nodes, id) && doc.nodes[id]?.type !== "frame") {
9811
+ err(`${c}.frames[${k}]`, "une_page_ne_contient_que_des_cadres");
9812
+ }
9813
+ });
9814
+ });
9815
+ const limite = doc.meta?.nextId ?? 1;
9816
+ for (const [id, node4] of Object.entries(doc.nodes)) {
9817
+ const c = `nodes.${id}`;
9818
+ if (!/^n_[0-9a-z]+$/.test(id)) err(c, "id_invalide");
9819
+ else if (parseInt(id.slice(2), 36) >= limite) err(c, "id_au_dela_du_compteur");
9820
+ if (node4?.id !== id) err(`${c}.id`, "id_different_de_la_cle");
9821
+ erreurs.push(...validateNode(node4, c));
9822
+ if (Array.isArray(node4?.children)) node4.children.forEach((enfant, k) => cite(enfant, `${c}.children[${k}]`));
9823
+ }
9824
+ for (const id of Object.keys(doc.nodes)) {
9825
+ const n = parents.get(id) || 0;
9826
+ if (n === 0) err(`nodes.${id}`, "noeud_orphelin");
9827
+ if (n > 1) err(`nodes.${id}`, "noeud_a_plusieurs_parents");
9828
+ }
9829
+ if (erreurs.length) return { ok: false, errors: erreurs };
9830
+ const vus = /* @__PURE__ */ new Set();
9831
+ const pile = doc.pages.flatMap((p) => p.frames);
9832
+ while (pile.length) {
9833
+ const id = pile.pop();
9834
+ vus.add(id);
9835
+ for (const enfant of doc.nodes[id].children || []) pile.push(enfant);
9836
+ }
9837
+ for (const id of Object.keys(doc.nodes)) if (!vus.has(id)) err(`nodes.${id}`, "cycle");
9838
+ return { ok: erreurs.length === 0, errors: erreurs };
9839
+ }
9840
+ function assertValid(doc) {
9841
+ const r = validate(doc);
9842
+ 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) });
9843
+ return doc;
9844
+ }
9845
+ var ORDRE_NOEUD = ["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"];
9846
+ var ordonner = (objet, ordre) => {
9847
+ const out = {};
9848
+ for (const k of ordre) if (objet[k] !== void 0) out[k] = objet[k];
9849
+ return out;
9850
+ };
9851
+ function canonical(doc) {
9852
+ const nodes = {};
9853
+ const ids = Object.keys(doc.nodes).sort((a, b) => parseInt(a.slice(2), 36) - parseInt(b.slice(2), 36));
9854
+ for (const id of ids) {
9855
+ const n = ordonner(doc.nodes[id], ORDRE_NOEUD);
9856
+ for (const g of Object.keys(CHAMPS)) if (n[g] && typeof n[g] === "object") n[g] = ordonner(n[g], Object.keys(CHAMPS[g]));
9857
+ nodes[id] = n;
9858
+ }
9859
+ return {
9860
+ format: doc.format,
9861
+ version: doc.version,
9862
+ meta: { nextId: doc.meta.nextId },
9863
+ pages: doc.pages.map((p) => ordonner({ ...p, frames: [...p.frames] }, ["id", "name", "route", "frames"])),
9864
+ nodes
9865
+ };
9866
+ }
9867
+ function migrate(doc) {
9868
+ if (doc && doc.version === FORMAT_VERSION) return doc;
9869
+ throw new StudioError("studio_document_invalid", `Version de document non prise en charge : ${doc?.version}`, { errors: [{ path: "version", reason: `version_${FORMAT_VERSION}_attendue` }] });
9870
+ }
9871
+
9872
+ // src/studio/ops.js
9873
+ var GROUPES = /* @__PURE__ */ new Set(["layout", "size", "position", "style", "text", "image", "shape"]);
9874
+ var SIMPLES = /* @__PURE__ */ new Set(["name", "as", "alt"]);
9875
+ var refus = (index, reason, message) => {
9876
+ throw new StudioError("studio_op_invalid", message || `Op\xE9ration ${index} refus\xE9e : ${reason}`, { index, reason });
9877
+ };
9878
+ function nouvelId(doc) {
9879
+ const id = `n_${doc.meta.nextId.toString(36)}`;
9880
+ doc.meta.nextId += 1;
9881
+ return id;
9882
+ }
9883
+ function emplacement(doc, id) {
9884
+ for (const p of doc.pages) {
9885
+ const i = p.frames.indexOf(id);
9886
+ if (i >= 0) return { parent: p.id, liste: p.frames, index: i };
9887
+ }
9888
+ for (const n of Object.values(doc.nodes)) if (n.children) {
9889
+ const i = n.children.indexOf(id);
9890
+ if (i >= 0) return { parent: n.id, liste: n.children, index: i };
9891
+ }
9892
+ return null;
9893
+ }
9894
+ function listeDuParent(doc, parent, type, index) {
9895
+ const page = doc.pages.find((p) => p.id === parent);
9896
+ if (page) {
9897
+ if (type !== "frame") refus(index, "une_page_ne_contient_que_des_cadres");
9898
+ return page.frames;
9899
+ }
9900
+ const n = doc.nodes[parent];
9901
+ if (!n) refus(index, "parent_introuvable");
9902
+ if (!isContainer(n)) refus(index, "le_parent_n_est_pas_un_cadre");
9903
+ return n.children;
9904
+ }
9905
+ function sousArbre(doc, id, acc = {}) {
9906
+ const n = doc.nodes[id];
9907
+ acc[id] = n;
9908
+ for (const e of n.children || []) sousArbre(doc, e, acc);
9909
+ return acc;
9910
+ }
9911
+ function placer(liste, id, index, iop) {
9912
+ const i = index === void 0 ? liste.length : index;
9913
+ if (!Number.isInteger(i) || i < 0 || i > liste.length) refus(iop, "index_hors_limites");
9914
+ liste.splice(i, 0, id);
9915
+ return i;
9916
+ }
9917
+ function aplatir(doc, brut, iop, acc) {
9918
+ if (!brut || typeof brut !== "object" || Array.isArray(brut)) refus(iop, "noeud_objet_attendu");
9919
+ if ("id" in brut) refus(iop, "un_id_ne_se_choisit_pas");
9920
+ const { children, ...reste } = brut;
9921
+ const id = nouvelId(doc);
9922
+ const node4 = { id, ...reste };
9923
+ if (isContainer(node4)) {
9924
+ if (children !== void 0 && !Array.isArray(children)) refus(iop, "children_liste_attendue");
9925
+ node4.children = (children || []).map((c) => aplatir(doc, c, iop, acc));
9926
+ } else if (children !== void 0) refus(iop, "ce_type_n_a_pas_d_enfants");
9927
+ const erreurs = validateNode(node4, "node");
9928
+ if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
9929
+ acc[id] = node4;
9930
+ return id;
9931
+ }
9932
+ function estDescendant(doc, ancetre, id) {
9933
+ const n = doc.nodes[ancetre];
9934
+ return (n?.children || []).some((e) => e === id || estDescendant(doc, e, id));
9935
+ }
9936
+ function lire(node4, path) {
9937
+ const [a, b] = path.split(".");
9938
+ if (b === void 0) return node4[a];
9939
+ return node4[a]?.[b];
9940
+ }
9941
+ function appliquerUne(doc, op, iop, inverses, created, removed) {
9942
+ if (!op || typeof op !== "object") refus(iop, "operation_objet_attendue");
9943
+ switch (op.op) {
9944
+ case "set": {
9945
+ const node4 = doc.nodes[op.id];
9946
+ if (!node4) refus(iop, "noeud_introuvable");
9947
+ if (typeof op.path !== "string") refus(iop, "chemin_attendu");
9948
+ const [a, b, ...trop] = op.path.split(".");
9949
+ if (trop.length || !(SIMPLES.has(a) && b === void 0) && !GROUPES.has(a)) refus(iop, "chemin_non_modifiable");
9950
+ const avant = lire(node4, op.path);
9951
+ const copie2 = structuredClone(node4);
9952
+ if (b === void 0) {
9953
+ if (op.value === void 0) delete copie2[a];
9954
+ else copie2[a] = structuredClone(op.value);
9955
+ } else {
9956
+ const groupe = { ...copie2[a] || {} };
9957
+ if (op.value === void 0) delete groupe[b];
9958
+ else groupe[b] = structuredClone(op.value);
9959
+ if (Object.keys(groupe).length) copie2[a] = groupe;
9960
+ else delete copie2[a];
9961
+ }
9962
+ const erreurs = validateNode(copie2, op.id);
9963
+ if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
9964
+ doc.nodes[op.id] = copie2;
9965
+ inverses.push({ op: "set", id: op.id, path: op.path, value: avant === void 0 ? void 0 : structuredClone(avant) });
9966
+ return;
9967
+ }
9968
+ case "insert": {
9969
+ const acc = {};
9970
+ const racine = aplatir(doc, op.node, iop, acc);
9971
+ const liste = listeDuParent(doc, op.parent, acc[racine].type, iop);
9972
+ Object.assign(doc.nodes, acc);
9973
+ placer(liste, racine, op.index, iop);
9974
+ created.push(...Object.keys(acc));
9975
+ inverses.push({ op: "remove", id: racine });
9976
+ return;
9977
+ }
9978
+ case "move": {
9979
+ const node4 = doc.nodes[op.id];
9980
+ if (!node4) refus(iop, "noeud_introuvable");
9981
+ if (op.parent === op.id || estDescendant(doc, op.id, op.parent)) refus(iop, "deplacement_dans_son_propre_descendant");
9982
+ const ici = emplacement(doc, op.id);
9983
+ const liste = listeDuParent(doc, op.parent, node4.type, iop);
9984
+ ici.liste.splice(ici.index, 1);
9985
+ placer(liste, op.id, op.index, iop);
9986
+ inverses.push({ op: "move", id: op.id, parent: ici.parent, index: ici.index });
9987
+ return;
9988
+ }
9989
+ case "remove": {
9990
+ if (!doc.nodes[op.id]) refus(iop, "noeud_introuvable");
9991
+ const ici = emplacement(doc, op.id);
9992
+ const arbre = sousArbre(doc, op.id);
9993
+ ici.liste.splice(ici.index, 1);
9994
+ for (const id of Object.keys(arbre)) delete doc.nodes[id];
9995
+ removed.push(...Object.keys(arbre));
9996
+ inverses.push({ op: "restore", parent: ici.parent, index: ici.index, root: op.id, nodes: arbre });
9997
+ return;
9998
+ }
9999
+ case "restore": {
10000
+ if (!op.__interne) refus(iop, "operation_inconnue");
10001
+ const liste = listeDuParent(doc, op.parent, op.nodes[op.root].type, iop);
10002
+ Object.assign(doc.nodes, structuredClone(op.nodes));
10003
+ placer(liste, op.root, op.index, iop);
10004
+ inverses.push({ op: "remove", id: op.root });
10005
+ return;
10006
+ }
10007
+ default:
10008
+ refus(iop, "operation_inconnue");
10009
+ }
10010
+ }
10011
+ function applyOps(doc, ops, { internal = false } = {}) {
10012
+ if (!Array.isArray(ops)) throw new StudioError("studio_op_invalid", "Un lot d'op\xE9rations est une liste.", { index: -1, reason: "liste_attendue" });
10013
+ const copie2 = structuredClone(doc);
10014
+ const inverses = [];
10015
+ const created = [];
10016
+ const removed = [];
10017
+ ops.forEach((op, i) => appliquerUne(copie2, internal && op?.op === "restore" ? { ...op, __interne: true } : op, i, inverses, created, removed));
10018
+ return { doc: copie2, inverse: inverses.reverse(), created, removed };
10019
+ }
10020
+
10021
+ // src/studio/style.js
10022
+ var px = (v) => `${+v.toFixed(3)}px`;
10023
+ var ALIGN = { start: "flex-start", center: "center", end: "flex-end", stretch: "stretch" };
10024
+ var JUSTIFY = { start: "flex-start", center: "center", end: "flex-end", between: "space-between" };
10025
+ function remplissage(f) {
10026
+ if (typeof f === "string") return f;
10027
+ return `linear-gradient(${+f.angle.toFixed(3)}deg, ${f.stops.map((s) => `${s.color} ${+(s.at * 100).toFixed(3)}%`).join(", ")})`;
10028
+ }
10029
+ function padding(p) {
10030
+ if (typeof p === "number") return px(p);
10031
+ return p.map(px).join(" ");
10032
+ }
10033
+ function taille(decl, axe, v, parent) {
10034
+ if (v === void 0) return;
10035
+ const prop = axe === "w" ? "width" : "height";
10036
+ const mode = parent?.layout?.mode;
10037
+ const dir = parent?.layout?.direction || "row";
10038
+ const principal = mode === "flex" && (axe === "w" && dir === "row" || axe === "h" && dir === "column");
10039
+ if (typeof v === "number") {
10040
+ decl.push([prop, px(v)]);
10041
+ if (principal) decl.push(["flex-shrink", "0"]);
10042
+ } else if (v === "fill") {
10043
+ if (principal) decl.push(["flex", "1 1 0"], [axe === "w" ? "min-width" : "min-height", "0"]);
10044
+ else if (mode === "flex") decl.push(["align-self", "stretch"]);
10045
+ else decl.push([prop, "100%"]);
10046
+ } else if (v === "hug") {
10047
+ decl.push([prop, "fit-content"]);
10048
+ }
10049
+ }
10050
+ function nodeCss(node4, parent = null) {
10051
+ const d = [];
10052
+ const pos = node4.position;
10053
+ if (parent?.layout?.mode === "free" || pos?.absolute) {
10054
+ d.push(["position", "absolute"], ["left", px(pos?.x ?? 0)], ["top", px(pos?.y ?? 0)]);
10055
+ }
10056
+ const l = node4.layout;
10057
+ if (node4.type === "frame") {
10058
+ if (l?.mode === "grid") {
10059
+ d.push(["display", "grid"], ["grid-template-columns", `repeat(${l.columns || 2}, minmax(0, 1fr))`]);
10060
+ } else if (l?.mode === "free") {
10061
+ if (!d.some(([p]) => p === "position")) d.push(["position", "relative"]);
10062
+ } else {
10063
+ d.push(["display", "flex"], ["flex-direction", l?.direction || "column"]);
10064
+ if (l?.wrap) d.push(["flex-wrap", "wrap"]);
10065
+ if (l?.align) d.push(["align-items", ALIGN[l.align]]);
10066
+ if (l?.justify) d.push(["justify-content", JUSTIFY[l.justify]]);
10067
+ }
10068
+ if (l?.gap !== void 0 && l.mode !== "free") d.push(["gap", px(l.gap)]);
10069
+ if (l?.padding !== void 0) d.push(["padding", padding(l.padding)]);
10070
+ }
10071
+ taille(d, "w", node4.size?.w, parent);
10072
+ taille(d, "h", node4.size?.h, parent);
10073
+ for (const [k, prop] of [["minW", "min-width"], ["minH", "min-height"], ["maxW", "max-width"], ["maxH", "max-height"]]) {
10074
+ if (node4.size?.[k] !== void 0) d.push([prop, px(node4.size[k])]);
10075
+ }
10076
+ const s = node4.style || {};
10077
+ if (s.fill !== void 0 && node4.type !== "text") d.push(["background", remplissage(s.fill)]);
10078
+ if (s.stroke) d.push(["border", `${px(s.stroke.width)} solid ${s.stroke.color}`]);
10079
+ if (node4.type === "shape" && node4.shape?.kind === "ellipse") d.push(["border-radius", "50%"]);
10080
+ else if (s.radius !== void 0) d.push(["border-radius", typeof s.radius === "number" ? px(s.radius) : s.radius.map(px).join(" ")]);
10081
+ 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(", ")]);
10082
+ if (s.opacity !== void 0 && s.opacity !== 1) d.push(["opacity", String(s.opacity)]);
10083
+ if (s.clip) d.push(["overflow", "hidden"]);
10084
+ if (node4.type === "shape" && node4.shape?.kind === "line") d.push(["height", "0"], ["border-top", `${px(s.stroke?.width ?? 1)} solid ${s.stroke?.color ?? "#000000"}`]);
10085
+ const t = node4.text;
10086
+ if (node4.type === "text") {
10087
+ if (t.font) d.push(["font-family", `"${t.font}", sans-serif`]);
10088
+ if (t.size !== void 0) d.push(["font-size", px(t.size)]);
10089
+ if (t.weight !== void 0) d.push(["font-weight", String(t.weight)]);
10090
+ if (t.lineHeight !== void 0) d.push(["line-height", String(t.lineHeight)]);
10091
+ if (t.letterSpacing !== void 0) d.push(["letter-spacing", px(t.letterSpacing)]);
10092
+ if (t.align) d.push(["text-align", t.align]);
10093
+ if (t.transform && t.transform !== "none") d.push(["text-transform", t.transform]);
10094
+ d.push(["color", t.color || "#000000"]);
10095
+ if (s.fill !== void 0) d.push(["background", remplissage(s.fill)]);
10096
+ d.push(["white-space", "pre-wrap"]);
10097
+ }
10098
+ if (node4.type === "image") d.push(["display", "block"], ["object-fit", node4.image.fit || "cover"]);
10099
+ return d;
10100
+ }
10101
+ function tagOf(node4) {
10102
+ return node4.as || DEFAULT_TAG[node4.type];
10103
+ }
10104
+ var BASE_CSS = "*,*::before,*::after{box-sizing:border-box;margin:0}";
10105
+ function parentsOf(doc) {
10106
+ const m = /* @__PURE__ */ new Map();
10107
+ for (const p of doc.pages) for (const id of p.frames) m.set(id, null);
10108
+ for (const n of Object.values(doc.nodes)) for (const e of n.children || []) m.set(e, n);
10109
+ return m;
10110
+ }
10111
+
10112
+ // src/studio/check.js
10113
+ function parseColor(c) {
10114
+ if (!isColor(c)) return null;
10115
+ const s = c.trim().toLowerCase();
10116
+ if (s === "transparent") return [0, 0, 0, 0];
10117
+ if (s.startsWith("#")) {
10118
+ let h = s.slice(1);
10119
+ if (h.length <= 4) h = [...h].map((x) => x + x).join("");
10120
+ const n = (i) => parseInt(h.slice(i, i + 2), 16);
10121
+ return [n(0), n(2), n(4), h.length === 8 ? n(6) / 255 : 1];
10122
+ }
10123
+ const v = s.match(/[\d.]+/g).map(Number);
10124
+ return [v[0], v[1], v[2], v[3] ?? 1];
10125
+ }
10126
+ function luminance([r, g, b]) {
10127
+ const lin = (x) => {
10128
+ x /= 255;
10129
+ return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
10130
+ };
10131
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
10132
+ }
10133
+ var melange = (dessus, fond) => [0, 1, 2].map((i) => dessus[i] * dessus[3] + fond[i] * (1 - dessus[3])).concat(1);
10134
+ function contrastRatio(a, b) {
10135
+ const [l1, l2] = [luminance(a), luminance(b)].sort((x, y) => y - x);
10136
+ return (l1 + 0.05) / (l2 + 0.05);
10137
+ }
10138
+ function fondsSous(doc, id, parents) {
10139
+ const couches = [];
10140
+ let n = doc.nodes[id];
10141
+ if (n.type === "text" && n.style?.fill !== void 0) couches.push(n.style.fill);
10142
+ for (let p = parents.get(id); p; p = parents.get(p.id)) if (p.style?.fill !== void 0) couches.push(p.style.fill);
10143
+ let fonds = [[255, 255, 255, 1]];
10144
+ for (const f of couches.reverse()) {
10145
+ const couleurs = typeof f === "string" ? [parseColor(f)] : f.stops.map((s) => parseColor(s.color));
10146
+ fonds = couleurs.flatMap((c) => fonds.map((base2) => melange(c, base2)));
10147
+ }
10148
+ return fonds;
10149
+ }
10150
+ function check(doc) {
10151
+ const issues = [];
10152
+ const parents = parentsOf(doc);
10153
+ for (const n of Object.values(doc.nodes)) {
10154
+ if (n.type === "text") {
10155
+ const couleur = parseColor(n.text.color || "#000000");
10156
+ const grand = (n.text.size ?? 16) >= 24 || (n.text.size ?? 16) >= 18.66 && (n.text.weight ?? 400) >= 700;
10157
+ const requis = grand ? 3 : 4.5;
10158
+ let pire = null;
10159
+ for (const fond of fondsSous(doc, n.id, parents)) {
10160
+ const ratio = contrastRatio(melange(couleur, fond), fond);
10161
+ if (!pire || ratio < pire.ratio) pire = { ratio, fond };
10162
+ }
10163
+ if (pire && pire.ratio < requis) {
10164
+ const hex = (c) => `#${c.slice(0, 3).map((x) => Math.round(x).toString(16).padStart(2, "0")).join("")}`;
10165
+ 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) } });
10166
+ }
10167
+ }
10168
+ if (n.type === "frame" && n.children.length === 0 && n.style?.fill === void 0 && !n.style?.stroke) {
10169
+ issues.push({ rule: "empty-frame", severity: "warning", node: n.id, name: n.name });
10170
+ }
10171
+ if (n.type === "image" && !n.alt) issues.push({ rule: "image-alt", severity: "warning", node: n.id, name: n.name });
10172
+ }
10173
+ return { issues };
10174
+ }
10175
+
10176
+ // src/studio/emit/html.js
10177
+ var ECHAPPE = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
10178
+ var escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ECHAPPE[c]);
10179
+ function slug(nom) {
10180
+ const s = String(nom).normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
10181
+ return /^[a-z]/.test(s) ? s : `n-${s || "noeud"}`;
10182
+ }
10183
+ function classNames(doc, page) {
10184
+ const prises = /* @__PURE__ */ new Set();
10185
+ const classes = /* @__PURE__ */ new Map();
10186
+ const unique = (base2) => {
10187
+ let c = base2;
10188
+ let k = 2;
10189
+ while (prises.has(c)) c = `${base2}-${k++}`;
10190
+ prises.add(c);
10191
+ return c;
10192
+ };
10193
+ const visiter = (id, racine) => {
10194
+ const n = doc.nodes[id];
10195
+ const c = racine ? unique(`${racine}__${slug(n.name)}`) : unique(slug(n.name));
10196
+ classes.set(id, c);
10197
+ for (const e of n.children || []) visiter(e, racine || c);
10198
+ };
10199
+ for (const id of page.frames) visiter(id, null);
10200
+ return classes;
10201
+ }
10202
+ function emitHtml(doc, { page: pageId, assets = {}, title, lang = "fr" } = {}) {
10203
+ const page = pageId ? doc.pages.find((p) => p.id === pageId) : doc.pages[0];
10204
+ if (!page) throw new StudioError("studio_page_not_found", `Page introuvable : ${pageId}`, void 0, 404);
10205
+ const parents = parentsOf(doc);
10206
+ const classes = classNames(doc, page);
10207
+ const warnings = [];
10208
+ const regles = [BASE_CSS];
10209
+ const html = (id, profondeur) => {
10210
+ const n = doc.nodes[id];
10211
+ const c = classes.get(id);
10212
+ const decl = nodeCss(n, parents.get(id));
10213
+ if (decl.length) regles.push(`.${c}{${decl.map(([p, v]) => `${p}:${v}`).join(";")}}`);
10214
+ const tag = tagOf(n);
10215
+ const pad2 = " ".repeat(profondeur);
10216
+ if (n.type === "image") {
10217
+ const asset = n.image.src.slice("asset:".length);
10218
+ if (n.alt === void 0) warnings.push(`image-alt : \xAB ${n.name} \xBB n'a pas de texte alternatif`);
10219
+ return `${pad2}<img class="${c}" src="${escapeHtml(assets[asset] || `assets/${asset}`)}" alt="${escapeHtml(n.alt ?? "")}">`;
10220
+ }
10221
+ if (n.type === "text") return `${pad2}<${tag} class="${c}">${escapeHtml(n.text.content)}</${tag}>`;
10222
+ const enfants = (n.children || []).map((e) => html(e, profondeur + 1));
10223
+ return enfants.length ? `${pad2}<${tag} class="${c}">
10224
+ ${enfants.join("\n")}
10225
+ ${pad2}</${tag}>` : `${pad2}<${tag} class="${c}"></${tag}>`;
10226
+ };
10227
+ const corps = page.frames.map((id) => html(id, 2)).join("\n");
10228
+ const index = `<!doctype html>
10229
+ <html lang="${escapeHtml(lang)}">
10230
+ <head>
10231
+ <meta charset="utf-8">
10232
+ <meta name="viewport" content="width=device-width, initial-scale=1">
10233
+ <title>${escapeHtml(title || page.name)}</title>
10234
+ <link rel="stylesheet" href="styles.css">
10235
+ </head>
10236
+ <body>
10237
+ ${corps}
10238
+ </body>
10239
+ </html>
10240
+ `;
10241
+ const css = `${regles.join("\n")}
10242
+ `;
10243
+ const octets = (s) => new TextEncoder().encode(s).length;
10244
+ return {
10245
+ target: "html",
10246
+ files: [
10247
+ { path: "index.html", content: index, bytes: octets(index) },
10248
+ { path: "styles.css", content: css, bytes: octets(css) }
10249
+ ],
10250
+ warnings
10251
+ };
10252
+ }
10253
+
10254
+ // src/studio/render.js
10255
+ function renderNode(doc, nodeId, { document: d = globalThis.document, assets = {}, parents = parentsOf(doc) } = {}) {
10256
+ if (!d || typeof d.createElement !== "function") {
10257
+ throw new StudioError("studio_render_unavailable", "Le rendu demande un navigateur (aucun DOM ici).");
10258
+ }
10259
+ const creer = (id) => {
10260
+ const n = doc.nodes[id];
10261
+ const el = d.createElement(tagOf(n));
10262
+ el.setAttribute("data-node-id", id);
10263
+ for (const [prop, valeur] of nodeCss(n, parents.get(id))) el.style.setProperty(prop, valeur);
10264
+ if (n.type === "image") {
10265
+ const asset = n.image.src.slice("asset:".length);
10266
+ el.setAttribute("src", assets[asset] || `assets/${asset}`);
10267
+ el.setAttribute("alt", n.alt ?? "");
10268
+ } else if (n.type === "text") {
10269
+ el.textContent = n.text.content;
10270
+ } else {
10271
+ for (const e of n.children || []) el.appendChild(creer(e));
10272
+ }
10273
+ return el;
10274
+ };
10275
+ if (!doc.nodes[nodeId]) throw new StudioError("studio_node_not_found", `N\u0153ud introuvable : ${nodeId}`, void 0, 404);
10276
+ return creer(nodeId);
10277
+ }
10278
+
10279
+ // src/studio/raster.js
10280
+ var XHTML = "http://www.w3.org/1999/xhtml";
10281
+ async function enData(url) {
10282
+ const reponse = await fetch(url);
10283
+ if (!reponse.ok) throw new StudioError("studio_asset_unavailable", `Ressource illisible pour l'export : ${url} (${reponse.status})`);
10284
+ const blob = await reponse.blob();
10285
+ return await new Promise((ok, ko) => {
10286
+ const f = new FileReader();
10287
+ f.onload = () => ok(f.result);
10288
+ f.onerror = ko;
10289
+ f.readAsDataURL(blob);
10290
+ });
10291
+ }
10292
+ async function policesIncorporees(d) {
10293
+ const regles = [];
10294
+ for (const feuille of d.styleSheets) {
10295
+ let liste;
10296
+ try {
10297
+ liste = feuille.cssRules;
10298
+ } catch {
10299
+ continue;
10300
+ }
10301
+ for (const r of liste) {
10302
+ if (r.type !== 5) continue;
10303
+ let css = r.cssText;
10304
+ const base2 = feuille.href || d.baseURI;
10305
+ for (const [, brut] of css.matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)/g)) {
10306
+ if (brut.startsWith("data:")) continue;
10307
+ css = css.replace(brut, await enData(new URL(brut, base2).href));
10308
+ }
10309
+ regles.push(css);
10310
+ }
10311
+ }
10312
+ return regles.join("\n");
10313
+ }
10314
+ function figerLignes(racine, d) {
10315
+ for (const el of racine.querySelectorAll("[data-node-id]")) {
10316
+ const texte = el.firstChild;
10317
+ if (!texte || texte.nodeType !== 3 || el.childNodes.length !== 1) continue;
10318
+ const t = texte.textContent;
10319
+ const r = d.createRange();
10320
+ let haut = null;
10321
+ let sortie = "";
10322
+ for (let i = 0; i < t.length; i++) {
10323
+ r.setStart(texte, i);
10324
+ r.setEnd(texte, i + 1);
10325
+ const rect = r.getClientRects()[0];
10326
+ if (rect && haut !== null && rect.top > haut + 1 && t[i] !== " " && t[i] !== "\n") sortie = `${sortie.replace(/ +$/, "")}
10327
+ `;
10328
+ if (rect) haut = rect.top;
10329
+ sortie += t[i];
10330
+ }
10331
+ texte.textContent = sortie;
10332
+ el.style.setProperty("white-space", "pre");
10333
+ }
10334
+ }
10335
+ async function renderPng(doc, { frame, scale = 1, assets = {}, document: d = globalThis.document } = {}) {
10336
+ const W = globalThis;
10337
+ if (!d?.body || typeof W.XMLSerializer !== "function" || typeof W.Image !== "function" || typeof W.fetch !== "function") {
10338
+ throw new StudioError("studio_render_unavailable", "L'export d'image se fait dans un navigateur (aucun DOM ici).");
10339
+ }
10340
+ 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" });
10341
+ const id = doc.nodes[frame]?.type === "frame" ? frame : Object.values(doc.nodes).find((n) => n.type === "frame" && n.name === frame)?.id;
10342
+ if (!id) throw new StudioError("studio_node_not_found", `Cadre introuvable : ${frame}`, void 0, 404);
10343
+ const hote = d.createElement("div");
10344
+ hote.setAttribute("aria-hidden", "true");
10345
+ hote.setAttribute("data-studio-raster", "");
10346
+ hote.style.cssText = "position:fixed;left:-100000px;top:0;contain:layout style;pointer-events:none";
10347
+ const base2 = d.createElement("style");
10348
+ base2.textContent = "[data-studio-raster] *,[data-studio-raster] *::before,[data-studio-raster] *::after{box-sizing:border-box;margin:0}";
10349
+ hote.append(base2, renderNode(doc, id, { document: d, assets }));
10350
+ d.body.appendChild(hote);
10351
+ try {
10352
+ const el = hote.lastChild;
10353
+ await d.fonts?.ready;
10354
+ await Promise.all([...el.querySelectorAll("img")].map((img) => img.decode().catch(() => {
10355
+ })));
10356
+ figerLignes(el, d);
10357
+ const rect = el.getBoundingClientRect();
10358
+ const width = Math.ceil(rect.width);
10359
+ const height = Math.ceil(rect.height);
10360
+ const copie2 = el.cloneNode(true);
10361
+ for (const img of copie2.querySelectorAll("img")) img.setAttribute("src", await enData(new URL(img.getAttribute("src"), d.baseURI).href));
10362
+ const polices = await policesIncorporees(d);
10363
+ const xhtml = new W.XMLSerializer().serializeToString(copie2);
10364
+ const style = `${BASE_CSS}
10365
+ ${polices}`.replace(/]]>/g, "]]&gt;");
10366
+ 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>`;
10367
+ const image = new W.Image();
10368
+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
10369
+ await image.decode();
10370
+ const canvas = d.createElement("canvas");
10371
+ canvas.width = Math.round(width * scale);
10372
+ canvas.height = Math.round(height * scale);
10373
+ canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
10374
+ const blob = await new Promise((ok) => canvas.toBlob(ok, "image/png"));
10375
+ return { bytes: new Uint8Array(await blob.arrayBuffer()), mime: "image/png", width: canvas.width, height: canvas.height };
10376
+ } finally {
10377
+ hote.remove();
10378
+ }
10379
+ }
10380
+
10381
+ // src/studio/targets.js
10382
+ var TARGETS = Object.freeze([
10383
+ Object.freeze({ target: "html", status: "available" }),
10384
+ Object.freeze({ target: "email", status: "planned", phase: 3 }),
10385
+ Object.freeze({ target: "react", status: "planned", phase: 6 })
10386
+ ]);
10387
+
10388
+ // src/studio/document.js
10389
+ var copie = (v) => v === void 0 ? void 0 : structuredClone(v);
10390
+ var StudioDocument = class {
10391
+ #doc;
10392
+ #passe = [];
10393
+ // lots qui défont, du plus ancien au plus récent
10394
+ #futur = [];
10395
+ // lots qui refont
10396
+ #ecoutes = /* @__PURE__ */ new Set();
10397
+ /** @param {object} [json] un document enregistré ; absent : un document vide */
10398
+ constructor(json) {
10399
+ this.#doc = json === void 0 ? createDocument() : assertValid(migrate(structuredClone(json)));
10400
+ }
10401
+ /* ── Lire ────────────────────────────────────────────────────────────────────────────────── */
10402
+ get pages() {
10403
+ return this.#doc.pages.map((p) => ({ ...p, frames: [...p.frames] }));
10404
+ }
10405
+ /** Une copie du nœud : la modifier ne change pas le document (seules les opérations le font). */
10406
+ node(id) {
10407
+ return copie(this.#doc.nodes[id]) ?? null;
10408
+ }
10409
+ /** Premier nœud qui correspond, dans l'ordre des pages puis de l'arbre. `{ name, type }` */
10410
+ find(critere = {}) {
10411
+ return this.findAll(critere)[0] ?? null;
10412
+ }
10413
+ findAll({ name, type } = {}) {
10414
+ const out = [];
10415
+ const visiter = (id) => {
10416
+ const n = this.#doc.nodes[id];
10417
+ if ((name === void 0 || n.name === name) && (type === void 0 || n.type === type)) out.push(copie(n));
10418
+ for (const e of n.children || []) visiter(e);
10419
+ };
10420
+ for (const p of this.#doc.pages) for (const id of p.frames) visiter(id);
10421
+ return out;
10422
+ }
10423
+ /** Le document en forme canonique : deux documents égaux donnent les mêmes octets. */
10424
+ toJSON() {
10425
+ return structuredClone(canonical(this.#doc));
10426
+ }
10427
+ /* ── Vérifier, émettre, rendre (P85) ─────────────────────────────────────────────────────── */
10428
+ /** → `{ issues: [{ rule, severity, node, name, detail? }] }` */
10429
+ check() {
10430
+ return check(this.#doc);
10431
+ }
10432
+ /** → `{ target, files: [{ path, content, bytes }], warnings }`. Phase 1 : `target: "html"` seulement. */
10433
+ emit({ target = "html", ...options } = {}) {
10434
+ if (target !== "html") {
10435
+ const prevue = TARGETS.find((t) => t.target === target);
10436
+ 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);
10437
+ }
10438
+ return emitHtml(this.#doc, options);
10439
+ }
10440
+ /** Un cadre en PNG, dans le navigateur. → `{ bytes, mime, width, height }` ; hors navigateur : `studio_render_unavailable`. */
10441
+ async render({ frame, format = "png", scale = 1, assets, document } = {}) {
10442
+ 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);
10443
+ return renderPng(this.#doc, { frame, scale, assets, document });
10444
+ }
10445
+ /* ── Modifier ────────────────────────────────────────────────────────────────────────────── */
10446
+ /** Applique un lot, en entier ou pas du tout. → `{ applied, created, removed }` */
10447
+ apply(ops, { source = "user" } = {}) {
10448
+ const r = applyOps(this.#doc, ops);
10449
+ this.#doc = r.doc;
10450
+ this.#passe.push(r.inverse);
10451
+ this.#futur = [];
10452
+ this.#emettre(ops, source);
10453
+ return { applied: ops.length, created: r.created, removed: r.removed };
10454
+ }
10455
+ set(id, path, value) {
10456
+ return this.apply([{ op: "set", id, path, value }]);
10457
+ }
10458
+ /** Insère un nœud et rend son id. `parent` : id d'un cadre, ou d'une page. */
10459
+ insert(parent, node4, { index } = {}) {
10460
+ return this.apply([{ op: "insert", parent, node: node4, index }]).created[0];
10461
+ }
10462
+ move(id, { parent, index } = {}) {
10463
+ return this.apply([{ op: "move", id, parent, index }]);
10464
+ }
10465
+ remove(id) {
10466
+ return this.apply([{ op: "remove", id }]);
10467
+ }
10468
+ undo() {
10469
+ return this.#deplacer(this.#passe, this.#futur, "undo");
10470
+ }
10471
+ redo() {
10472
+ return this.#deplacer(this.#futur, this.#passe, "redo");
10473
+ }
10474
+ history() {
10475
+ return { undo: this.#passe.length, redo: this.#futur.length };
10476
+ }
10477
+ /** Écoute les changements ; rend la fonction qui arrête l'écoute. `e = { ops, source }` */
10478
+ on(evenement, fn) {
10479
+ if (evenement !== "change") throw new StudioError("studio_event_unknown", `\xC9v\xE9nement inconnu : ${evenement}`);
10480
+ this.#ecoutes.add(fn);
10481
+ return () => this.#ecoutes.delete(fn);
10482
+ }
10483
+ #deplacer(depuis, vers, source) {
10484
+ const lot = depuis.pop();
10485
+ if (!lot) return false;
10486
+ const r = applyOps(this.#doc, lot, { internal: true });
10487
+ this.#doc = r.doc;
10488
+ vers.push(r.inverse);
10489
+ this.#emettre(lot, source);
10490
+ return true;
10491
+ }
10492
+ #emettre(ops, source) {
10493
+ for (const fn of this.#ecoutes) {
10494
+ try {
10495
+ fn({ ops: copie(ops), source });
10496
+ } catch {
10497
+ }
10498
+ }
10499
+ }
10500
+ };
10501
+
10502
+ // src/resources/design.js
10503
+ var base = "/api/design";
10504
+ var projectPath = (id) => `${base}/projects/${encodeURIComponent(id)}`;
10505
+ var byType = (path, type) => type === void 0 ? path : `${path}?type=${encodeURIComponent(type)}`;
10506
+ var StudioProject = class _StudioProject {
10507
+ #client;
10508
+ constructor(client, data) {
10509
+ this.#client = client;
10510
+ Object.assign(this, data);
10511
+ }
10512
+ async open() {
10513
+ const path = projectPath(this.id);
10514
+ const { document, version } = await this.#client.get(`${path}/document`);
10515
+ const doc = new StudioDocument(document);
10516
+ let current = version;
10517
+ let pending = Promise.resolve();
10518
+ doc.save = ({ version: name } = {}) => {
10519
+ const document2 = doc.toJSON();
10520
+ const request = pending.then(async () => {
10521
+ const result = await this.#client.post(`${path}/document`, { document: document2, baseVersion: current, name });
10522
+ current = result.version;
10523
+ this.version = { id: current, name: name ?? null };
10524
+ this.bytes = result.bytes;
10525
+ return { version: current, bytes: result.bytes };
10526
+ });
10527
+ pending = request.catch(() => {
10528
+ });
10529
+ return request;
10530
+ };
10531
+ return doc;
10532
+ }
10533
+ async update(data) {
10534
+ const { project } = await this.#client.post(projectPath(this.id), data);
10535
+ Object.assign(this, project);
10536
+ return this;
10537
+ }
10538
+ async duplicate(data) {
10539
+ const { project } = await this.#client.post(`${projectPath(this.id)}/duplicate`, data);
10540
+ return new _StudioProject(this.#client, project);
10541
+ }
10542
+ async versions() {
10543
+ return (await this.#client.get(`${projectPath(this.id)}/versions`)).versions;
10544
+ }
10545
+ async restore(version) {
10546
+ const { project } = await this.#client.post(`${projectPath(this.id)}/restore`, { version });
10547
+ Object.assign(this, project);
10548
+ return this;
10549
+ }
10550
+ async render({ frame, width, height } = {}) {
10551
+ return this.#client.post(`${projectPath(this.id)}/render`, { frame, width, height }, { timeout: 0 });
10552
+ }
10553
+ };
10554
+ var DesignResource = class {
10555
+ constructor(client) {
10556
+ const wrap = (data) => new StudioProject(client, data);
10557
+ this.templates = {
10558
+ list: async ({ type } = {}) => (await client.get(byType(`${base}/templates`, type))).templates,
10559
+ get: async (id) => (await client.get(`${base}/templates/${encodeURIComponent(id)}`)).template
10560
+ };
10561
+ this.projects = {
10562
+ create: async (data) => wrap((await client.post(`${base}/projects`, data)).project),
10563
+ list: async ({ type } = {}) => (await client.get(byType(`${base}/projects`, type))).projects.map(wrap),
10564
+ get: async (id) => wrap((await client.get(projectPath(id))).project),
10565
+ remove: async (id) => client.delete(projectPath(id))
10566
+ };
10567
+ }
10568
+ /** Un document vide, ou rouvert depuis son JSON (validé ; invalide → `studio_document_invalid`). */
10569
+ document(json) {
10570
+ return new StudioDocument(json);
10571
+ }
10572
+ /** Les cibles d'émission et leur état : `[{ target, status: "available" | "planned", phase? }]` */
10573
+ targets() {
10574
+ return TARGETS.map((t) => ({ ...t }));
10575
+ }
10576
+ };
10577
+
9407
10578
  // src/index.js
9408
10579
  var DEFAULT_BASE_URL = typeof process !== "undefined" && process?.env?.IAGENIFY_API_URL || "https://api.iagenify.com";
9409
10580
  var IaGenify = class {
@@ -9492,6 +10663,7 @@ var IaGenify = class {
9492
10663
  this.mail = new MailResource(this._client);
9493
10664
  this.hosts = new HostsResource(this._client);
9494
10665
  this.compute = new ComputeResource(this._client);
10666
+ this.design = new DesignResource(this._client);
9495
10667
  }
9496
10668
  async getUser() {
9497
10669
  const res = await this._client.get("/api/auth/me");