iagenify 0.4.1 → 0.4.2
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.cjs +1067 -29
- package/dist/index.js +1067 -29
- package/dist/studio.js +907 -0
- package/package.json +7 -2
package/dist/index.cjs
CHANGED
|
@@ -580,11 +580,15 @@ function createHttpClient({ baseUrl, sessionManager, appName = "", timeout = DEF
|
|
|
580
580
|
async function request(method, path, body, opts = {}) {
|
|
581
581
|
const url = `${baseUrl}${path}`;
|
|
582
582
|
const isFormData = typeof FormData !== "undefined" && body instanceof FormData;
|
|
583
|
+
const isBinary = body instanceof Uint8Array;
|
|
583
584
|
const headers = {
|
|
584
585
|
"X-IaGenify-Version": SDK_VERSION,
|
|
585
|
-
...appName ? { "X-IaGenify-App-Name": appName } : {}
|
|
586
|
+
...appName ? { "X-IaGenify-App-Name": appName } : {},
|
|
587
|
+
...opts.headers || {}
|
|
586
588
|
};
|
|
587
|
-
if (
|
|
589
|
+
if (isBinary) {
|
|
590
|
+
headers["Content-Type"] = "application/octet-stream";
|
|
591
|
+
} else if (!isFormData) {
|
|
588
592
|
headers["Content-Type"] = "application/json";
|
|
589
593
|
}
|
|
590
594
|
if (opts.skipAuth !== true) {
|
|
@@ -604,7 +608,7 @@ function createHttpClient({ baseUrl, sessionManager, appName = "", timeout = DEF
|
|
|
604
608
|
const res = await doFetch(url, {
|
|
605
609
|
method,
|
|
606
610
|
headers,
|
|
607
|
-
body: body !== void 0 ? isFormData ? body : JSON.stringify(body) : void 0
|
|
611
|
+
body: body !== void 0 ? isFormData || isBinary ? body : JSON.stringify(body) : void 0
|
|
608
612
|
}, { timeout: opts.timeout ?? timeout, signal: opts.signal });
|
|
609
613
|
const text2 = await res.text();
|
|
610
614
|
let data;
|
|
@@ -1719,10 +1723,10 @@ function cloudUsageLine(storage, usage) {
|
|
|
1719
1723
|
const u = usage?.[storage?.service];
|
|
1720
1724
|
if (!u) return "";
|
|
1721
1725
|
const mine = storage.limits?.usedBytes || 0;
|
|
1722
|
-
const
|
|
1723
|
-
const plafond =
|
|
1726
|
+
const base2 = (u.storages || []).find((b) => String(b.id) === String(storage.id));
|
|
1727
|
+
const plafond = base2 ? base2.quotaBytes : u.perBaseBytes;
|
|
1724
1728
|
const plan = `(${PLAN_NAMES[usage.pack] || usage.pack} plan)`;
|
|
1725
|
-
const plein =
|
|
1729
|
+
const plein = base2?.overQuota || !base2 && u.overQuota;
|
|
1726
1730
|
if (plafond == null) {
|
|
1727
1731
|
return `${formatBytes(mine)} used, ${SERVICE_NAMES[storage.service]} space ${formatBytes(u.usedBytes)} of ${formatBytes(u.quotaBytes)} ${plan}${u.overQuota ? " \u2014 FULL: writes are refused" : ""}`;
|
|
1728
1732
|
}
|
|
@@ -4896,8 +4900,8 @@ ${(res.slowest || []).map((x) => `${Math.round(x.duration)} ms ${short(x.url, 12
|
|
|
4896
4900
|
if (!result?.ok) fail5(result?.message || `Conversion ${from} \u2192 ${target} failed.`);
|
|
4897
4901
|
const data = result.content !== void 0 ? String(result.content) : Buffer.from(result.base64 || "", "base64");
|
|
4898
4902
|
const ext = EXT_FOR[target] || target;
|
|
4899
|
-
const
|
|
4900
|
-
const destination = filled2(save) ? String(save) : filled2(path) ? `${
|
|
4903
|
+
const base2 = sourceName.replace(/\.[^.]+$/, "");
|
|
4904
|
+
const destination = filled2(save) ? String(save) : filled2(path) ? `${base2}.${ext}` : `Agent/${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}/${base2}.${ext}`;
|
|
4901
4905
|
const written = await files.write(destination, data);
|
|
4902
4906
|
return {
|
|
4903
4907
|
output: `Converted ${sourceName} (${from} \u2192 ${target}) to ${written.path} \u2014 ${Math.round(written.size / 1024)} KB, ${result.creditsUsed ?? 1} credit.`,
|
|
@@ -5317,8 +5321,8 @@ function storageIndex(storages = []) {
|
|
|
5317
5321
|
const byProvider = /* @__PURE__ */ new Map();
|
|
5318
5322
|
for (const s of storages) {
|
|
5319
5323
|
if (!s) continue;
|
|
5320
|
-
const
|
|
5321
|
-
if (
|
|
5324
|
+
const slug2 = storageSlug(s.label || s.name);
|
|
5325
|
+
if (slug2) index.set(slug2, s);
|
|
5322
5326
|
if (s.provider) byProvider.set(s.provider, [...byProvider.get(s.provider) || [], s]);
|
|
5323
5327
|
}
|
|
5324
5328
|
for (const [provider, list] of byProvider) if (list.length === 1 && !index.has(provider)) index.set(provider, list[0]);
|
|
@@ -5486,10 +5490,10 @@ var LocalLibrary = class {
|
|
|
5486
5490
|
throw fail7(409, "storage_not_on_this_machine", `\xAB ${this.storage.label} \xBB belongs to another computer: its ${this.kind} stay there.`);
|
|
5487
5491
|
}
|
|
5488
5492
|
const { fs, path, os } = await node3();
|
|
5489
|
-
const
|
|
5490
|
-
const dir = path.join(
|
|
5493
|
+
const base2 = this.root || path.join(os.homedir(), ".iagenify");
|
|
5494
|
+
const dir = path.join(base2, this.spec.folder);
|
|
5491
5495
|
await fs.mkdir(dir, { recursive: true, mode: 448 });
|
|
5492
|
-
return { fs, path, base, dir };
|
|
5496
|
+
return { fs, path, base: base2, dir };
|
|
5493
5497
|
}
|
|
5494
5498
|
_file(path, dir, name) {
|
|
5495
5499
|
return this.kind === "skills" ? path.join(dir, name, "SKILL.md") : path.join(dir, `${name}.md`);
|
|
@@ -5502,9 +5506,9 @@ var LocalLibrary = class {
|
|
|
5502
5506
|
/** Un élément lu sur disque : { name, description, …, content, builtIn: false }. */
|
|
5503
5507
|
_fromFile(name, text2, extra = {}) {
|
|
5504
5508
|
const { data, body } = parseFrontmatter(text2);
|
|
5505
|
-
const
|
|
5506
|
-
if (this.kind === "subagents") Object.assign(
|
|
5507
|
-
return { ...
|
|
5509
|
+
const base2 = { name, description: String(data.description || "").trim(), builtIn: false };
|
|
5510
|
+
if (this.kind === "subagents") Object.assign(base2, { tools: normalizeTools(data.tools), model: normalizeModel(data.model) });
|
|
5511
|
+
return { ...base2, ...extra, content: body };
|
|
5508
5512
|
}
|
|
5509
5513
|
_builtIn(name) {
|
|
5510
5514
|
const item = this.spec.builtIns[name];
|
|
@@ -5584,14 +5588,14 @@ var LocalLibrary = class {
|
|
|
5584
5588
|
async remove(name) {
|
|
5585
5589
|
this._checkName(name);
|
|
5586
5590
|
if (this.spec.builtIns[name]) throw fail7(400, "builtin_item", `"${name}" is built in and cannot be removed.`);
|
|
5587
|
-
const { fs, path, base, dir } = await this._ready();
|
|
5591
|
+
const { fs, path, base: base2, dir } = await this._ready();
|
|
5588
5592
|
const source = this.kind === "skills" ? path.join(dir, name) : this._file(path, dir, name);
|
|
5589
5593
|
try {
|
|
5590
5594
|
await fs.access(source);
|
|
5591
5595
|
} catch {
|
|
5592
5596
|
throw fail7(404, `${this.spec.label}_not_found`, `No ${this.spec.label} named "${name}".`);
|
|
5593
5597
|
}
|
|
5594
|
-
const target = path.join(
|
|
5598
|
+
const target = path.join(base2, ".trash", (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-"), this.spec.folder, path.basename(source));
|
|
5595
5599
|
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
5596
5600
|
await fs.rename(source, target);
|
|
5597
5601
|
return { ok: true };
|
|
@@ -8897,10 +8901,16 @@ var Host = class {
|
|
|
8897
8901
|
if (files !== void 0) throw new IaGenifyError(400, "invalid_deploy", "An edge host deploys code, not a folder.");
|
|
8898
8902
|
if (typeof code !== "string" || !code.trim()) throw new IaGenifyError(400, "nothing_to_deploy", "An edge host needs a code module.");
|
|
8899
8903
|
}
|
|
8900
|
-
const
|
|
8901
|
-
if (code !== void 0)
|
|
8902
|
-
if (files
|
|
8903
|
-
|
|
8904
|
+
const withServer = this.runtime === "node" && server !== void 0;
|
|
8905
|
+
if (files !== void 0 && code !== void 0) throw new IaGenifyError(400, "invalid_deploy", "Pass files or code, not both.");
|
|
8906
|
+
if (files === void 0) {
|
|
8907
|
+
return (await this.client.post(`/api/hosting/${this.id}/deploy`, { code, ...withServer ? { server } : {} })).deploy;
|
|
8908
|
+
}
|
|
8909
|
+
const entries = await collectFiles(files);
|
|
8910
|
+
const total = entries.reduce((sum, file) => sum + file.size, 0);
|
|
8911
|
+
if (total > DIRECT_UPLOAD_ABOVE) return deployDirect(this.client, this.id, entries, withServer ? server : void 0);
|
|
8912
|
+
const body = { files: await Promise.all(entries.map(async (file) => ({ path: file.path, content: toBase64(await file.load()) }))) };
|
|
8913
|
+
if (withServer) body.server = server;
|
|
8904
8914
|
return (await this.client.post(`/api/hosting/${this.id}/deploy`, body)).deploy;
|
|
8905
8915
|
}
|
|
8906
8916
|
async update({ label } = {}) {
|
|
@@ -8921,14 +8931,18 @@ var Host = class {
|
|
|
8921
8931
|
return this.client.delete(`/api/hosting/${this.id}`);
|
|
8922
8932
|
}
|
|
8923
8933
|
};
|
|
8924
|
-
|
|
8934
|
+
var DIRECT_UPLOAD_ABOVE = 8 * 1024 * 1024;
|
|
8935
|
+
var PACKS_IN_FLIGHT = 3;
|
|
8936
|
+
var PACK_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
8937
|
+
var FINISH_TIMEOUT_MS = 10 * 60 * 1e3;
|
|
8938
|
+
async function collectFiles(input) {
|
|
8925
8939
|
if (Array.isArray(input)) {
|
|
8926
8940
|
const files = input.map((file) => {
|
|
8927
8941
|
const path2 = String(file?.path ?? "").replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "");
|
|
8928
8942
|
if (!path2) throw new IaGenifyError(400, "nothing_to_deploy", "Every file needs a path.");
|
|
8929
8943
|
if (NEVER_DEPLOY2.some((rule) => rule.test(path2))) return null;
|
|
8930
8944
|
const bytes = typeof file?.content === "string" ? new TextEncoder().encode(file.content) : new Uint8Array(file?.content ?? []);
|
|
8931
|
-
return { path: path2,
|
|
8945
|
+
return { path: path2, size: bytes.length, load: async () => bytes };
|
|
8932
8946
|
}).filter(Boolean);
|
|
8933
8947
|
if (!files.length) throw new IaGenifyError(400, "nothing_to_deploy", "No deployable files were provided.");
|
|
8934
8948
|
return files;
|
|
@@ -8950,7 +8964,10 @@ async function readFiles(input) {
|
|
|
8950
8964
|
const relative = path.relative(root, full).split(path.sep).join("/");
|
|
8951
8965
|
if (NEVER_DEPLOY2.some((rule) => rule.test(relative))) continue;
|
|
8952
8966
|
if (entry.isDirectory()) await visit(full);
|
|
8953
|
-
else if (entry.isFile())
|
|
8967
|
+
else if (entry.isFile()) {
|
|
8968
|
+
const { size } = await fs.stat(full);
|
|
8969
|
+
result.push({ path: relative, size, load: async () => new Uint8Array(await fs.readFile(full)) });
|
|
8970
|
+
}
|
|
8954
8971
|
}
|
|
8955
8972
|
};
|
|
8956
8973
|
try {
|
|
@@ -8962,6 +8979,80 @@ async function readFiles(input) {
|
|
|
8962
8979
|
if (!result.length) throw new IaGenifyError(400, "nothing_to_deploy", `The folder "${input}" contains no deployable files.`);
|
|
8963
8980
|
return result;
|
|
8964
8981
|
}
|
|
8982
|
+
async function hashBytes(bytes) {
|
|
8983
|
+
const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", bytes));
|
|
8984
|
+
let hex = "";
|
|
8985
|
+
for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
|
|
8986
|
+
return hex.slice(0, 32);
|
|
8987
|
+
}
|
|
8988
|
+
function planPacks(hashes, sizeOf, { maxBytes, maxFiles }) {
|
|
8989
|
+
const packs = [];
|
|
8990
|
+
let current = [];
|
|
8991
|
+
let bytes = 0;
|
|
8992
|
+
for (const hash of hashes) {
|
|
8993
|
+
const size = sizeOf(hash);
|
|
8994
|
+
if (current.length && (bytes + size > maxBytes || current.length >= maxFiles)) {
|
|
8995
|
+
packs.push(current);
|
|
8996
|
+
current = [];
|
|
8997
|
+
bytes = 0;
|
|
8998
|
+
}
|
|
8999
|
+
current.push(hash);
|
|
9000
|
+
bytes += size;
|
|
9001
|
+
}
|
|
9002
|
+
if (current.length) packs.push(current);
|
|
9003
|
+
return packs;
|
|
9004
|
+
}
|
|
9005
|
+
async function deployDirect(client, hostId, entries, server) {
|
|
9006
|
+
const base2 = `/api/hosting/${hostId}/uploads`;
|
|
9007
|
+
const byHash = /* @__PURE__ */ new Map();
|
|
9008
|
+
const manifest = [];
|
|
9009
|
+
for (const entry of entries) {
|
|
9010
|
+
const hash = await hashBytes(await entry.load());
|
|
9011
|
+
manifest.push({ path: entry.path, size: entry.size, hash });
|
|
9012
|
+
if (!byHash.has(hash)) byHash.set(hash, entry);
|
|
9013
|
+
}
|
|
9014
|
+
const { upload } = await client.post(base2, { files: manifest, ...server !== void 0 ? { server } : {} });
|
|
9015
|
+
const send = async (missing2) => {
|
|
9016
|
+
const packs = planPacks(
|
|
9017
|
+
missing2.filter((hash) => byHash.has(hash)),
|
|
9018
|
+
(hash) => byHash.get(hash).size,
|
|
9019
|
+
{ maxBytes: upload.packBytes, maxFiles: upload.packFiles }
|
|
9020
|
+
);
|
|
9021
|
+
let next = 0;
|
|
9022
|
+
const worker = async () => {
|
|
9023
|
+
while (next < packs.length) {
|
|
9024
|
+
const pack = packs[next++];
|
|
9025
|
+
const parts = await Promise.all(pack.map((hash) => byHash.get(hash).load()));
|
|
9026
|
+
const body = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
|
|
9027
|
+
let offset = 0;
|
|
9028
|
+
for (const part of parts) {
|
|
9029
|
+
body.set(part, offset);
|
|
9030
|
+
offset += part.length;
|
|
9031
|
+
}
|
|
9032
|
+
const header = pack.map((hash) => `${hash}:${byHash.get(hash).size}`).join(",");
|
|
9033
|
+
for (let attempt = 1; ; attempt++) {
|
|
9034
|
+
try {
|
|
9035
|
+
await client.put(`${base2}/${upload.id}/parts`, body, { headers: { "X-IaGenify-Parts": header }, timeout: PACK_TIMEOUT_MS });
|
|
9036
|
+
break;
|
|
9037
|
+
} catch (error) {
|
|
9038
|
+
const transient = !error?.status || error.status >= 500 || error.status === 429;
|
|
9039
|
+
if (!transient || attempt >= 3) throw error;
|
|
9040
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3 * attempt));
|
|
9041
|
+
}
|
|
9042
|
+
}
|
|
9043
|
+
}
|
|
9044
|
+
};
|
|
9045
|
+
await Promise.all(Array.from({ length: Math.min(PACKS_IN_FLIGHT, packs.length) }, worker));
|
|
9046
|
+
};
|
|
9047
|
+
await send(upload.missing || []);
|
|
9048
|
+
try {
|
|
9049
|
+
return (await client.post(`${base2}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
|
|
9050
|
+
} catch (error) {
|
|
9051
|
+
if (error?.code !== "upload_incomplete" || !Array.isArray(error.details?.missing)) throw error;
|
|
9052
|
+
await send(error.details.missing);
|
|
9053
|
+
return (await client.post(`${base2}/${upload.id}/finish`, {}, { timeout: FINISH_TIMEOUT_MS })).deploy;
|
|
9054
|
+
}
|
|
9055
|
+
}
|
|
8965
9056
|
function toBase64(bytes) {
|
|
8966
9057
|
if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
|
|
8967
9058
|
let binary = "";
|
|
@@ -8973,10 +9064,10 @@ var HostsResource = class {
|
|
|
8973
9064
|
this.client = client;
|
|
8974
9065
|
}
|
|
8975
9066
|
/** `runtime` is the public contract. `kind` remains accepted for one upgrade cycle. */
|
|
8976
|
-
async create({ runtime, framework, label, slug, kind } = {}) {
|
|
9067
|
+
async create({ runtime, framework, label, slug: slug2, kind } = {}) {
|
|
8977
9068
|
const rule = assertRuntime(runtime || LEGACY_RUNTIME[kind], framework);
|
|
8978
9069
|
const resolvedRuntime = runtime || LEGACY_RUNTIME[kind];
|
|
8979
|
-
const res = await this.client.post("/api/hosting", { runtime: resolvedRuntime, framework, label, slug });
|
|
9070
|
+
const res = await this.client.post("/api/hosting", { runtime: resolvedRuntime, framework, label, slug: slug2 });
|
|
8980
9071
|
return new Host(this.client, res.host, { framework });
|
|
8981
9072
|
}
|
|
8982
9073
|
async list() {
|
|
@@ -9370,8 +9461,8 @@ var Contacts = class {
|
|
|
9370
9461
|
/** `avatar` est rendu absolu ici : l'API rend un chemin, elle ignore sous quel nom on l'atteint. */
|
|
9371
9462
|
_absolu(contact) {
|
|
9372
9463
|
if (!contact) return contact;
|
|
9373
|
-
const
|
|
9374
|
-
return contact.avatar?.startsWith("/") &&
|
|
9464
|
+
const base2 = typeof this.client?.baseUrl === "string" ? this.client.baseUrl : "";
|
|
9465
|
+
return contact.avatar?.startsWith("/") && base2 ? { ...contact, avatar: `${base2}${contact.avatar}` } : contact;
|
|
9375
9466
|
}
|
|
9376
9467
|
async list() {
|
|
9377
9468
|
const res = await this.client.get("/api/mail/contacts");
|
|
@@ -9462,6 +9553,952 @@ var MailResource = class {
|
|
|
9462
9553
|
}
|
|
9463
9554
|
};
|
|
9464
9555
|
|
|
9556
|
+
// src/studio/errors.js
|
|
9557
|
+
var StudioError = class extends Error {
|
|
9558
|
+
constructor(code, message, details = void 0, status = 400) {
|
|
9559
|
+
super(message);
|
|
9560
|
+
this.name = "StudioError";
|
|
9561
|
+
this.status = status;
|
|
9562
|
+
this.code = code;
|
|
9563
|
+
if (details !== void 0) this.details = details;
|
|
9564
|
+
}
|
|
9565
|
+
};
|
|
9566
|
+
|
|
9567
|
+
// src/studio/format.js
|
|
9568
|
+
var FORMAT = "iagenify.design";
|
|
9569
|
+
var FORMAT_VERSION = 1;
|
|
9570
|
+
var NODE_TYPES = ["frame", "text", "image", "shape"];
|
|
9571
|
+
var CONTENEURS = /* @__PURE__ */ new Set(["frame"]);
|
|
9572
|
+
var TAGS = {
|
|
9573
|
+
frame: ["div", "section", "header", "footer", "nav", "main", "article", "aside", "figure", "ul", "li", "a", "button"],
|
|
9574
|
+
text: ["p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "a", "button", "li", "small", "strong", "em", "label"],
|
|
9575
|
+
image: ["img"],
|
|
9576
|
+
shape: ["div"]
|
|
9577
|
+
};
|
|
9578
|
+
var DEFAULT_TAG = { frame: "div", text: "p", image: "img", shape: "div" };
|
|
9579
|
+
var CHAMPS_NOEUD = /* @__PURE__ */ new Set(["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"]);
|
|
9580
|
+
var CHAMPS = {
|
|
9581
|
+
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" },
|
|
9582
|
+
size: { w: "dimension", h: "dimension", minW: "longueur", minH: "longueur", maxW: "longueur", maxH: "longueur" },
|
|
9583
|
+
position: { x: "nombre", y: "nombre", absolute: "booleen" },
|
|
9584
|
+
style: { fill: "remplissage", stroke: "trait", radius: "rayon", shadow: "ombres", opacity: "opacite", clip: "booleen" },
|
|
9585
|
+
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"] },
|
|
9586
|
+
image: { src: "source", fit: ["cover", "contain", "fill"] },
|
|
9587
|
+
shape: { kind: ["rect", "ellipse", "line"] }
|
|
9588
|
+
};
|
|
9589
|
+
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;
|
|
9590
|
+
var POLICE = /^[A-Za-z0-9 \-]{1,64}$/;
|
|
9591
|
+
var SOURCE = /^asset:[A-Za-z0-9_\-]{1,64}$/;
|
|
9592
|
+
var fini = (v) => typeof v === "number" && Number.isFinite(v);
|
|
9593
|
+
function isColor(v) {
|
|
9594
|
+
return typeof v === "string" && COULEUR.test(v.trim());
|
|
9595
|
+
}
|
|
9596
|
+
function verifierValeur(regle, v) {
|
|
9597
|
+
if (Array.isArray(regle)) return regle.includes(v) ? null : `valeur_non_permise (${regle.join(", ")})`;
|
|
9598
|
+
switch (regle) {
|
|
9599
|
+
case "booleen":
|
|
9600
|
+
return typeof v === "boolean" ? null : "booleen_attendu";
|
|
9601
|
+
case "nombre":
|
|
9602
|
+
return fini(v) ? null : "nombre_attendu";
|
|
9603
|
+
case "entier":
|
|
9604
|
+
return Number.isInteger(v) && v >= 1 && v <= 24 ? null : "entier_1_24_attendu";
|
|
9605
|
+
case "longueur":
|
|
9606
|
+
return fini(v) && v >= 0 && v <= 1e5 ? null : "longueur_positive_attendue";
|
|
9607
|
+
case "dimension":
|
|
9608
|
+
return v === "hug" || v === "fill" || fini(v) && v >= 0 && v <= 1e5 ? null : "hug_fill_ou_longueur_attendu";
|
|
9609
|
+
case "padding":
|
|
9610
|
+
if (fini(v) && v >= 0) return null;
|
|
9611
|
+
if (Array.isArray(v) && (v.length === 2 || v.length === 4) && v.every((x) => fini(x) && x >= 0)) return null;
|
|
9612
|
+
return "padding_nombre_ou_liste_2_4";
|
|
9613
|
+
case "rayon":
|
|
9614
|
+
if (fini(v) && v >= 0) return null;
|
|
9615
|
+
if (Array.isArray(v) && v.length === 4 && v.every((x) => fini(x) && x >= 0)) return null;
|
|
9616
|
+
return "rayon_nombre_ou_liste_4";
|
|
9617
|
+
case "opacite":
|
|
9618
|
+
return fini(v) && v >= 0 && v <= 1 ? null : "opacite_0_1";
|
|
9619
|
+
case "couleur":
|
|
9620
|
+
return isColor(v) ? null : "couleur_invalide";
|
|
9621
|
+
case "remplissage":
|
|
9622
|
+
if (isColor(v)) return null;
|
|
9623
|
+
if (v && typeof v === "object" && v.type === "linear") {
|
|
9624
|
+
const cles = Object.keys(v).filter((k) => !["type", "angle", "stops"].includes(k));
|
|
9625
|
+
if (cles.length) return `champ_inconnu (${cles[0]})`;
|
|
9626
|
+
if (!fini(v.angle)) return "angle_attendu";
|
|
9627
|
+
if (!Array.isArray(v.stops) || v.stops.length < 2 || v.stops.length > 8) return "2_a_8_arrets";
|
|
9628
|
+
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";
|
|
9629
|
+
return null;
|
|
9630
|
+
}
|
|
9631
|
+
return "couleur_ou_degrade_attendu";
|
|
9632
|
+
case "trait":
|
|
9633
|
+
if (v && typeof v === "object" && isColor(v.color) && fini(v.width) && v.width >= 0 && v.width <= 100 && Object.keys(v).length === 2) return null;
|
|
9634
|
+
return "trait_{color,width}_attendu";
|
|
9635
|
+
case "ombres":
|
|
9636
|
+
if (!Array.isArray(v) || v.length > 4) return "liste_de_4_ombres_max";
|
|
9637
|
+
for (const o of v) {
|
|
9638
|
+
if (!o || typeof o !== "object") return "ombre_invalide";
|
|
9639
|
+
const cles = Object.keys(o).filter((k) => !["x", "y", "blur", "spread", "color", "inset"].includes(k));
|
|
9640
|
+
if (cles.length) return `champ_inconnu (${cles[0]})`;
|
|
9641
|
+
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";
|
|
9642
|
+
}
|
|
9643
|
+
return null;
|
|
9644
|
+
case "texte":
|
|
9645
|
+
return typeof v === "string" && v.length <= 2e4 ? null : "texte_attendu";
|
|
9646
|
+
case "police":
|
|
9647
|
+
return typeof v === "string" && POLICE.test(v) ? null : "nom_de_police_invalide";
|
|
9648
|
+
case "graisse":
|
|
9649
|
+
return Number.isInteger(v) && v >= 100 && v <= 900 && v % 100 === 0 ? null : "graisse_100_a_900";
|
|
9650
|
+
case "interligne":
|
|
9651
|
+
return fini(v) && v > 0 && v <= 10 ? null : "interligne_0_10";
|
|
9652
|
+
case "source":
|
|
9653
|
+
return typeof v === "string" && SOURCE.test(v) ? null : "source_asset:<id>_attendue";
|
|
9654
|
+
default:
|
|
9655
|
+
return "regle_inconnue";
|
|
9656
|
+
}
|
|
9657
|
+
}
|
|
9658
|
+
function verifierGroupe(groupe, objet, chemin, erreurs) {
|
|
9659
|
+
if (objet === void 0) return;
|
|
9660
|
+
if (!objet || typeof objet !== "object" || Array.isArray(objet)) {
|
|
9661
|
+
erreurs.push({ path: chemin, reason: "objet_attendu" });
|
|
9662
|
+
return;
|
|
9663
|
+
}
|
|
9664
|
+
const regles = CHAMPS[groupe];
|
|
9665
|
+
for (const [cle, valeur] of Object.entries(objet)) {
|
|
9666
|
+
if (!(cle in regles)) {
|
|
9667
|
+
erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
|
|
9668
|
+
continue;
|
|
9669
|
+
}
|
|
9670
|
+
if (valeur === null && ["stroke", "shadow"].includes(cle)) continue;
|
|
9671
|
+
const motif = verifierValeur(regles[cle], valeur);
|
|
9672
|
+
if (motif) erreurs.push({ path: `${chemin}.${cle}`, reason: motif });
|
|
9673
|
+
}
|
|
9674
|
+
}
|
|
9675
|
+
function validateNode(node4, chemin = "node") {
|
|
9676
|
+
const erreurs = [];
|
|
9677
|
+
if (!node4 || typeof node4 !== "object" || Array.isArray(node4)) return [{ path: chemin, reason: "objet_attendu" }];
|
|
9678
|
+
for (const cle of Object.keys(node4)) if (!CHAMPS_NOEUD.has(cle)) erreurs.push({ path: `${chemin}.${cle}`, reason: "champ_inconnu" });
|
|
9679
|
+
if (!NODE_TYPES.includes(node4.type)) erreurs.push({ path: `${chemin}.type`, reason: `type_inconnu (${NODE_TYPES.join(", ")})` });
|
|
9680
|
+
if (typeof node4.name !== "string" || !node4.name.trim() || node4.name.length > 120) erreurs.push({ path: `${chemin}.name`, reason: "nom_1_a_120_caracteres" });
|
|
9681
|
+
if (node4.as !== void 0 && !(TAGS[node4.type] || []).includes(node4.as)) erreurs.push({ path: `${chemin}.as`, reason: "balise_non_permise" });
|
|
9682
|
+
if (node4.alt !== void 0 && (typeof node4.alt !== "string" || node4.alt.length > 500)) erreurs.push({ path: `${chemin}.alt`, reason: "texte_500_max" });
|
|
9683
|
+
for (const groupe of ["layout", "size", "position", "style", "text", "image", "shape"]) verifierGroupe(groupe, node4[groupe], `${chemin}.${groupe}`, erreurs);
|
|
9684
|
+
if (node4.type !== "frame" && node4.layout !== void 0) erreurs.push({ path: `${chemin}.layout`, reason: "seul_un_cadre_a_une_mise_en_page" });
|
|
9685
|
+
if (node4.type !== "text" && node4.text !== void 0) erreurs.push({ path: `${chemin}.text`, reason: "seul_un_texte_a_du_texte" });
|
|
9686
|
+
if (node4.type === "text" && typeof node4.text?.content !== "string") erreurs.push({ path: `${chemin}.text.content`, reason: "texte_attendu" });
|
|
9687
|
+
if (node4.type !== "image" && node4.image !== void 0) erreurs.push({ path: `${chemin}.image`, reason: "seule_une_image_a_une_source" });
|
|
9688
|
+
if (node4.type === "image" && typeof node4.image?.src !== "string") erreurs.push({ path: `${chemin}.image.src`, reason: "source_asset:<id>_attendue" });
|
|
9689
|
+
if (node4.type !== "shape" && node4.shape !== void 0) erreurs.push({ path: `${chemin}.shape`, reason: "seule_une_forme_a_un_genre" });
|
|
9690
|
+
if (CONTENEURS.has(node4.type)) {
|
|
9691
|
+
if (!Array.isArray(node4.children)) erreurs.push({ path: `${chemin}.children`, reason: "liste_attendue" });
|
|
9692
|
+
} else if (node4.children !== void 0) erreurs.push({ path: `${chemin}.children`, reason: "ce_type_n_a_pas_d_enfants" });
|
|
9693
|
+
return erreurs;
|
|
9694
|
+
}
|
|
9695
|
+
function isContainer(node4) {
|
|
9696
|
+
return CONTENEURS.has(node4?.type);
|
|
9697
|
+
}
|
|
9698
|
+
function createDocument() {
|
|
9699
|
+
return { format: FORMAT, version: FORMAT_VERSION, meta: { nextId: 1 }, pages: [{ id: "p_1", name: "Page 1", frames: [] }], nodes: {} };
|
|
9700
|
+
}
|
|
9701
|
+
function validate(doc) {
|
|
9702
|
+
const erreurs = [];
|
|
9703
|
+
const err = (path, reason) => erreurs.push({ path, reason });
|
|
9704
|
+
if (!doc || typeof doc !== "object" || Array.isArray(doc)) return { ok: false, errors: [{ path: "", reason: "objet_attendu" }] };
|
|
9705
|
+
for (const cle of Object.keys(doc)) if (!["format", "version", "meta", "pages", "nodes"].includes(cle)) err(cle, "champ_inconnu");
|
|
9706
|
+
if (doc.format !== FORMAT) err("format", `attendu_${FORMAT}`);
|
|
9707
|
+
if (doc.version !== FORMAT_VERSION) err("version", `version_${FORMAT_VERSION}_attendue`);
|
|
9708
|
+
if (!doc.meta || !Number.isInteger(doc.meta.nextId) || doc.meta.nextId < 1 || Object.keys(doc.meta).length !== 1) err("meta", "meta_{nextId}_attendu");
|
|
9709
|
+
if (!doc.nodes || typeof doc.nodes !== "object" || Array.isArray(doc.nodes)) {
|
|
9710
|
+
err("nodes", "objet_attendu");
|
|
9711
|
+
return { ok: false, errors: erreurs };
|
|
9712
|
+
}
|
|
9713
|
+
if (!Array.isArray(doc.pages) || doc.pages.length === 0) {
|
|
9714
|
+
err("pages", "au_moins_une_page");
|
|
9715
|
+
return { ok: false, errors: erreurs };
|
|
9716
|
+
}
|
|
9717
|
+
const parents = /* @__PURE__ */ new Map();
|
|
9718
|
+
const cite = (id, path) => {
|
|
9719
|
+
if (typeof id !== "string" || !Object.hasOwn(doc.nodes, id)) {
|
|
9720
|
+
err(path, "enfant_inexistant");
|
|
9721
|
+
return;
|
|
9722
|
+
}
|
|
9723
|
+
parents.set(id, (parents.get(id) || 0) + 1);
|
|
9724
|
+
};
|
|
9725
|
+
const idsPages = /* @__PURE__ */ new Set();
|
|
9726
|
+
doc.pages.forEach((p, i) => {
|
|
9727
|
+
const c = `pages[${i}]`;
|
|
9728
|
+
if (!p || typeof p !== "object") return err(c, "objet_attendu");
|
|
9729
|
+
for (const cle of Object.keys(p)) if (!["id", "name", "route", "frames"].includes(cle)) err(`${c}.${cle}`, "champ_inconnu");
|
|
9730
|
+
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");
|
|
9731
|
+
idsPages.add(p.id);
|
|
9732
|
+
if (typeof p.name !== "string" || !p.name.trim() || p.name.length > 120) err(`${c}.name`, "nom_1_a_120_caracteres");
|
|
9733
|
+
if (p.route !== void 0 && (typeof p.route !== "string" || !/^\/[a-z0-9\-/[\]]*$/.test(p.route))) err(`${c}.route`, "route_invalide");
|
|
9734
|
+
if (!Array.isArray(p.frames)) return err(`${c}.frames`, "liste_attendue");
|
|
9735
|
+
p.frames.forEach((id, k) => {
|
|
9736
|
+
cite(id, `${c}.frames[${k}]`);
|
|
9737
|
+
if (typeof id === "string" && Object.hasOwn(doc.nodes, id) && doc.nodes[id]?.type !== "frame") {
|
|
9738
|
+
err(`${c}.frames[${k}]`, "une_page_ne_contient_que_des_cadres");
|
|
9739
|
+
}
|
|
9740
|
+
});
|
|
9741
|
+
});
|
|
9742
|
+
const limite = doc.meta?.nextId ?? 1;
|
|
9743
|
+
for (const [id, node4] of Object.entries(doc.nodes)) {
|
|
9744
|
+
const c = `nodes.${id}`;
|
|
9745
|
+
if (!/^n_[0-9a-z]+$/.test(id)) err(c, "id_invalide");
|
|
9746
|
+
else if (parseInt(id.slice(2), 36) >= limite) err(c, "id_au_dela_du_compteur");
|
|
9747
|
+
if (node4?.id !== id) err(`${c}.id`, "id_different_de_la_cle");
|
|
9748
|
+
erreurs.push(...validateNode(node4, c));
|
|
9749
|
+
if (Array.isArray(node4?.children)) node4.children.forEach((enfant, k) => cite(enfant, `${c}.children[${k}]`));
|
|
9750
|
+
}
|
|
9751
|
+
for (const id of Object.keys(doc.nodes)) {
|
|
9752
|
+
const n = parents.get(id) || 0;
|
|
9753
|
+
if (n === 0) err(`nodes.${id}`, "noeud_orphelin");
|
|
9754
|
+
if (n > 1) err(`nodes.${id}`, "noeud_a_plusieurs_parents");
|
|
9755
|
+
}
|
|
9756
|
+
if (erreurs.length) return { ok: false, errors: erreurs };
|
|
9757
|
+
const vus = /* @__PURE__ */ new Set();
|
|
9758
|
+
const pile = doc.pages.flatMap((p) => p.frames);
|
|
9759
|
+
while (pile.length) {
|
|
9760
|
+
const id = pile.pop();
|
|
9761
|
+
vus.add(id);
|
|
9762
|
+
for (const enfant of doc.nodes[id].children || []) pile.push(enfant);
|
|
9763
|
+
}
|
|
9764
|
+
for (const id of Object.keys(doc.nodes)) if (!vus.has(id)) err(`nodes.${id}`, "cycle");
|
|
9765
|
+
return { ok: erreurs.length === 0, errors: erreurs };
|
|
9766
|
+
}
|
|
9767
|
+
function assertValid(doc) {
|
|
9768
|
+
const r = validate(doc);
|
|
9769
|
+
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) });
|
|
9770
|
+
return doc;
|
|
9771
|
+
}
|
|
9772
|
+
var ORDRE_NOEUD = ["id", "type", "name", "as", "alt", "layout", "size", "position", "style", "text", "image", "shape", "children"];
|
|
9773
|
+
var ordonner = (objet, ordre) => {
|
|
9774
|
+
const out = {};
|
|
9775
|
+
for (const k of ordre) if (objet[k] !== void 0) out[k] = objet[k];
|
|
9776
|
+
return out;
|
|
9777
|
+
};
|
|
9778
|
+
function canonical(doc) {
|
|
9779
|
+
const nodes = {};
|
|
9780
|
+
const ids = Object.keys(doc.nodes).sort((a, b) => parseInt(a.slice(2), 36) - parseInt(b.slice(2), 36));
|
|
9781
|
+
for (const id of ids) {
|
|
9782
|
+
const n = ordonner(doc.nodes[id], ORDRE_NOEUD);
|
|
9783
|
+
for (const g of Object.keys(CHAMPS)) if (n[g] && typeof n[g] === "object") n[g] = ordonner(n[g], Object.keys(CHAMPS[g]));
|
|
9784
|
+
nodes[id] = n;
|
|
9785
|
+
}
|
|
9786
|
+
return {
|
|
9787
|
+
format: doc.format,
|
|
9788
|
+
version: doc.version,
|
|
9789
|
+
meta: { nextId: doc.meta.nextId },
|
|
9790
|
+
pages: doc.pages.map((p) => ordonner({ ...p, frames: [...p.frames] }, ["id", "name", "route", "frames"])),
|
|
9791
|
+
nodes
|
|
9792
|
+
};
|
|
9793
|
+
}
|
|
9794
|
+
function migrate(doc) {
|
|
9795
|
+
if (doc && doc.version === FORMAT_VERSION) return doc;
|
|
9796
|
+
throw new StudioError("studio_document_invalid", `Version de document non prise en charge : ${doc?.version}`, { errors: [{ path: "version", reason: `version_${FORMAT_VERSION}_attendue` }] });
|
|
9797
|
+
}
|
|
9798
|
+
|
|
9799
|
+
// src/studio/ops.js
|
|
9800
|
+
var GROUPES = /* @__PURE__ */ new Set(["layout", "size", "position", "style", "text", "image", "shape"]);
|
|
9801
|
+
var SIMPLES = /* @__PURE__ */ new Set(["name", "as", "alt"]);
|
|
9802
|
+
var refus = (index, reason, message) => {
|
|
9803
|
+
throw new StudioError("studio_op_invalid", message || `Op\xE9ration ${index} refus\xE9e : ${reason}`, { index, reason });
|
|
9804
|
+
};
|
|
9805
|
+
function nouvelId(doc) {
|
|
9806
|
+
const id = `n_${doc.meta.nextId.toString(36)}`;
|
|
9807
|
+
doc.meta.nextId += 1;
|
|
9808
|
+
return id;
|
|
9809
|
+
}
|
|
9810
|
+
function emplacement(doc, id) {
|
|
9811
|
+
for (const p of doc.pages) {
|
|
9812
|
+
const i = p.frames.indexOf(id);
|
|
9813
|
+
if (i >= 0) return { parent: p.id, liste: p.frames, index: i };
|
|
9814
|
+
}
|
|
9815
|
+
for (const n of Object.values(doc.nodes)) if (n.children) {
|
|
9816
|
+
const i = n.children.indexOf(id);
|
|
9817
|
+
if (i >= 0) return { parent: n.id, liste: n.children, index: i };
|
|
9818
|
+
}
|
|
9819
|
+
return null;
|
|
9820
|
+
}
|
|
9821
|
+
function listeDuParent(doc, parent, type, index) {
|
|
9822
|
+
const page = doc.pages.find((p) => p.id === parent);
|
|
9823
|
+
if (page) {
|
|
9824
|
+
if (type !== "frame") refus(index, "une_page_ne_contient_que_des_cadres");
|
|
9825
|
+
return page.frames;
|
|
9826
|
+
}
|
|
9827
|
+
const n = doc.nodes[parent];
|
|
9828
|
+
if (!n) refus(index, "parent_introuvable");
|
|
9829
|
+
if (!isContainer(n)) refus(index, "le_parent_n_est_pas_un_cadre");
|
|
9830
|
+
return n.children;
|
|
9831
|
+
}
|
|
9832
|
+
function sousArbre(doc, id, acc = {}) {
|
|
9833
|
+
const n = doc.nodes[id];
|
|
9834
|
+
acc[id] = n;
|
|
9835
|
+
for (const e of n.children || []) sousArbre(doc, e, acc);
|
|
9836
|
+
return acc;
|
|
9837
|
+
}
|
|
9838
|
+
function placer(liste, id, index, iop) {
|
|
9839
|
+
const i = index === void 0 ? liste.length : index;
|
|
9840
|
+
if (!Number.isInteger(i) || i < 0 || i > liste.length) refus(iop, "index_hors_limites");
|
|
9841
|
+
liste.splice(i, 0, id);
|
|
9842
|
+
return i;
|
|
9843
|
+
}
|
|
9844
|
+
function aplatir(doc, brut, iop, acc) {
|
|
9845
|
+
if (!brut || typeof brut !== "object" || Array.isArray(brut)) refus(iop, "noeud_objet_attendu");
|
|
9846
|
+
if ("id" in brut) refus(iop, "un_id_ne_se_choisit_pas");
|
|
9847
|
+
const { children, ...reste } = brut;
|
|
9848
|
+
const id = nouvelId(doc);
|
|
9849
|
+
const node4 = { id, ...reste };
|
|
9850
|
+
if (isContainer(node4)) {
|
|
9851
|
+
if (children !== void 0 && !Array.isArray(children)) refus(iop, "children_liste_attendue");
|
|
9852
|
+
node4.children = (children || []).map((c) => aplatir(doc, c, iop, acc));
|
|
9853
|
+
} else if (children !== void 0) refus(iop, "ce_type_n_a_pas_d_enfants");
|
|
9854
|
+
const erreurs = validateNode(node4, "node");
|
|
9855
|
+
if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
|
|
9856
|
+
acc[id] = node4;
|
|
9857
|
+
return id;
|
|
9858
|
+
}
|
|
9859
|
+
function estDescendant(doc, ancetre, id) {
|
|
9860
|
+
const n = doc.nodes[ancetre];
|
|
9861
|
+
return (n?.children || []).some((e) => e === id || estDescendant(doc, e, id));
|
|
9862
|
+
}
|
|
9863
|
+
function lire(node4, path) {
|
|
9864
|
+
const [a, b] = path.split(".");
|
|
9865
|
+
if (b === void 0) return node4[a];
|
|
9866
|
+
return node4[a]?.[b];
|
|
9867
|
+
}
|
|
9868
|
+
function appliquerUne(doc, op, iop, inverses, created, removed) {
|
|
9869
|
+
if (!op || typeof op !== "object") refus(iop, "operation_objet_attendue");
|
|
9870
|
+
switch (op.op) {
|
|
9871
|
+
case "set": {
|
|
9872
|
+
const node4 = doc.nodes[op.id];
|
|
9873
|
+
if (!node4) refus(iop, "noeud_introuvable");
|
|
9874
|
+
if (typeof op.path !== "string") refus(iop, "chemin_attendu");
|
|
9875
|
+
const [a, b, ...trop] = op.path.split(".");
|
|
9876
|
+
if (trop.length || !(SIMPLES.has(a) && b === void 0) && !GROUPES.has(a)) refus(iop, "chemin_non_modifiable");
|
|
9877
|
+
const avant = lire(node4, op.path);
|
|
9878
|
+
const copie2 = structuredClone(node4);
|
|
9879
|
+
if (b === void 0) {
|
|
9880
|
+
if (op.value === void 0) delete copie2[a];
|
|
9881
|
+
else copie2[a] = structuredClone(op.value);
|
|
9882
|
+
} else {
|
|
9883
|
+
const groupe = { ...copie2[a] || {} };
|
|
9884
|
+
if (op.value === void 0) delete groupe[b];
|
|
9885
|
+
else groupe[b] = structuredClone(op.value);
|
|
9886
|
+
if (Object.keys(groupe).length) copie2[a] = groupe;
|
|
9887
|
+
else delete copie2[a];
|
|
9888
|
+
}
|
|
9889
|
+
const erreurs = validateNode(copie2, op.id);
|
|
9890
|
+
if (erreurs.length) refus(iop, `${erreurs[0].path} ${erreurs[0].reason}`);
|
|
9891
|
+
doc.nodes[op.id] = copie2;
|
|
9892
|
+
inverses.push({ op: "set", id: op.id, path: op.path, value: avant === void 0 ? void 0 : structuredClone(avant) });
|
|
9893
|
+
return;
|
|
9894
|
+
}
|
|
9895
|
+
case "insert": {
|
|
9896
|
+
const acc = {};
|
|
9897
|
+
const racine = aplatir(doc, op.node, iop, acc);
|
|
9898
|
+
const liste = listeDuParent(doc, op.parent, acc[racine].type, iop);
|
|
9899
|
+
Object.assign(doc.nodes, acc);
|
|
9900
|
+
placer(liste, racine, op.index, iop);
|
|
9901
|
+
created.push(...Object.keys(acc));
|
|
9902
|
+
inverses.push({ op: "remove", id: racine });
|
|
9903
|
+
return;
|
|
9904
|
+
}
|
|
9905
|
+
case "move": {
|
|
9906
|
+
const node4 = doc.nodes[op.id];
|
|
9907
|
+
if (!node4) refus(iop, "noeud_introuvable");
|
|
9908
|
+
if (op.parent === op.id || estDescendant(doc, op.id, op.parent)) refus(iop, "deplacement_dans_son_propre_descendant");
|
|
9909
|
+
const ici = emplacement(doc, op.id);
|
|
9910
|
+
const liste = listeDuParent(doc, op.parent, node4.type, iop);
|
|
9911
|
+
ici.liste.splice(ici.index, 1);
|
|
9912
|
+
placer(liste, op.id, op.index, iop);
|
|
9913
|
+
inverses.push({ op: "move", id: op.id, parent: ici.parent, index: ici.index });
|
|
9914
|
+
return;
|
|
9915
|
+
}
|
|
9916
|
+
case "remove": {
|
|
9917
|
+
if (!doc.nodes[op.id]) refus(iop, "noeud_introuvable");
|
|
9918
|
+
const ici = emplacement(doc, op.id);
|
|
9919
|
+
const arbre = sousArbre(doc, op.id);
|
|
9920
|
+
ici.liste.splice(ici.index, 1);
|
|
9921
|
+
for (const id of Object.keys(arbre)) delete doc.nodes[id];
|
|
9922
|
+
removed.push(...Object.keys(arbre));
|
|
9923
|
+
inverses.push({ op: "restore", parent: ici.parent, index: ici.index, root: op.id, nodes: arbre });
|
|
9924
|
+
return;
|
|
9925
|
+
}
|
|
9926
|
+
case "restore": {
|
|
9927
|
+
if (!op.__interne) refus(iop, "operation_inconnue");
|
|
9928
|
+
const liste = listeDuParent(doc, op.parent, op.nodes[op.root].type, iop);
|
|
9929
|
+
Object.assign(doc.nodes, structuredClone(op.nodes));
|
|
9930
|
+
placer(liste, op.root, op.index, iop);
|
|
9931
|
+
inverses.push({ op: "remove", id: op.root });
|
|
9932
|
+
return;
|
|
9933
|
+
}
|
|
9934
|
+
default:
|
|
9935
|
+
refus(iop, "operation_inconnue");
|
|
9936
|
+
}
|
|
9937
|
+
}
|
|
9938
|
+
function applyOps(doc, ops, { internal = false } = {}) {
|
|
9939
|
+
if (!Array.isArray(ops)) throw new StudioError("studio_op_invalid", "Un lot d'op\xE9rations est une liste.", { index: -1, reason: "liste_attendue" });
|
|
9940
|
+
const copie2 = structuredClone(doc);
|
|
9941
|
+
const inverses = [];
|
|
9942
|
+
const created = [];
|
|
9943
|
+
const removed = [];
|
|
9944
|
+
ops.forEach((op, i) => appliquerUne(copie2, internal && op?.op === "restore" ? { ...op, __interne: true } : op, i, inverses, created, removed));
|
|
9945
|
+
return { doc: copie2, inverse: inverses.reverse(), created, removed };
|
|
9946
|
+
}
|
|
9947
|
+
|
|
9948
|
+
// src/studio/style.js
|
|
9949
|
+
var px = (v) => `${+v.toFixed(3)}px`;
|
|
9950
|
+
var ALIGN = { start: "flex-start", center: "center", end: "flex-end", stretch: "stretch" };
|
|
9951
|
+
var JUSTIFY = { start: "flex-start", center: "center", end: "flex-end", between: "space-between" };
|
|
9952
|
+
function remplissage(f) {
|
|
9953
|
+
if (typeof f === "string") return f;
|
|
9954
|
+
return `linear-gradient(${+f.angle.toFixed(3)}deg, ${f.stops.map((s) => `${s.color} ${+(s.at * 100).toFixed(3)}%`).join(", ")})`;
|
|
9955
|
+
}
|
|
9956
|
+
function padding(p) {
|
|
9957
|
+
if (typeof p === "number") return px(p);
|
|
9958
|
+
return p.map(px).join(" ");
|
|
9959
|
+
}
|
|
9960
|
+
function taille(decl, axe, v, parent) {
|
|
9961
|
+
if (v === void 0) return;
|
|
9962
|
+
const prop = axe === "w" ? "width" : "height";
|
|
9963
|
+
const mode = parent?.layout?.mode;
|
|
9964
|
+
const dir = parent?.layout?.direction || "row";
|
|
9965
|
+
const principal = mode === "flex" && (axe === "w" && dir === "row" || axe === "h" && dir === "column");
|
|
9966
|
+
if (typeof v === "number") {
|
|
9967
|
+
decl.push([prop, px(v)]);
|
|
9968
|
+
if (principal) decl.push(["flex-shrink", "0"]);
|
|
9969
|
+
} else if (v === "fill") {
|
|
9970
|
+
if (principal) decl.push(["flex", "1 1 0"], [axe === "w" ? "min-width" : "min-height", "0"]);
|
|
9971
|
+
else if (mode === "flex") decl.push(["align-self", "stretch"]);
|
|
9972
|
+
else decl.push([prop, "100%"]);
|
|
9973
|
+
} else if (v === "hug") {
|
|
9974
|
+
decl.push([prop, "fit-content"]);
|
|
9975
|
+
}
|
|
9976
|
+
}
|
|
9977
|
+
function nodeCss(node4, parent = null) {
|
|
9978
|
+
const d = [];
|
|
9979
|
+
const pos = node4.position;
|
|
9980
|
+
if (parent?.layout?.mode === "free" || pos?.absolute) {
|
|
9981
|
+
d.push(["position", "absolute"], ["left", px(pos?.x ?? 0)], ["top", px(pos?.y ?? 0)]);
|
|
9982
|
+
}
|
|
9983
|
+
const l = node4.layout;
|
|
9984
|
+
if (node4.type === "frame") {
|
|
9985
|
+
if (l?.mode === "grid") {
|
|
9986
|
+
d.push(["display", "grid"], ["grid-template-columns", `repeat(${l.columns || 2}, minmax(0, 1fr))`]);
|
|
9987
|
+
} else if (l?.mode === "free") {
|
|
9988
|
+
if (!d.some(([p]) => p === "position")) d.push(["position", "relative"]);
|
|
9989
|
+
} else {
|
|
9990
|
+
d.push(["display", "flex"], ["flex-direction", l?.direction || "column"]);
|
|
9991
|
+
if (l?.wrap) d.push(["flex-wrap", "wrap"]);
|
|
9992
|
+
if (l?.align) d.push(["align-items", ALIGN[l.align]]);
|
|
9993
|
+
if (l?.justify) d.push(["justify-content", JUSTIFY[l.justify]]);
|
|
9994
|
+
}
|
|
9995
|
+
if (l?.gap !== void 0 && l.mode !== "free") d.push(["gap", px(l.gap)]);
|
|
9996
|
+
if (l?.padding !== void 0) d.push(["padding", padding(l.padding)]);
|
|
9997
|
+
}
|
|
9998
|
+
taille(d, "w", node4.size?.w, parent);
|
|
9999
|
+
taille(d, "h", node4.size?.h, parent);
|
|
10000
|
+
for (const [k, prop] of [["minW", "min-width"], ["minH", "min-height"], ["maxW", "max-width"], ["maxH", "max-height"]]) {
|
|
10001
|
+
if (node4.size?.[k] !== void 0) d.push([prop, px(node4.size[k])]);
|
|
10002
|
+
}
|
|
10003
|
+
const s = node4.style || {};
|
|
10004
|
+
if (s.fill !== void 0 && node4.type !== "text") d.push(["background", remplissage(s.fill)]);
|
|
10005
|
+
if (s.stroke) d.push(["border", `${px(s.stroke.width)} solid ${s.stroke.color}`]);
|
|
10006
|
+
if (node4.type === "shape" && node4.shape?.kind === "ellipse") d.push(["border-radius", "50%"]);
|
|
10007
|
+
else if (s.radius !== void 0) d.push(["border-radius", typeof s.radius === "number" ? px(s.radius) : s.radius.map(px).join(" ")]);
|
|
10008
|
+
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(", ")]);
|
|
10009
|
+
if (s.opacity !== void 0 && s.opacity !== 1) d.push(["opacity", String(s.opacity)]);
|
|
10010
|
+
if (s.clip) d.push(["overflow", "hidden"]);
|
|
10011
|
+
if (node4.type === "shape" && node4.shape?.kind === "line") d.push(["height", "0"], ["border-top", `${px(s.stroke?.width ?? 1)} solid ${s.stroke?.color ?? "#000000"}`]);
|
|
10012
|
+
const t = node4.text;
|
|
10013
|
+
if (node4.type === "text") {
|
|
10014
|
+
if (t.font) d.push(["font-family", `"${t.font}", sans-serif`]);
|
|
10015
|
+
if (t.size !== void 0) d.push(["font-size", px(t.size)]);
|
|
10016
|
+
if (t.weight !== void 0) d.push(["font-weight", String(t.weight)]);
|
|
10017
|
+
if (t.lineHeight !== void 0) d.push(["line-height", String(t.lineHeight)]);
|
|
10018
|
+
if (t.letterSpacing !== void 0) d.push(["letter-spacing", px(t.letterSpacing)]);
|
|
10019
|
+
if (t.align) d.push(["text-align", t.align]);
|
|
10020
|
+
if (t.transform && t.transform !== "none") d.push(["text-transform", t.transform]);
|
|
10021
|
+
d.push(["color", t.color || "#000000"]);
|
|
10022
|
+
if (s.fill !== void 0) d.push(["background", remplissage(s.fill)]);
|
|
10023
|
+
d.push(["white-space", "pre-wrap"]);
|
|
10024
|
+
}
|
|
10025
|
+
if (node4.type === "image") d.push(["display", "block"], ["object-fit", node4.image.fit || "cover"]);
|
|
10026
|
+
return d;
|
|
10027
|
+
}
|
|
10028
|
+
function tagOf(node4) {
|
|
10029
|
+
return node4.as || DEFAULT_TAG[node4.type];
|
|
10030
|
+
}
|
|
10031
|
+
var BASE_CSS = "*,*::before,*::after{box-sizing:border-box;margin:0}";
|
|
10032
|
+
function parentsOf(doc) {
|
|
10033
|
+
const m = /* @__PURE__ */ new Map();
|
|
10034
|
+
for (const p of doc.pages) for (const id of p.frames) m.set(id, null);
|
|
10035
|
+
for (const n of Object.values(doc.nodes)) for (const e of n.children || []) m.set(e, n);
|
|
10036
|
+
return m;
|
|
10037
|
+
}
|
|
10038
|
+
|
|
10039
|
+
// src/studio/check.js
|
|
10040
|
+
function parseColor(c) {
|
|
10041
|
+
if (!isColor(c)) return null;
|
|
10042
|
+
const s = c.trim().toLowerCase();
|
|
10043
|
+
if (s === "transparent") return [0, 0, 0, 0];
|
|
10044
|
+
if (s.startsWith("#")) {
|
|
10045
|
+
let h = s.slice(1);
|
|
10046
|
+
if (h.length <= 4) h = [...h].map((x) => x + x).join("");
|
|
10047
|
+
const n = (i) => parseInt(h.slice(i, i + 2), 16);
|
|
10048
|
+
return [n(0), n(2), n(4), h.length === 8 ? n(6) / 255 : 1];
|
|
10049
|
+
}
|
|
10050
|
+
const v = s.match(/[\d.]+/g).map(Number);
|
|
10051
|
+
return [v[0], v[1], v[2], v[3] ?? 1];
|
|
10052
|
+
}
|
|
10053
|
+
function luminance([r, g, b]) {
|
|
10054
|
+
const lin = (x) => {
|
|
10055
|
+
x /= 255;
|
|
10056
|
+
return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
|
|
10057
|
+
};
|
|
10058
|
+
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
|
|
10059
|
+
}
|
|
10060
|
+
var melange = (dessus, fond) => [0, 1, 2].map((i) => dessus[i] * dessus[3] + fond[i] * (1 - dessus[3])).concat(1);
|
|
10061
|
+
function contrastRatio(a, b) {
|
|
10062
|
+
const [l1, l2] = [luminance(a), luminance(b)].sort((x, y) => y - x);
|
|
10063
|
+
return (l1 + 0.05) / (l2 + 0.05);
|
|
10064
|
+
}
|
|
10065
|
+
function fondsSous(doc, id, parents) {
|
|
10066
|
+
const couches = [];
|
|
10067
|
+
let n = doc.nodes[id];
|
|
10068
|
+
if (n.type === "text" && n.style?.fill !== void 0) couches.push(n.style.fill);
|
|
10069
|
+
for (let p = parents.get(id); p; p = parents.get(p.id)) if (p.style?.fill !== void 0) couches.push(p.style.fill);
|
|
10070
|
+
let fonds = [[255, 255, 255, 1]];
|
|
10071
|
+
for (const f of couches.reverse()) {
|
|
10072
|
+
const couleurs = typeof f === "string" ? [parseColor(f)] : f.stops.map((s) => parseColor(s.color));
|
|
10073
|
+
fonds = couleurs.flatMap((c) => fonds.map((base2) => melange(c, base2)));
|
|
10074
|
+
}
|
|
10075
|
+
return fonds;
|
|
10076
|
+
}
|
|
10077
|
+
function check(doc) {
|
|
10078
|
+
const issues = [];
|
|
10079
|
+
const parents = parentsOf(doc);
|
|
10080
|
+
for (const n of Object.values(doc.nodes)) {
|
|
10081
|
+
if (n.type === "text") {
|
|
10082
|
+
const couleur = parseColor(n.text.color || "#000000");
|
|
10083
|
+
const grand = (n.text.size ?? 16) >= 24 || (n.text.size ?? 16) >= 18.66 && (n.text.weight ?? 400) >= 700;
|
|
10084
|
+
const requis = grand ? 3 : 4.5;
|
|
10085
|
+
let pire = null;
|
|
10086
|
+
for (const fond of fondsSous(doc, n.id, parents)) {
|
|
10087
|
+
const ratio = contrastRatio(melange(couleur, fond), fond);
|
|
10088
|
+
if (!pire || ratio < pire.ratio) pire = { ratio, fond };
|
|
10089
|
+
}
|
|
10090
|
+
if (pire && pire.ratio < requis) {
|
|
10091
|
+
const hex = (c) => `#${c.slice(0, 3).map((x) => Math.round(x).toString(16).padStart(2, "0")).join("")}`;
|
|
10092
|
+
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) } });
|
|
10093
|
+
}
|
|
10094
|
+
}
|
|
10095
|
+
if (n.type === "frame" && n.children.length === 0 && n.style?.fill === void 0 && !n.style?.stroke) {
|
|
10096
|
+
issues.push({ rule: "empty-frame", severity: "warning", node: n.id, name: n.name });
|
|
10097
|
+
}
|
|
10098
|
+
if (n.type === "image" && !n.alt) issues.push({ rule: "image-alt", severity: "warning", node: n.id, name: n.name });
|
|
10099
|
+
}
|
|
10100
|
+
return { issues };
|
|
10101
|
+
}
|
|
10102
|
+
|
|
10103
|
+
// src/studio/emit/html.js
|
|
10104
|
+
var ECHAPPE = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
|
|
10105
|
+
var escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ECHAPPE[c]);
|
|
10106
|
+
function slug(nom) {
|
|
10107
|
+
const s = String(nom).normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
|
|
10108
|
+
return /^[a-z]/.test(s) ? s : `n-${s || "noeud"}`;
|
|
10109
|
+
}
|
|
10110
|
+
function classNames(doc, page) {
|
|
10111
|
+
const prises = /* @__PURE__ */ new Set();
|
|
10112
|
+
const classes = /* @__PURE__ */ new Map();
|
|
10113
|
+
const unique = (base2) => {
|
|
10114
|
+
let c = base2;
|
|
10115
|
+
let k = 2;
|
|
10116
|
+
while (prises.has(c)) c = `${base2}-${k++}`;
|
|
10117
|
+
prises.add(c);
|
|
10118
|
+
return c;
|
|
10119
|
+
};
|
|
10120
|
+
const visiter = (id, racine) => {
|
|
10121
|
+
const n = doc.nodes[id];
|
|
10122
|
+
const c = racine ? unique(`${racine}__${slug(n.name)}`) : unique(slug(n.name));
|
|
10123
|
+
classes.set(id, c);
|
|
10124
|
+
for (const e of n.children || []) visiter(e, racine || c);
|
|
10125
|
+
};
|
|
10126
|
+
for (const id of page.frames) visiter(id, null);
|
|
10127
|
+
return classes;
|
|
10128
|
+
}
|
|
10129
|
+
function emitHtml(doc, { page: pageId, assets = {}, title, lang = "fr" } = {}) {
|
|
10130
|
+
const page = pageId ? doc.pages.find((p) => p.id === pageId) : doc.pages[0];
|
|
10131
|
+
if (!page) throw new StudioError("studio_page_not_found", `Page introuvable : ${pageId}`, void 0, 404);
|
|
10132
|
+
const parents = parentsOf(doc);
|
|
10133
|
+
const classes = classNames(doc, page);
|
|
10134
|
+
const warnings = [];
|
|
10135
|
+
const regles = [BASE_CSS];
|
|
10136
|
+
const html = (id, profondeur) => {
|
|
10137
|
+
const n = doc.nodes[id];
|
|
10138
|
+
const c = classes.get(id);
|
|
10139
|
+
const decl = nodeCss(n, parents.get(id));
|
|
10140
|
+
if (decl.length) regles.push(`.${c}{${decl.map(([p, v]) => `${p}:${v}`).join(";")}}`);
|
|
10141
|
+
const tag = tagOf(n);
|
|
10142
|
+
const pad2 = " ".repeat(profondeur);
|
|
10143
|
+
if (n.type === "image") {
|
|
10144
|
+
const asset = n.image.src.slice("asset:".length);
|
|
10145
|
+
if (n.alt === void 0) warnings.push(`image-alt : \xAB ${n.name} \xBB n'a pas de texte alternatif`);
|
|
10146
|
+
return `${pad2}<img class="${c}" src="${escapeHtml(assets[asset] || `assets/${asset}`)}" alt="${escapeHtml(n.alt ?? "")}">`;
|
|
10147
|
+
}
|
|
10148
|
+
if (n.type === "text") return `${pad2}<${tag} class="${c}">${escapeHtml(n.text.content)}</${tag}>`;
|
|
10149
|
+
const enfants = (n.children || []).map((e) => html(e, profondeur + 1));
|
|
10150
|
+
return enfants.length ? `${pad2}<${tag} class="${c}">
|
|
10151
|
+
${enfants.join("\n")}
|
|
10152
|
+
${pad2}</${tag}>` : `${pad2}<${tag} class="${c}"></${tag}>`;
|
|
10153
|
+
};
|
|
10154
|
+
const corps = page.frames.map((id) => html(id, 2)).join("\n");
|
|
10155
|
+
const index = `<!doctype html>
|
|
10156
|
+
<html lang="${escapeHtml(lang)}">
|
|
10157
|
+
<head>
|
|
10158
|
+
<meta charset="utf-8">
|
|
10159
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
10160
|
+
<title>${escapeHtml(title || page.name)}</title>
|
|
10161
|
+
<link rel="stylesheet" href="styles.css">
|
|
10162
|
+
</head>
|
|
10163
|
+
<body>
|
|
10164
|
+
${corps}
|
|
10165
|
+
</body>
|
|
10166
|
+
</html>
|
|
10167
|
+
`;
|
|
10168
|
+
const css = `${regles.join("\n")}
|
|
10169
|
+
`;
|
|
10170
|
+
const octets = (s) => new TextEncoder().encode(s).length;
|
|
10171
|
+
return {
|
|
10172
|
+
target: "html",
|
|
10173
|
+
files: [
|
|
10174
|
+
{ path: "index.html", content: index, bytes: octets(index) },
|
|
10175
|
+
{ path: "styles.css", content: css, bytes: octets(css) }
|
|
10176
|
+
],
|
|
10177
|
+
warnings
|
|
10178
|
+
};
|
|
10179
|
+
}
|
|
10180
|
+
|
|
10181
|
+
// src/studio/render.js
|
|
10182
|
+
function renderNode(doc, nodeId, { document: d = globalThis.document, assets = {}, parents = parentsOf(doc) } = {}) {
|
|
10183
|
+
if (!d || typeof d.createElement !== "function") {
|
|
10184
|
+
throw new StudioError("studio_render_unavailable", "Le rendu demande un navigateur (aucun DOM ici).");
|
|
10185
|
+
}
|
|
10186
|
+
const creer = (id) => {
|
|
10187
|
+
const n = doc.nodes[id];
|
|
10188
|
+
const el = d.createElement(tagOf(n));
|
|
10189
|
+
el.setAttribute("data-node-id", id);
|
|
10190
|
+
for (const [prop, valeur] of nodeCss(n, parents.get(id))) el.style.setProperty(prop, valeur);
|
|
10191
|
+
if (n.type === "image") {
|
|
10192
|
+
const asset = n.image.src.slice("asset:".length);
|
|
10193
|
+
el.setAttribute("src", assets[asset] || `assets/${asset}`);
|
|
10194
|
+
el.setAttribute("alt", n.alt ?? "");
|
|
10195
|
+
} else if (n.type === "text") {
|
|
10196
|
+
el.textContent = n.text.content;
|
|
10197
|
+
} else {
|
|
10198
|
+
for (const e of n.children || []) el.appendChild(creer(e));
|
|
10199
|
+
}
|
|
10200
|
+
return el;
|
|
10201
|
+
};
|
|
10202
|
+
if (!doc.nodes[nodeId]) throw new StudioError("studio_node_not_found", `N\u0153ud introuvable : ${nodeId}`, void 0, 404);
|
|
10203
|
+
return creer(nodeId);
|
|
10204
|
+
}
|
|
10205
|
+
|
|
10206
|
+
// src/studio/raster.js
|
|
10207
|
+
var XHTML = "http://www.w3.org/1999/xhtml";
|
|
10208
|
+
async function enData(url) {
|
|
10209
|
+
const reponse = await fetch(url);
|
|
10210
|
+
if (!reponse.ok) throw new StudioError("studio_asset_unavailable", `Ressource illisible pour l'export : ${url} (${reponse.status})`);
|
|
10211
|
+
const blob = await reponse.blob();
|
|
10212
|
+
return await new Promise((ok, ko) => {
|
|
10213
|
+
const f = new FileReader();
|
|
10214
|
+
f.onload = () => ok(f.result);
|
|
10215
|
+
f.onerror = ko;
|
|
10216
|
+
f.readAsDataURL(blob);
|
|
10217
|
+
});
|
|
10218
|
+
}
|
|
10219
|
+
async function policesIncorporees(d) {
|
|
10220
|
+
const regles = [];
|
|
10221
|
+
for (const feuille of d.styleSheets) {
|
|
10222
|
+
let liste;
|
|
10223
|
+
try {
|
|
10224
|
+
liste = feuille.cssRules;
|
|
10225
|
+
} catch {
|
|
10226
|
+
continue;
|
|
10227
|
+
}
|
|
10228
|
+
for (const r of liste) {
|
|
10229
|
+
if (r.type !== 5) continue;
|
|
10230
|
+
let css = r.cssText;
|
|
10231
|
+
const base2 = feuille.href || d.baseURI;
|
|
10232
|
+
for (const [, brut] of css.matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)/g)) {
|
|
10233
|
+
if (brut.startsWith("data:")) continue;
|
|
10234
|
+
css = css.replace(brut, await enData(new URL(brut, base2).href));
|
|
10235
|
+
}
|
|
10236
|
+
regles.push(css);
|
|
10237
|
+
}
|
|
10238
|
+
}
|
|
10239
|
+
return regles.join("\n");
|
|
10240
|
+
}
|
|
10241
|
+
function figerLignes(racine, d) {
|
|
10242
|
+
for (const el of racine.querySelectorAll("[data-node-id]")) {
|
|
10243
|
+
const texte = el.firstChild;
|
|
10244
|
+
if (!texte || texte.nodeType !== 3 || el.childNodes.length !== 1) continue;
|
|
10245
|
+
const t = texte.textContent;
|
|
10246
|
+
const r = d.createRange();
|
|
10247
|
+
let haut = null;
|
|
10248
|
+
let sortie = "";
|
|
10249
|
+
for (let i = 0; i < t.length; i++) {
|
|
10250
|
+
r.setStart(texte, i);
|
|
10251
|
+
r.setEnd(texte, i + 1);
|
|
10252
|
+
const rect = r.getClientRects()[0];
|
|
10253
|
+
if (rect && haut !== null && rect.top > haut + 1 && t[i] !== " " && t[i] !== "\n") sortie = `${sortie.replace(/ +$/, "")}
|
|
10254
|
+
`;
|
|
10255
|
+
if (rect) haut = rect.top;
|
|
10256
|
+
sortie += t[i];
|
|
10257
|
+
}
|
|
10258
|
+
texte.textContent = sortie;
|
|
10259
|
+
el.style.setProperty("white-space", "pre");
|
|
10260
|
+
}
|
|
10261
|
+
}
|
|
10262
|
+
async function renderPng(doc, { frame, scale = 1, assets = {}, document: d = globalThis.document } = {}) {
|
|
10263
|
+
const W = globalThis;
|
|
10264
|
+
if (!d?.body || typeof W.XMLSerializer !== "function" || typeof W.Image !== "function" || typeof W.fetch !== "function") {
|
|
10265
|
+
throw new StudioError("studio_render_unavailable", "L'export d'image se fait dans un navigateur (aucun DOM ici).");
|
|
10266
|
+
}
|
|
10267
|
+
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" });
|
|
10268
|
+
const id = doc.nodes[frame]?.type === "frame" ? frame : Object.values(doc.nodes).find((n) => n.type === "frame" && n.name === frame)?.id;
|
|
10269
|
+
if (!id) throw new StudioError("studio_node_not_found", `Cadre introuvable : ${frame}`, void 0, 404);
|
|
10270
|
+
const hote = d.createElement("div");
|
|
10271
|
+
hote.setAttribute("aria-hidden", "true");
|
|
10272
|
+
hote.setAttribute("data-studio-raster", "");
|
|
10273
|
+
hote.style.cssText = "position:fixed;left:-100000px;top:0;contain:layout style;pointer-events:none";
|
|
10274
|
+
const base2 = d.createElement("style");
|
|
10275
|
+
base2.textContent = "[data-studio-raster] *,[data-studio-raster] *::before,[data-studio-raster] *::after{box-sizing:border-box;margin:0}";
|
|
10276
|
+
hote.append(base2, renderNode(doc, id, { document: d, assets }));
|
|
10277
|
+
d.body.appendChild(hote);
|
|
10278
|
+
try {
|
|
10279
|
+
const el = hote.lastChild;
|
|
10280
|
+
await d.fonts?.ready;
|
|
10281
|
+
await Promise.all([...el.querySelectorAll("img")].map((img) => img.decode().catch(() => {
|
|
10282
|
+
})));
|
|
10283
|
+
figerLignes(el, d);
|
|
10284
|
+
const rect = el.getBoundingClientRect();
|
|
10285
|
+
const width = Math.ceil(rect.width);
|
|
10286
|
+
const height = Math.ceil(rect.height);
|
|
10287
|
+
const copie2 = el.cloneNode(true);
|
|
10288
|
+
for (const img of copie2.querySelectorAll("img")) img.setAttribute("src", await enData(new URL(img.getAttribute("src"), d.baseURI).href));
|
|
10289
|
+
const polices = await policesIncorporees(d);
|
|
10290
|
+
const xhtml = new W.XMLSerializer().serializeToString(copie2);
|
|
10291
|
+
const style = `${BASE_CSS}
|
|
10292
|
+
${polices}`.replace(/]]>/g, "]]>");
|
|
10293
|
+
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>`;
|
|
10294
|
+
const image = new W.Image();
|
|
10295
|
+
image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
|
10296
|
+
await image.decode();
|
|
10297
|
+
const canvas = d.createElement("canvas");
|
|
10298
|
+
canvas.width = Math.round(width * scale);
|
|
10299
|
+
canvas.height = Math.round(height * scale);
|
|
10300
|
+
canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
|
|
10301
|
+
const blob = await new Promise((ok) => canvas.toBlob(ok, "image/png"));
|
|
10302
|
+
return { bytes: new Uint8Array(await blob.arrayBuffer()), mime: "image/png", width: canvas.width, height: canvas.height };
|
|
10303
|
+
} finally {
|
|
10304
|
+
hote.remove();
|
|
10305
|
+
}
|
|
10306
|
+
}
|
|
10307
|
+
|
|
10308
|
+
// src/studio/targets.js
|
|
10309
|
+
var TARGETS = Object.freeze([
|
|
10310
|
+
Object.freeze({ target: "html", status: "available" }),
|
|
10311
|
+
Object.freeze({ target: "email", status: "planned", phase: 3 }),
|
|
10312
|
+
Object.freeze({ target: "react", status: "planned", phase: 6 })
|
|
10313
|
+
]);
|
|
10314
|
+
|
|
10315
|
+
// src/studio/document.js
|
|
10316
|
+
var copie = (v) => v === void 0 ? void 0 : structuredClone(v);
|
|
10317
|
+
var StudioDocument = class {
|
|
10318
|
+
#doc;
|
|
10319
|
+
#passe = [];
|
|
10320
|
+
// lots qui défont, du plus ancien au plus récent
|
|
10321
|
+
#futur = [];
|
|
10322
|
+
// lots qui refont
|
|
10323
|
+
#ecoutes = /* @__PURE__ */ new Set();
|
|
10324
|
+
/** @param {object} [json] un document enregistré ; absent : un document vide */
|
|
10325
|
+
constructor(json) {
|
|
10326
|
+
this.#doc = json === void 0 ? createDocument() : assertValid(migrate(structuredClone(json)));
|
|
10327
|
+
}
|
|
10328
|
+
/* ── Lire ────────────────────────────────────────────────────────────────────────────────── */
|
|
10329
|
+
get pages() {
|
|
10330
|
+
return this.#doc.pages.map((p) => ({ ...p, frames: [...p.frames] }));
|
|
10331
|
+
}
|
|
10332
|
+
/** Une copie du nœud : la modifier ne change pas le document (seules les opérations le font). */
|
|
10333
|
+
node(id) {
|
|
10334
|
+
return copie(this.#doc.nodes[id]) ?? null;
|
|
10335
|
+
}
|
|
10336
|
+
/** Premier nœud qui correspond, dans l'ordre des pages puis de l'arbre. `{ name, type }` */
|
|
10337
|
+
find(critere = {}) {
|
|
10338
|
+
return this.findAll(critere)[0] ?? null;
|
|
10339
|
+
}
|
|
10340
|
+
findAll({ name, type } = {}) {
|
|
10341
|
+
const out = [];
|
|
10342
|
+
const visiter = (id) => {
|
|
10343
|
+
const n = this.#doc.nodes[id];
|
|
10344
|
+
if ((name === void 0 || n.name === name) && (type === void 0 || n.type === type)) out.push(copie(n));
|
|
10345
|
+
for (const e of n.children || []) visiter(e);
|
|
10346
|
+
};
|
|
10347
|
+
for (const p of this.#doc.pages) for (const id of p.frames) visiter(id);
|
|
10348
|
+
return out;
|
|
10349
|
+
}
|
|
10350
|
+
/** Le document en forme canonique : deux documents égaux donnent les mêmes octets. */
|
|
10351
|
+
toJSON() {
|
|
10352
|
+
return structuredClone(canonical(this.#doc));
|
|
10353
|
+
}
|
|
10354
|
+
/* ── Vérifier, émettre, rendre (P85) ─────────────────────────────────────────────────────── */
|
|
10355
|
+
/** → `{ issues: [{ rule, severity, node, name, detail? }] }` */
|
|
10356
|
+
check() {
|
|
10357
|
+
return check(this.#doc);
|
|
10358
|
+
}
|
|
10359
|
+
/** → `{ target, files: [{ path, content, bytes }], warnings }`. Phase 1 : `target: "html"` seulement. */
|
|
10360
|
+
emit({ target = "html", ...options } = {}) {
|
|
10361
|
+
if (target !== "html") {
|
|
10362
|
+
const prevue = TARGETS.find((t) => t.target === target);
|
|
10363
|
+
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);
|
|
10364
|
+
}
|
|
10365
|
+
return emitHtml(this.#doc, options);
|
|
10366
|
+
}
|
|
10367
|
+
/** Un cadre en PNG, dans le navigateur. → `{ bytes, mime, width, height }` ; hors navigateur : `studio_render_unavailable`. */
|
|
10368
|
+
async render({ frame, format = "png", scale = 1, assets, document } = {}) {
|
|
10369
|
+
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);
|
|
10370
|
+
return renderPng(this.#doc, { frame, scale, assets, document });
|
|
10371
|
+
}
|
|
10372
|
+
/* ── Modifier ────────────────────────────────────────────────────────────────────────────── */
|
|
10373
|
+
/** Applique un lot, en entier ou pas du tout. → `{ applied, created, removed }` */
|
|
10374
|
+
apply(ops, { source = "user" } = {}) {
|
|
10375
|
+
const r = applyOps(this.#doc, ops);
|
|
10376
|
+
this.#doc = r.doc;
|
|
10377
|
+
this.#passe.push(r.inverse);
|
|
10378
|
+
this.#futur = [];
|
|
10379
|
+
this.#emettre(ops, source);
|
|
10380
|
+
return { applied: ops.length, created: r.created, removed: r.removed };
|
|
10381
|
+
}
|
|
10382
|
+
set(id, path, value) {
|
|
10383
|
+
return this.apply([{ op: "set", id, path, value }]);
|
|
10384
|
+
}
|
|
10385
|
+
/** Insère un nœud et rend son id. `parent` : id d'un cadre, ou d'une page. */
|
|
10386
|
+
insert(parent, node4, { index } = {}) {
|
|
10387
|
+
return this.apply([{ op: "insert", parent, node: node4, index }]).created[0];
|
|
10388
|
+
}
|
|
10389
|
+
move(id, { parent, index } = {}) {
|
|
10390
|
+
return this.apply([{ op: "move", id, parent, index }]);
|
|
10391
|
+
}
|
|
10392
|
+
remove(id) {
|
|
10393
|
+
return this.apply([{ op: "remove", id }]);
|
|
10394
|
+
}
|
|
10395
|
+
undo() {
|
|
10396
|
+
return this.#deplacer(this.#passe, this.#futur, "undo");
|
|
10397
|
+
}
|
|
10398
|
+
redo() {
|
|
10399
|
+
return this.#deplacer(this.#futur, this.#passe, "redo");
|
|
10400
|
+
}
|
|
10401
|
+
history() {
|
|
10402
|
+
return { undo: this.#passe.length, redo: this.#futur.length };
|
|
10403
|
+
}
|
|
10404
|
+
/** Écoute les changements ; rend la fonction qui arrête l'écoute. `e = { ops, source }` */
|
|
10405
|
+
on(evenement, fn) {
|
|
10406
|
+
if (evenement !== "change") throw new StudioError("studio_event_unknown", `\xC9v\xE9nement inconnu : ${evenement}`);
|
|
10407
|
+
this.#ecoutes.add(fn);
|
|
10408
|
+
return () => this.#ecoutes.delete(fn);
|
|
10409
|
+
}
|
|
10410
|
+
#deplacer(depuis, vers, source) {
|
|
10411
|
+
const lot = depuis.pop();
|
|
10412
|
+
if (!lot) return false;
|
|
10413
|
+
const r = applyOps(this.#doc, lot, { internal: true });
|
|
10414
|
+
this.#doc = r.doc;
|
|
10415
|
+
vers.push(r.inverse);
|
|
10416
|
+
this.#emettre(lot, source);
|
|
10417
|
+
return true;
|
|
10418
|
+
}
|
|
10419
|
+
#emettre(ops, source) {
|
|
10420
|
+
for (const fn of this.#ecoutes) {
|
|
10421
|
+
try {
|
|
10422
|
+
fn({ ops: copie(ops), source });
|
|
10423
|
+
} catch {
|
|
10424
|
+
}
|
|
10425
|
+
}
|
|
10426
|
+
}
|
|
10427
|
+
};
|
|
10428
|
+
|
|
10429
|
+
// src/resources/studio.js
|
|
10430
|
+
var base = "/api/studio";
|
|
10431
|
+
var projectPath = (id) => `${base}/projects/${encodeURIComponent(id)}`;
|
|
10432
|
+
var byType = (path, type) => type === void 0 ? path : `${path}?type=${encodeURIComponent(type)}`;
|
|
10433
|
+
var StudioProject = class _StudioProject {
|
|
10434
|
+
#client;
|
|
10435
|
+
constructor(client, data) {
|
|
10436
|
+
this.#client = client;
|
|
10437
|
+
Object.assign(this, data);
|
|
10438
|
+
}
|
|
10439
|
+
async open() {
|
|
10440
|
+
const path = projectPath(this.id);
|
|
10441
|
+
const { document, version } = await this.#client.get(`${path}/document`);
|
|
10442
|
+
const doc = new StudioDocument(document);
|
|
10443
|
+
let current = version;
|
|
10444
|
+
let pending = Promise.resolve();
|
|
10445
|
+
doc.save = ({ version: name } = {}) => {
|
|
10446
|
+
const document2 = doc.toJSON();
|
|
10447
|
+
const request = pending.then(async () => {
|
|
10448
|
+
const result = await this.#client.post(`${path}/document`, { document: document2, baseVersion: current, name });
|
|
10449
|
+
current = result.version;
|
|
10450
|
+
this.version = { id: current, name: name ?? null };
|
|
10451
|
+
this.bytes = result.bytes;
|
|
10452
|
+
return { version: current, bytes: result.bytes };
|
|
10453
|
+
});
|
|
10454
|
+
pending = request.catch(() => {
|
|
10455
|
+
});
|
|
10456
|
+
return request;
|
|
10457
|
+
};
|
|
10458
|
+
return doc;
|
|
10459
|
+
}
|
|
10460
|
+
async update(data) {
|
|
10461
|
+
const { project } = await this.#client.post(projectPath(this.id), data);
|
|
10462
|
+
Object.assign(this, project);
|
|
10463
|
+
return this;
|
|
10464
|
+
}
|
|
10465
|
+
async duplicate(data) {
|
|
10466
|
+
const { project } = await this.#client.post(`${projectPath(this.id)}/duplicate`, data);
|
|
10467
|
+
return new _StudioProject(this.#client, project);
|
|
10468
|
+
}
|
|
10469
|
+
async versions() {
|
|
10470
|
+
return (await this.#client.get(`${projectPath(this.id)}/versions`)).versions;
|
|
10471
|
+
}
|
|
10472
|
+
async restore(version) {
|
|
10473
|
+
const { project } = await this.#client.post(`${projectPath(this.id)}/restore`, { version });
|
|
10474
|
+
Object.assign(this, project);
|
|
10475
|
+
return this;
|
|
10476
|
+
}
|
|
10477
|
+
};
|
|
10478
|
+
var StudioResource = class {
|
|
10479
|
+
constructor(client) {
|
|
10480
|
+
const wrap = (data) => new StudioProject(client, data);
|
|
10481
|
+
this.templates = {
|
|
10482
|
+
list: async ({ type } = {}) => (await client.get(byType(`${base}/templates`, type))).templates,
|
|
10483
|
+
get: async (id) => (await client.get(`${base}/templates/${encodeURIComponent(id)}`)).template
|
|
10484
|
+
};
|
|
10485
|
+
this.projects = {
|
|
10486
|
+
create: async (data) => wrap((await client.post(`${base}/projects`, data)).project),
|
|
10487
|
+
list: async ({ type } = {}) => (await client.get(byType(`${base}/projects`, type))).projects.map(wrap),
|
|
10488
|
+
get: async (id) => wrap((await client.get(projectPath(id))).project),
|
|
10489
|
+
remove: async (id) => client.delete(projectPath(id))
|
|
10490
|
+
};
|
|
10491
|
+
}
|
|
10492
|
+
/** Un document vide, ou rouvert depuis son JSON (validé ; invalide → `studio_document_invalid`). */
|
|
10493
|
+
document(json) {
|
|
10494
|
+
return new StudioDocument(json);
|
|
10495
|
+
}
|
|
10496
|
+
/** Les cibles d'émission et leur état : `[{ target, status: "available" | "planned", phase? }]` */
|
|
10497
|
+
targets() {
|
|
10498
|
+
return TARGETS.map((t) => ({ ...t }));
|
|
10499
|
+
}
|
|
10500
|
+
};
|
|
10501
|
+
|
|
9465
10502
|
// src/index.js
|
|
9466
10503
|
var DEFAULT_BASE_URL = typeof process !== "undefined" && process?.env?.IAGENIFY_API_URL || "https://api.iagenify.com";
|
|
9467
10504
|
var IaGenify = class {
|
|
@@ -9550,6 +10587,7 @@ var IaGenify = class {
|
|
|
9550
10587
|
this.mail = new MailResource(this._client);
|
|
9551
10588
|
this.hosts = new HostsResource(this._client);
|
|
9552
10589
|
this.compute = new ComputeResource(this._client);
|
|
10590
|
+
this.studio = new StudioResource(this._client);
|
|
9553
10591
|
}
|
|
9554
10592
|
async getUser() {
|
|
9555
10593
|
const res = await this._client.get("/api/auth/me");
|