beplus-mcp 0.44.0 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -2
- package/dist/index.js +3520 -57
- package/dist/index.js.map +1 -1
- package/dist/remote-server.js +3520 -57
- package/dist/remote-server.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -6885,6 +6885,2721 @@ var require_dist = __commonJS({
|
|
|
6885
6885
|
}
|
|
6886
6886
|
});
|
|
6887
6887
|
|
|
6888
|
+
// src/vendor/canvas-core/index.cjs
|
|
6889
|
+
var require_canvas_core = __commonJS({
|
|
6890
|
+
"src/vendor/canvas-core/index.cjs"(exports, module) {
|
|
6891
|
+
"use strict";
|
|
6892
|
+
var __defProp2 = Object.defineProperty;
|
|
6893
|
+
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
6894
|
+
var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
6895
|
+
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
6896
|
+
var __export2 = (target, all) => {
|
|
6897
|
+
for (var name in all)
|
|
6898
|
+
__defProp2(target, name, { get: all[name], enumerable: true });
|
|
6899
|
+
};
|
|
6900
|
+
var __copyProps2 = (to, from, except, desc) => {
|
|
6901
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
6902
|
+
for (let key of __getOwnPropNames2(from))
|
|
6903
|
+
if (!__hasOwnProp2.call(to, key) && key !== except)
|
|
6904
|
+
__defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
|
|
6905
|
+
}
|
|
6906
|
+
return to;
|
|
6907
|
+
};
|
|
6908
|
+
var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
|
|
6909
|
+
var index_exports = {};
|
|
6910
|
+
__export2(index_exports, {
|
|
6911
|
+
BOARD_FIELDS: () => BOARD_FIELDS,
|
|
6912
|
+
BoardStore: () => BoardStore,
|
|
6913
|
+
DEFAULT_MAX_PER_COLUMN: () => DEFAULT_MAX_PER_COLUMN,
|
|
6914
|
+
DEFAULT_PLACEMENT_GAP: () => DEFAULT_PLACEMENT_GAP,
|
|
6915
|
+
DEFAULT_SHAPE_SIZE: () => DEFAULT_SHAPE_SIZE,
|
|
6916
|
+
DEFAULT_TIDY_GAP_X: () => DEFAULT_TIDY_GAP_X,
|
|
6917
|
+
DEFAULT_TIDY_GAP_Y: () => DEFAULT_TIDY_GAP_Y,
|
|
6918
|
+
DEFAULT_TIDY_SWEEPS: () => DEFAULT_TIDY_SWEEPS,
|
|
6919
|
+
Draft: () => Draft,
|
|
6920
|
+
EMPTY_INTERACTION: () => EMPTY_INTERACTION,
|
|
6921
|
+
FORBIDDEN_PATH_SEGMENTS: () => FORBIDDEN_PATH_SEGMENTS,
|
|
6922
|
+
HISTORY_LIMIT: () => HISTORY_LIMIT,
|
|
6923
|
+
HISTORY_MAX_BYTES: () => HISTORY_MAX_BYTES,
|
|
6924
|
+
HistoryStack: () => HistoryStack,
|
|
6925
|
+
InvalidBoardSetError: () => InvalidBoardSetError,
|
|
6926
|
+
InvalidPathError: () => InvalidPathError,
|
|
6927
|
+
MAX_OP_BYTES: () => MAX_OP_BYTES2,
|
|
6928
|
+
MAX_REPLAY: () => MAX_REPLAY,
|
|
6929
|
+
MIGRATIONS: () => MIGRATIONS,
|
|
6930
|
+
OPS: () => OPS2,
|
|
6931
|
+
OpSyncClient: () => OpSyncClient,
|
|
6932
|
+
OpTooLargeError: () => OpTooLargeError2,
|
|
6933
|
+
SCHEMA_VERSION: () => SCHEMA_VERSION2,
|
|
6934
|
+
SHAPE_NODE_TYPE: () => SHAPE_NODE_TYPE,
|
|
6935
|
+
anyPathCrosses: () => anyPathCrosses,
|
|
6936
|
+
applyBoardSet: () => applyBoardSet,
|
|
6937
|
+
applyConfirmed: () => applyConfirmed2,
|
|
6938
|
+
applyEnvelopes: () => applyEnvelopes,
|
|
6939
|
+
applyOp: () => applyOp,
|
|
6940
|
+
applyOps: () => applyOps,
|
|
6941
|
+
assertBoardSet: () => assertBoardSet,
|
|
6942
|
+
assertOpEnvelopeFits: () => assertOpEnvelopeFits,
|
|
6943
|
+
batchOf: () => batchOf2,
|
|
6944
|
+
boundsOf: () => boundsOf,
|
|
6945
|
+
captureOf: () => captureOf,
|
|
6946
|
+
createCloneCounts: () => createCloneCounts,
|
|
6947
|
+
createEmptyBoard: () => createEmptyBoard,
|
|
6948
|
+
createOpIdGenerator: () => createOpIdGenerator,
|
|
6949
|
+
createShapeNode: () => createShapeNode,
|
|
6950
|
+
defaultScheduler: () => defaultScheduler,
|
|
6951
|
+
estimateOpBytes: () => estimateOpBytes,
|
|
6952
|
+
fanOutPositions: () => fanOutPositions,
|
|
6953
|
+
findFreeSpot: () => findFreeSpot,
|
|
6954
|
+
getPath: () => getPath,
|
|
6955
|
+
hasPath: () => hasPath,
|
|
6956
|
+
invert: () => invert,
|
|
6957
|
+
invertBoardSet: () => invertBoardSet,
|
|
6958
|
+
invertEdgeAdd: () => invertEdgeAdd,
|
|
6959
|
+
invertEdgeRemove: () => invertEdgeRemove,
|
|
6960
|
+
invertHistoryAppend: () => invertHistoryAppend,
|
|
6961
|
+
invertHistoryRemove: () => invertHistoryRemove,
|
|
6962
|
+
invertNodeAdd: () => invertNodeAdd,
|
|
6963
|
+
invertNodeRemove: () => invertNodeRemove,
|
|
6964
|
+
invertNodeSet: () => invertNodeSet,
|
|
6965
|
+
invertResultSet: () => invertResultSet,
|
|
6966
|
+
isLocalEnvelope: () => isLocalEnvelope,
|
|
6967
|
+
isPropValue: () => isPropValue,
|
|
6968
|
+
migrate: () => migrate,
|
|
6969
|
+
moveOps: () => moveOps,
|
|
6970
|
+
newOpId: () => newOpId,
|
|
6971
|
+
opEnvelopeBytes: () => opEnvelopeBytes,
|
|
6972
|
+
parsePath: () => parsePath,
|
|
6973
|
+
pathsCross: () => pathsCross,
|
|
6974
|
+
placeWithoutOverlap: () => placeWithoutOverlap,
|
|
6975
|
+
propValue: () => propValue,
|
|
6976
|
+
rectOf: () => rectOf2,
|
|
6977
|
+
rectsCollide: () => rectsCollide,
|
|
6978
|
+
reduce: () => reduce,
|
|
6979
|
+
removeNode: () => removeNode,
|
|
6980
|
+
sameBox: () => sameBox,
|
|
6981
|
+
sameNodeIds: () => sameNodeIds,
|
|
6982
|
+
setPath: () => setPath,
|
|
6983
|
+
shallowestMissingPath: () => shallowestMissingPath,
|
|
6984
|
+
tidyUp: () => tidyUp,
|
|
6985
|
+
tidyUpOps: () => tidyUpOps,
|
|
6986
|
+
touchedPaths: () => touchedPaths,
|
|
6987
|
+
trackCapture: () => trackCapture,
|
|
6988
|
+
tryApplyEnvelope: () => tryApplyEnvelope,
|
|
6989
|
+
tryApplyOp: () => tryApplyOp,
|
|
6990
|
+
unsetPath: () => unsetPath,
|
|
6991
|
+
unsetPropValue: () => unsetPropValue,
|
|
6992
|
+
utf8ByteLength: () => utf8ByteLength,
|
|
6993
|
+
walkBatch: () => walkBatch,
|
|
6994
|
+
writeKey: () => writeKey
|
|
6995
|
+
});
|
|
6996
|
+
module.exports = __toCommonJS(index_exports);
|
|
6997
|
+
var SCHEMA_VERSION2 = 1;
|
|
6998
|
+
var SHAPE_NODE_TYPE = "shape";
|
|
6999
|
+
var DEFAULT_SHAPE_SIZE = { w: 180, h: 120 };
|
|
7000
|
+
function randomUuidV4() {
|
|
7001
|
+
let out = "";
|
|
7002
|
+
for (let i = 0; i < 36; i += 1) {
|
|
7003
|
+
if (i === 8 || i === 13 || i === 18 || i === 23) {
|
|
7004
|
+
out += "-";
|
|
7005
|
+
continue;
|
|
7006
|
+
}
|
|
7007
|
+
if (i === 14) {
|
|
7008
|
+
out += "4";
|
|
7009
|
+
continue;
|
|
7010
|
+
}
|
|
7011
|
+
const value = Math.floor(Math.random() * 16);
|
|
7012
|
+
out += (i === 19 ? value & 3 | 8 : value).toString(16);
|
|
7013
|
+
}
|
|
7014
|
+
return out;
|
|
7015
|
+
}
|
|
7016
|
+
function createEmptyBoard(init = {}) {
|
|
7017
|
+
const newId = init.newId ?? randomUuidV4;
|
|
7018
|
+
const timestamp = (init.now ?? Date.now)();
|
|
7019
|
+
return {
|
|
7020
|
+
id: init.id ?? newId(),
|
|
7021
|
+
schemaVersion: SCHEMA_VERSION2,
|
|
7022
|
+
title: init.title ?? "Board sem t\xEDtulo",
|
|
7023
|
+
ownerId: init.ownerId ?? "",
|
|
7024
|
+
folderId: init.folderId ?? null,
|
|
7025
|
+
version: 0,
|
|
7026
|
+
nodes: {},
|
|
7027
|
+
edges: {},
|
|
7028
|
+
results: {},
|
|
7029
|
+
nodeHistory: {},
|
|
7030
|
+
createdAt: timestamp,
|
|
7031
|
+
updatedAt: timestamp
|
|
7032
|
+
};
|
|
7033
|
+
}
|
|
7034
|
+
function createShapeNode(shape, init = {}) {
|
|
7035
|
+
const newId = init.newId ?? randomUuidV4;
|
|
7036
|
+
const timestamp = (init.now ?? Date.now)();
|
|
7037
|
+
return {
|
|
7038
|
+
id: init.id ?? newId(),
|
|
7039
|
+
type: SHAPE_NODE_TYPE,
|
|
7040
|
+
position: init.position ?? { x: 0, y: 0 },
|
|
7041
|
+
size: init.size ?? { w: DEFAULT_SHAPE_SIZE.w, h: DEFAULT_SHAPE_SIZE.h },
|
|
7042
|
+
zIndex: init.zIndex ?? 0,
|
|
7043
|
+
parentId: init.parentId ?? null,
|
|
7044
|
+
data: { shape },
|
|
7045
|
+
createdBy: init.createdBy ?? null,
|
|
7046
|
+
createdAt: timestamp,
|
|
7047
|
+
updatedAt: timestamp
|
|
7048
|
+
};
|
|
7049
|
+
}
|
|
7050
|
+
var MIGRATIONS = {};
|
|
7051
|
+
var MAX_MIGRATION_STEPS = 16;
|
|
7052
|
+
function isRecord2(value) {
|
|
7053
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7054
|
+
}
|
|
7055
|
+
function isFiniteNumber3(value) {
|
|
7056
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
7057
|
+
}
|
|
7058
|
+
function isStringOrNull2(value) {
|
|
7059
|
+
return value === null || typeof value === "string";
|
|
7060
|
+
}
|
|
7061
|
+
function isSeq(value) {
|
|
7062
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
7063
|
+
}
|
|
7064
|
+
function hasOnlyKeys2(record2, keys) {
|
|
7065
|
+
return Object.keys(record2).every((key) => keys.includes(key));
|
|
7066
|
+
}
|
|
7067
|
+
function isJson2(value) {
|
|
7068
|
+
if (value === null) return true;
|
|
7069
|
+
const kind = typeof value;
|
|
7070
|
+
if (kind === "boolean" || kind === "string") return true;
|
|
7071
|
+
if (kind === "number") return Number.isFinite(value);
|
|
7072
|
+
if (Array.isArray(value)) return value.every(isJson2);
|
|
7073
|
+
if (isRecord2(value)) return Object.values(value).every(isJson2);
|
|
7074
|
+
return false;
|
|
7075
|
+
}
|
|
7076
|
+
function isJsonBag2(value) {
|
|
7077
|
+
return isRecord2(value) && Object.values(value).every(isJson2);
|
|
7078
|
+
}
|
|
7079
|
+
function isStringMap(value) {
|
|
7080
|
+
return isRecord2(value) && Object.values(value).every((item) => typeof item === "string");
|
|
7081
|
+
}
|
|
7082
|
+
function isPoint2(value) {
|
|
7083
|
+
return isRecord2(value) && hasOnlyKeys2(value, ["x", "y"]) && isFiniteNumber3(value["x"]) && isFiniteNumber3(value["y"]);
|
|
7084
|
+
}
|
|
7085
|
+
function isSize2(value) {
|
|
7086
|
+
return isRecord2(value) && hasOnlyKeys2(value, ["w", "h"]) && isFiniteNumber3(value["w"]) && isFiniteNumber3(value["h"]);
|
|
7087
|
+
}
|
|
7088
|
+
var NODE_KEYS2 = [
|
|
7089
|
+
"id",
|
|
7090
|
+
"type",
|
|
7091
|
+
"position",
|
|
7092
|
+
"size",
|
|
7093
|
+
"zIndex",
|
|
7094
|
+
"parentId",
|
|
7095
|
+
"data",
|
|
7096
|
+
"createdBy",
|
|
7097
|
+
"createdAt",
|
|
7098
|
+
"updatedAt"
|
|
7099
|
+
];
|
|
7100
|
+
var EDGE_KEYS2 = [
|
|
7101
|
+
"id",
|
|
7102
|
+
"source",
|
|
7103
|
+
"sourcePort",
|
|
7104
|
+
"target",
|
|
7105
|
+
"targetPort",
|
|
7106
|
+
"data",
|
|
7107
|
+
"createdBy",
|
|
7108
|
+
"createdAt"
|
|
7109
|
+
];
|
|
7110
|
+
var RESULT_KEYS = [
|
|
7111
|
+
"id",
|
|
7112
|
+
"nodeId",
|
|
7113
|
+
"runId",
|
|
7114
|
+
"generationId",
|
|
7115
|
+
"kind",
|
|
7116
|
+
"url",
|
|
7117
|
+
"lodUrls",
|
|
7118
|
+
"status",
|
|
7119
|
+
"spec",
|
|
7120
|
+
"costDiamonds",
|
|
7121
|
+
"error",
|
|
7122
|
+
"createdAt"
|
|
7123
|
+
];
|
|
7124
|
+
var DOC_KEYS = [
|
|
7125
|
+
"id",
|
|
7126
|
+
"schemaVersion",
|
|
7127
|
+
"title",
|
|
7128
|
+
"ownerId",
|
|
7129
|
+
"folderId",
|
|
7130
|
+
"version",
|
|
7131
|
+
"nodes",
|
|
7132
|
+
"edges",
|
|
7133
|
+
"results",
|
|
7134
|
+
"nodeHistory",
|
|
7135
|
+
"createdAt",
|
|
7136
|
+
"updatedAt",
|
|
7137
|
+
"meta"
|
|
7138
|
+
];
|
|
7139
|
+
var META_KEYS = ["guide", "ialab", "assetUrls"];
|
|
7140
|
+
function isValidMeta(value) {
|
|
7141
|
+
if (value === void 0) return true;
|
|
7142
|
+
return isRecord2(value) && hasOnlyKeys2(value, META_KEYS) && (value["guide"] === void 0 || isStringOrNull2(value["guide"])) && (value["ialab"] === void 0 || value["ialab"] === null || isJsonBag2(value["ialab"])) && (value["assetUrls"] === void 0 || isStringMap(value["assetUrls"]));
|
|
7143
|
+
}
|
|
7144
|
+
var RESULT_KINDS = ["image", "video", "audio", "text"];
|
|
7145
|
+
var RESULT_STATUSES = ["pending", "running", "done", "failed", "cancelled"];
|
|
7146
|
+
function isValidNode2(key, value) {
|
|
7147
|
+
return isRecord2(value) && hasOnlyKeys2(value, NODE_KEYS2) && value["id"] === key && typeof value["type"] === "string" && isPoint2(value["position"]) && isSize2(value["size"]) && isFiniteNumber3(value["zIndex"]) && isStringOrNull2(value["parentId"]) && isJsonBag2(value["data"]) && isStringOrNull2(value["createdBy"]) && isFiniteNumber3(value["createdAt"]) && isFiniteNumber3(value["updatedAt"]);
|
|
7148
|
+
}
|
|
7149
|
+
function isValidEdge2(key, value) {
|
|
7150
|
+
return isRecord2(value) && hasOnlyKeys2(value, EDGE_KEYS2) && value["id"] === key && typeof value["source"] === "string" && typeof value["sourcePort"] === "string" && typeof value["target"] === "string" && typeof value["targetPort"] === "string" && isJsonBag2(value["data"]) && isStringOrNull2(value["createdBy"]) && isFiniteNumber3(value["createdAt"]);
|
|
7151
|
+
}
|
|
7152
|
+
function isValidResult(key, value) {
|
|
7153
|
+
return isRecord2(value) && hasOnlyKeys2(value, RESULT_KEYS) && value["id"] === key && typeof value["nodeId"] === "string" && isStringOrNull2(value["runId"]) && isStringOrNull2(value["generationId"]) && typeof value["kind"] === "string" && RESULT_KINDS.includes(value["kind"]) && isStringOrNull2(value["url"]) && isStringMap(value["lodUrls"]) && typeof value["status"] === "string" && RESULT_STATUSES.includes(value["status"]) && isJsonBag2(value["spec"]) && (value["costDiamonds"] === null || isFiniteNumber3(value["costDiamonds"])) && isStringOrNull2(value["error"]) && isFiniteNumber3(value["createdAt"]);
|
|
7154
|
+
}
|
|
7155
|
+
function isValidHistory(value) {
|
|
7156
|
+
return Array.isArray(value) && value.every((resultId) => typeof resultId === "string");
|
|
7157
|
+
}
|
|
7158
|
+
function normalizeHistory(history) {
|
|
7159
|
+
for (const [nodeId3, list] of Object.entries(history)) {
|
|
7160
|
+
if (Array.isArray(list) && list.length === 0) delete history[nodeId3];
|
|
7161
|
+
}
|
|
7162
|
+
}
|
|
7163
|
+
function everyEntry(value, check2) {
|
|
7164
|
+
return isRecord2(value) && Object.entries(value).every(([key, entry]) => check2(key, entry));
|
|
7165
|
+
}
|
|
7166
|
+
function upgrade(raw) {
|
|
7167
|
+
let current = raw;
|
|
7168
|
+
for (let step2 = 0; step2 <= MAX_MIGRATION_STEPS; step2 += 1) {
|
|
7169
|
+
if (!isRecord2(current)) return null;
|
|
7170
|
+
const version2 = current["schemaVersion"];
|
|
7171
|
+
if (typeof version2 !== "number" || !Number.isInteger(version2)) return null;
|
|
7172
|
+
if (version2 === SCHEMA_VERSION2) return current;
|
|
7173
|
+
const migration = MIGRATIONS[version2];
|
|
7174
|
+
if (migration === void 0) return null;
|
|
7175
|
+
current = migration(current);
|
|
7176
|
+
}
|
|
7177
|
+
return null;
|
|
7178
|
+
}
|
|
7179
|
+
function migrate(raw) {
|
|
7180
|
+
try {
|
|
7181
|
+
return read(raw);
|
|
7182
|
+
} catch {
|
|
7183
|
+
return null;
|
|
7184
|
+
}
|
|
7185
|
+
}
|
|
7186
|
+
function read(raw) {
|
|
7187
|
+
const upgraded = upgrade(raw);
|
|
7188
|
+
if (!isRecord2(upgraded)) return null;
|
|
7189
|
+
const ok = hasOnlyKeys2(upgraded, DOC_KEYS) && typeof upgraded["id"] === "string" && upgraded["schemaVersion"] === SCHEMA_VERSION2 && typeof upgraded["title"] === "string" && typeof upgraded["ownerId"] === "string" && isStringOrNull2(upgraded["folderId"]) && isSeq(upgraded["version"]) && everyEntry(upgraded["nodes"], isValidNode2) && everyEntry(upgraded["edges"], isValidEdge2) && everyEntry(upgraded["results"], isValidResult) && everyEntry(upgraded["nodeHistory"], (_key, entry) => isValidHistory(entry)) && isFiniteNumber3(upgraded["createdAt"]) && isFiniteNumber3(upgraded["updatedAt"]) && isValidMeta(upgraded["meta"]);
|
|
7190
|
+
if (!ok) return null;
|
|
7191
|
+
if (isRecord2(upgraded["meta"]) && Object.keys(upgraded["meta"]).length === 0) {
|
|
7192
|
+
delete upgraded["meta"];
|
|
7193
|
+
}
|
|
7194
|
+
normalizeHistory(upgraded["nodeHistory"]);
|
|
7195
|
+
return upgraded;
|
|
7196
|
+
}
|
|
7197
|
+
function propValue(value) {
|
|
7198
|
+
return { kind: "value", value };
|
|
7199
|
+
}
|
|
7200
|
+
function unsetPropValue() {
|
|
7201
|
+
return { kind: "unset" };
|
|
7202
|
+
}
|
|
7203
|
+
function isJson22(root) {
|
|
7204
|
+
const pending = [{ visit: root }];
|
|
7205
|
+
const open3 = /* @__PURE__ */ new Set();
|
|
7206
|
+
for (let step2 = pending.pop(); step2 !== void 0; step2 = pending.pop()) {
|
|
7207
|
+
if ("close" in step2) {
|
|
7208
|
+
open3.delete(step2.close);
|
|
7209
|
+
continue;
|
|
7210
|
+
}
|
|
7211
|
+
const value = step2.visit;
|
|
7212
|
+
if (value === null) continue;
|
|
7213
|
+
const kind = typeof value;
|
|
7214
|
+
if (kind === "boolean" || kind === "string") continue;
|
|
7215
|
+
if (kind === "number") {
|
|
7216
|
+
if (!Number.isFinite(value)) return false;
|
|
7217
|
+
continue;
|
|
7218
|
+
}
|
|
7219
|
+
if (kind !== "object") return false;
|
|
7220
|
+
const node = value;
|
|
7221
|
+
if (open3.has(node)) return false;
|
|
7222
|
+
open3.add(node);
|
|
7223
|
+
pending.push({ close: node });
|
|
7224
|
+
const children = Array.isArray(node) ? node : Object.values(node);
|
|
7225
|
+
for (const item of children) pending.push({ visit: item });
|
|
7226
|
+
}
|
|
7227
|
+
return true;
|
|
7228
|
+
}
|
|
7229
|
+
function isPropValue(candidate) {
|
|
7230
|
+
if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) return false;
|
|
7231
|
+
const record2 = candidate;
|
|
7232
|
+
const keys = Object.keys(record2);
|
|
7233
|
+
if (record2["kind"] === "unset") return keys.length === 1;
|
|
7234
|
+
if (record2["kind"] !== "value") return false;
|
|
7235
|
+
if (keys.length !== 2 || !Object.hasOwn(record2, "value")) return false;
|
|
7236
|
+
return isJson22(record2["value"]);
|
|
7237
|
+
}
|
|
7238
|
+
var FORBIDDEN_PATH_SEGMENTS = ["__proto__", "constructor", "prototype"];
|
|
7239
|
+
var InvalidPathError = class extends Error {
|
|
7240
|
+
/** O caminho recusado, já como veio da operação. */
|
|
7241
|
+
path;
|
|
7242
|
+
constructor(path, reason) {
|
|
7243
|
+
super(`Caminho inv\xE1lido em node.set: ${JSON.stringify(path)} \u2014 ${reason}`);
|
|
7244
|
+
this.name = "InvalidPathError";
|
|
7245
|
+
this.path = path;
|
|
7246
|
+
}
|
|
7247
|
+
};
|
|
7248
|
+
function asRecord(value) {
|
|
7249
|
+
return value;
|
|
7250
|
+
}
|
|
7251
|
+
function isPlainRecord(value) {
|
|
7252
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7253
|
+
}
|
|
7254
|
+
function parsePath(path) {
|
|
7255
|
+
if (path.length === 0) throw new InvalidPathError(path, "caminho vazio");
|
|
7256
|
+
const segments = path.split(".");
|
|
7257
|
+
for (const segment of segments) {
|
|
7258
|
+
if (segment.length === 0) throw new InvalidPathError(path, "segmento vazio entre pontos");
|
|
7259
|
+
if (FORBIDDEN_PATH_SEGMENTS.includes(segment)) {
|
|
7260
|
+
throw new InvalidPathError(path, `segmento proibido: ${segment}`);
|
|
7261
|
+
}
|
|
7262
|
+
}
|
|
7263
|
+
return segments;
|
|
7264
|
+
}
|
|
7265
|
+
function splitLeaf(path) {
|
|
7266
|
+
const segments = parsePath(path);
|
|
7267
|
+
const leaf = segments[segments.length - 1];
|
|
7268
|
+
if (leaf === void 0) throw new InvalidPathError(path, "caminho sem folha");
|
|
7269
|
+
return { parents: segments.slice(0, -1), leaf };
|
|
7270
|
+
}
|
|
7271
|
+
function getPath(target, path) {
|
|
7272
|
+
const segments = parsePath(path);
|
|
7273
|
+
let cursor = target;
|
|
7274
|
+
for (const segment of segments) {
|
|
7275
|
+
if (!isPlainRecord(cursor) || !Object.hasOwn(cursor, segment)) return void 0;
|
|
7276
|
+
cursor = cursor[segment];
|
|
7277
|
+
}
|
|
7278
|
+
return cursor;
|
|
7279
|
+
}
|
|
7280
|
+
function hasPath(target, path) {
|
|
7281
|
+
const segments = parsePath(path);
|
|
7282
|
+
let cursor = target;
|
|
7283
|
+
for (const segment of segments) {
|
|
7284
|
+
if (!isPlainRecord(cursor) || !Object.hasOwn(cursor, segment)) return false;
|
|
7285
|
+
cursor = cursor[segment];
|
|
7286
|
+
}
|
|
7287
|
+
return true;
|
|
7288
|
+
}
|
|
7289
|
+
function setPath(target, path, value) {
|
|
7290
|
+
const { parents, leaf } = splitLeaf(path);
|
|
7291
|
+
const root = { ...asRecord(target) };
|
|
7292
|
+
let cursor = root;
|
|
7293
|
+
for (const segment of parents) {
|
|
7294
|
+
const current = Object.hasOwn(cursor, segment) ? cursor[segment] : void 0;
|
|
7295
|
+
if (current === void 0) {
|
|
7296
|
+
const created = {};
|
|
7297
|
+
writeKey(cursor, segment, created);
|
|
7298
|
+
cursor = created;
|
|
7299
|
+
continue;
|
|
7300
|
+
}
|
|
7301
|
+
if (!isPlainRecord(current)) {
|
|
7302
|
+
throw new InvalidPathError(path, `o n\xEDvel ${segment} existe e n\xE3o \xE9 objeto`);
|
|
7303
|
+
}
|
|
7304
|
+
const cloned = { ...current };
|
|
7305
|
+
writeKey(cursor, segment, cloned);
|
|
7306
|
+
cursor = cloned;
|
|
7307
|
+
}
|
|
7308
|
+
writeKey(cursor, leaf, value);
|
|
7309
|
+
return root;
|
|
7310
|
+
}
|
|
7311
|
+
function unsetPath(target, path) {
|
|
7312
|
+
if (!hasPath(target, path)) return target;
|
|
7313
|
+
const { parents, leaf } = splitLeaf(path);
|
|
7314
|
+
const root = { ...asRecord(target) };
|
|
7315
|
+
let cursor = root;
|
|
7316
|
+
for (const segment of parents) {
|
|
7317
|
+
const current = cursor[segment];
|
|
7318
|
+
if (!isPlainRecord(current))
|
|
7319
|
+
throw new InvalidPathError(path, `o n\xEDvel ${segment} n\xE3o \xE9 objeto`);
|
|
7320
|
+
const cloned = { ...current };
|
|
7321
|
+
writeKey(cursor, segment, cloned);
|
|
7322
|
+
cursor = cloned;
|
|
7323
|
+
}
|
|
7324
|
+
delete cursor[leaf];
|
|
7325
|
+
return root;
|
|
7326
|
+
}
|
|
7327
|
+
function writeKey(record2, key, value) {
|
|
7328
|
+
if (key === "__proto__") {
|
|
7329
|
+
Object.defineProperty(record2, key, {
|
|
7330
|
+
value,
|
|
7331
|
+
writable: true,
|
|
7332
|
+
enumerable: true,
|
|
7333
|
+
configurable: true
|
|
7334
|
+
});
|
|
7335
|
+
return;
|
|
7336
|
+
}
|
|
7337
|
+
record2[key] = value;
|
|
7338
|
+
}
|
|
7339
|
+
function createCloneCounts() {
|
|
7340
|
+
return { doc: 0, nodes: 0, edges: 0, results: 0, nodeHistory: 0, nodeEntry: 0, historyEntry: 0 };
|
|
7341
|
+
}
|
|
7342
|
+
var Draft = class {
|
|
7343
|
+
base;
|
|
7344
|
+
counts;
|
|
7345
|
+
nodes;
|
|
7346
|
+
edges;
|
|
7347
|
+
results;
|
|
7348
|
+
nodeHistory;
|
|
7349
|
+
nodesOwned = false;
|
|
7350
|
+
edgesOwned = false;
|
|
7351
|
+
resultsOwned = false;
|
|
7352
|
+
nodeHistoryOwned = false;
|
|
7353
|
+
changed = /* @__PURE__ */ new Set();
|
|
7354
|
+
/** Título e metadado do board (`board.set`). Só entram no documento novo se foram escritos. */
|
|
7355
|
+
title;
|
|
7356
|
+
titleChanged = false;
|
|
7357
|
+
boardMeta;
|
|
7358
|
+
metaOwned = false;
|
|
7359
|
+
constructor(base, counts) {
|
|
7360
|
+
this.base = base;
|
|
7361
|
+
this.counts = counts;
|
|
7362
|
+
this.nodes = base.nodes;
|
|
7363
|
+
this.edges = base.edges;
|
|
7364
|
+
this.results = base.results;
|
|
7365
|
+
this.nodeHistory = base.nodeHistory;
|
|
7366
|
+
this.title = base.title;
|
|
7367
|
+
this.boardMeta = base.meta;
|
|
7368
|
+
}
|
|
7369
|
+
// ------------------------------------------------------------------- leitura
|
|
7370
|
+
node(id) {
|
|
7371
|
+
return Object.hasOwn(this.nodes, id) ? this.nodes[id] : void 0;
|
|
7372
|
+
}
|
|
7373
|
+
edge(id) {
|
|
7374
|
+
return Object.hasOwn(this.edges, id) ? this.edges[id] : void 0;
|
|
7375
|
+
}
|
|
7376
|
+
// Não existe leitor de `results` aqui: `result.set` grava sem consultar, e a
|
|
7377
|
+
// inversa dele é nula (story 004). Ler resultado é da fase 2, e o método nasce
|
|
7378
|
+
// no dia em que tiver chamador.
|
|
7379
|
+
history(nodeId3) {
|
|
7380
|
+
return Object.hasOwn(this.nodeHistory, nodeId3) ? this.nodeHistory[nodeId3] : void 0;
|
|
7381
|
+
}
|
|
7382
|
+
/** O título do board como está no rascunho. */
|
|
7383
|
+
boardTitle() {
|
|
7384
|
+
return this.title;
|
|
7385
|
+
}
|
|
7386
|
+
/** O metadado do board como está no rascunho. Ausente: sem metadado. */
|
|
7387
|
+
meta() {
|
|
7388
|
+
return this.boardMeta;
|
|
7389
|
+
}
|
|
7390
|
+
/** Marca o nó como tocado, para o `changedNodeIds` que a projeção lê. */
|
|
7391
|
+
touch(nodeId3) {
|
|
7392
|
+
this.changed.add(nodeId3);
|
|
7393
|
+
}
|
|
7394
|
+
// ------------------------------------------------------------------- escrita
|
|
7395
|
+
putNode(id, node) {
|
|
7396
|
+
this.ownNodes();
|
|
7397
|
+
writeKey(this.nodes, id, node);
|
|
7398
|
+
this.changed.add(id);
|
|
7399
|
+
}
|
|
7400
|
+
/**
|
|
7401
|
+
* Apaga o nó e, junto, a chave de histórico dele que já era lista vazia.
|
|
7402
|
+
*
|
|
7403
|
+
* Apagar a chave não é limpeza de referência, é normalização: lista vazia não
|
|
7404
|
+
* existe na forma canônica, chave ausente é que significa "sem variação"
|
|
7405
|
+
* (`dev/PLANO-FASE-0.md` §4). Descartar `[]` não perde informação nenhuma, e
|
|
7406
|
+
* por isso a inversa `node.add` devolve um documento equivalente sem precisar
|
|
7407
|
+
* recriar a chave. Chave com item continua intocada: aí sim existe informação,
|
|
7408
|
+
* e `node.remove` nunca limpa sozinho nada que carregue informação. Quem tira
|
|
7409
|
+
* as variações de um nó que vai embora é o `batch` de `removeNode`.
|
|
7410
|
+
*
|
|
7411
|
+
* Nó ausente sai antes de qualquer cópia, senão um `node.remove` que o CA8
|
|
7412
|
+
* declara no-op sujaria o rascunho e produziria documento novo por nada.
|
|
7413
|
+
*/
|
|
7414
|
+
dropNode(id) {
|
|
7415
|
+
if (!Object.hasOwn(this.nodes, id)) return;
|
|
7416
|
+
this.ownNodes();
|
|
7417
|
+
delete this.nodes[id];
|
|
7418
|
+
this.changed.add(id);
|
|
7419
|
+
this.discardEmptyHistory(id);
|
|
7420
|
+
}
|
|
7421
|
+
discardEmptyHistory(nodeId3) {
|
|
7422
|
+
const current = this.history(nodeId3);
|
|
7423
|
+
if (current === void 0 || current.length > 0) return;
|
|
7424
|
+
this.ownNodeHistory();
|
|
7425
|
+
delete this.nodeHistory[nodeId3];
|
|
7426
|
+
}
|
|
7427
|
+
/**
|
|
7428
|
+
* Troca um nó pelo resultado de uma escrita por caminho.
|
|
7429
|
+
*
|
|
7430
|
+
* A função recebe o nó e devolve o nó novo, ou o mesmo quando não há o que
|
|
7431
|
+
* mudar. Devolvendo o mesmo, nada é escrito e nenhuma coleção é clonada: é
|
|
7432
|
+
* assim que `node.set` sem efeito sai de graça.
|
|
7433
|
+
*/
|
|
7434
|
+
mutateNode(id, change) {
|
|
7435
|
+
const current = this.node(id);
|
|
7436
|
+
if (current === void 0) return;
|
|
7437
|
+
const next = change(current);
|
|
7438
|
+
if (next === current) return;
|
|
7439
|
+
if (this.counts !== void 0) this.counts.nodeEntry += 1;
|
|
7440
|
+
this.putNode(id, next);
|
|
7441
|
+
}
|
|
7442
|
+
putEdge(id, edge) {
|
|
7443
|
+
this.ownEdges();
|
|
7444
|
+
writeKey(this.edges, id, edge);
|
|
7445
|
+
}
|
|
7446
|
+
dropEdge(id) {
|
|
7447
|
+
if (!Object.hasOwn(this.edges, id)) return;
|
|
7448
|
+
this.ownEdges();
|
|
7449
|
+
delete this.edges[id];
|
|
7450
|
+
}
|
|
7451
|
+
putResult(id, entry) {
|
|
7452
|
+
this.ownResults();
|
|
7453
|
+
writeKey(this.results, id, entry);
|
|
7454
|
+
}
|
|
7455
|
+
/**
|
|
7456
|
+
* Acrescenta uma variação ao histórico do nó, no fim da lista.
|
|
7457
|
+
*
|
|
7458
|
+
* A lista nasce na primeira chamada. Id repetido entra de novo, de propósito:
|
|
7459
|
+
* `history.remove` tira a última ocorrência, então append seguido de remove
|
|
7460
|
+
* devolve a lista exatamente como estava, que é o que a inversa da story 004
|
|
7461
|
+
* precisa.
|
|
7462
|
+
*/
|
|
7463
|
+
appendHistory(nodeId3, resultId) {
|
|
7464
|
+
const current = this.history(nodeId3);
|
|
7465
|
+
const next = current === void 0 ? [] : [...current];
|
|
7466
|
+
if (current !== void 0 && this.counts !== void 0) this.counts.historyEntry += 1;
|
|
7467
|
+
next.push(resultId);
|
|
7468
|
+
this.ownNodeHistory();
|
|
7469
|
+
writeKey(this.nodeHistory, nodeId3, next);
|
|
7470
|
+
this.changed.add(nodeId3);
|
|
7471
|
+
}
|
|
7472
|
+
/**
|
|
7473
|
+
* Tira a última ocorrência da variação no histórico do nó.
|
|
7474
|
+
*
|
|
7475
|
+
* Id ausente é no-op. Lista que fica vazia some junto com a chave: histórico
|
|
7476
|
+
* vazio pendurado em nó que vai ser apagado é exatamente a referência órfã que
|
|
7477
|
+
* o §4 do plano proíbe, e é o que o CA9 cobra depois de `removeNode`.
|
|
7478
|
+
*/
|
|
7479
|
+
removeHistory(nodeId3, resultId) {
|
|
7480
|
+
const current = this.history(nodeId3);
|
|
7481
|
+
if (current === void 0) return;
|
|
7482
|
+
const at = current.lastIndexOf(resultId);
|
|
7483
|
+
if (at === -1) return;
|
|
7484
|
+
if (this.counts !== void 0) this.counts.historyEntry += 1;
|
|
7485
|
+
const next = [...current.slice(0, at), ...current.slice(at + 1)];
|
|
7486
|
+
this.ownNodeHistory();
|
|
7487
|
+
if (next.length === 0) {
|
|
7488
|
+
delete this.nodeHistory[nodeId3];
|
|
7489
|
+
} else {
|
|
7490
|
+
writeKey(this.nodeHistory, nodeId3, next);
|
|
7491
|
+
}
|
|
7492
|
+
this.changed.add(nodeId3);
|
|
7493
|
+
}
|
|
7494
|
+
/** Troca o título. Título igual sai de graça, sem documento novo. */
|
|
7495
|
+
setTitle(title) {
|
|
7496
|
+
if (title === this.title) return;
|
|
7497
|
+
this.title = title;
|
|
7498
|
+
this.titleChanged = true;
|
|
7499
|
+
}
|
|
7500
|
+
/**
|
|
7501
|
+
* Troca o metadado inteiro do board pela versão que `change` devolve.
|
|
7502
|
+
*
|
|
7503
|
+
* Metadado vazio vira ausente: `{}` não existe na forma canônica, pela mesma
|
|
7504
|
+
* razão da lista vazia de `nodeHistory`. Sem isso, gravar e desfazer a dica
|
|
7505
|
+
* num board sem metadado devolveria um documento com `meta: {}` a mais.
|
|
7506
|
+
*/
|
|
7507
|
+
mutateMeta(change) {
|
|
7508
|
+
const current = this.boardMeta ?? {};
|
|
7509
|
+
const next = change(current);
|
|
7510
|
+
if (next === current) return;
|
|
7511
|
+
this.boardMeta = Object.keys(next).length === 0 ? void 0 : next;
|
|
7512
|
+
this.metaOwned = true;
|
|
7513
|
+
}
|
|
7514
|
+
// --------------------------------------------------------- cópia por escrita
|
|
7515
|
+
ownNodes() {
|
|
7516
|
+
if (this.nodesOwned) return;
|
|
7517
|
+
this.nodes = { ...this.base.nodes };
|
|
7518
|
+
this.nodesOwned = true;
|
|
7519
|
+
if (this.counts !== void 0) this.counts.nodes += 1;
|
|
7520
|
+
}
|
|
7521
|
+
ownEdges() {
|
|
7522
|
+
if (this.edgesOwned) return;
|
|
7523
|
+
this.edges = { ...this.base.edges };
|
|
7524
|
+
this.edgesOwned = true;
|
|
7525
|
+
if (this.counts !== void 0) this.counts.edges += 1;
|
|
7526
|
+
}
|
|
7527
|
+
ownResults() {
|
|
7528
|
+
if (this.resultsOwned) return;
|
|
7529
|
+
this.results = { ...this.base.results };
|
|
7530
|
+
this.resultsOwned = true;
|
|
7531
|
+
if (this.counts !== void 0) this.counts.results += 1;
|
|
7532
|
+
}
|
|
7533
|
+
ownNodeHistory() {
|
|
7534
|
+
if (this.nodeHistoryOwned) return;
|
|
7535
|
+
this.nodeHistory = { ...this.base.nodeHistory };
|
|
7536
|
+
this.nodeHistoryOwned = true;
|
|
7537
|
+
if (this.counts !== void 0) this.counts.nodeHistory += 1;
|
|
7538
|
+
}
|
|
7539
|
+
// ---------------------------------------------------------------- fechamento
|
|
7540
|
+
/** Alguma coleção foi escrita? Lote de no-ops não produz documento novo. */
|
|
7541
|
+
get dirty() {
|
|
7542
|
+
return this.nodesOwned || this.edgesOwned || this.resultsOwned || this.nodeHistoryOwned || this.titleChanged || this.metaOwned;
|
|
7543
|
+
}
|
|
7544
|
+
/**
|
|
7545
|
+
* Fecha o rascunho.
|
|
7546
|
+
*
|
|
7547
|
+
* Sem escrita, devolve a própria referência de entrada: o lote inteiro de
|
|
7548
|
+
* no-ops não gera documento novo e a tela não re-renderiza por nada.
|
|
7549
|
+
*
|
|
7550
|
+
* O documento sai sem `Object.freeze`, desvio do plano §4 ("congela e
|
|
7551
|
+
* devolve"), e a razão é custo e alcance. Congelamento fundo percorre o
|
|
7552
|
+
* documento inteiro a cada lote e joga fora justamente o ganho da cópia por
|
|
7553
|
+
* escrita. Congelamento raso protegeria só o objeto de topo, enquanto
|
|
7554
|
+
* `nodes`, `edges`, `results` e `nodeHistory` continuariam mutáveis, e compra
|
|
7555
|
+
* quase nada. Escrever `version` depois não é argumento contra congelar:
|
|
7556
|
+
* spread funciona sobre objeto congelado, e é o que `reduce` já faz. A
|
|
7557
|
+
* garantia de imutabilidade da entrada é estrutural e tem teste.
|
|
7558
|
+
*/
|
|
7559
|
+
finish() {
|
|
7560
|
+
const changedNodeIds = [...this.changed];
|
|
7561
|
+
if (!this.dirty) return { doc: this.base, changedNodeIds };
|
|
7562
|
+
if (this.counts !== void 0) this.counts.doc += 1;
|
|
7563
|
+
const doc = {
|
|
7564
|
+
...this.base,
|
|
7565
|
+
nodes: this.nodes,
|
|
7566
|
+
edges: this.edges,
|
|
7567
|
+
results: this.results,
|
|
7568
|
+
nodeHistory: this.nodeHistory
|
|
7569
|
+
};
|
|
7570
|
+
if (this.titleChanged) doc.title = this.title;
|
|
7571
|
+
if (this.metaOwned) {
|
|
7572
|
+
if (this.boardMeta === void 0) delete doc.meta;
|
|
7573
|
+
else doc.meta = this.boardMeta;
|
|
7574
|
+
}
|
|
7575
|
+
return { doc, changedNodeIds };
|
|
7576
|
+
}
|
|
7577
|
+
};
|
|
7578
|
+
function nodeOf(doc, id) {
|
|
7579
|
+
return Object.hasOwn(doc.nodes, id) ? doc.nodes[id] : void 0;
|
|
7580
|
+
}
|
|
7581
|
+
function edgeOf(doc, id) {
|
|
7582
|
+
return Object.hasOwn(doc.edges, id) ? doc.edges[id] : void 0;
|
|
7583
|
+
}
|
|
7584
|
+
function historyOf(doc, nodeId3) {
|
|
7585
|
+
return Object.hasOwn(doc.nodeHistory, nodeId3) ? doc.nodeHistory[nodeId3] : void 0;
|
|
7586
|
+
}
|
|
7587
|
+
function previousValue(node, path) {
|
|
7588
|
+
return getPath(node, path);
|
|
7589
|
+
}
|
|
7590
|
+
function shallowestMissingPath(target, path) {
|
|
7591
|
+
const walked = [];
|
|
7592
|
+
for (const segment of parsePath(path)) {
|
|
7593
|
+
walked.push(segment);
|
|
7594
|
+
const prefix = walked.join(".");
|
|
7595
|
+
if (!hasPath(target, prefix)) return prefix;
|
|
7596
|
+
}
|
|
7597
|
+
return path;
|
|
7598
|
+
}
|
|
7599
|
+
function invertNodeAdd(doc, op) {
|
|
7600
|
+
const previous = nodeOf(doc, op.nodeId);
|
|
7601
|
+
if (previous === void 0) return { type: "node.remove", nodeId: op.nodeId };
|
|
7602
|
+
return { type: "node.add", nodeId: op.nodeId, node: previous };
|
|
7603
|
+
}
|
|
7604
|
+
function invertNodeRemove(doc, op) {
|
|
7605
|
+
const current = nodeOf(doc, op.nodeId);
|
|
7606
|
+
if (current === void 0) return { type: "node.remove", nodeId: op.nodeId };
|
|
7607
|
+
return { type: "node.add", nodeId: op.nodeId, node: current };
|
|
7608
|
+
}
|
|
7609
|
+
function invertNodeSet(doc, op) {
|
|
7610
|
+
const node = nodeOf(doc, op.nodeId);
|
|
7611
|
+
if (node === void 0) {
|
|
7612
|
+
return { type: "node.set", nodeId: op.nodeId, path: op.path, value: unsetPropValue() };
|
|
7613
|
+
}
|
|
7614
|
+
if (hasPath(node, op.path)) {
|
|
7615
|
+
return {
|
|
7616
|
+
type: "node.set",
|
|
7617
|
+
nodeId: op.nodeId,
|
|
7618
|
+
path: op.path,
|
|
7619
|
+
value: propValue(previousValue(node, op.path))
|
|
7620
|
+
};
|
|
7621
|
+
}
|
|
7622
|
+
return {
|
|
7623
|
+
type: "node.set",
|
|
7624
|
+
nodeId: op.nodeId,
|
|
7625
|
+
path: shallowestMissingPath(node, op.path),
|
|
7626
|
+
value: unsetPropValue()
|
|
7627
|
+
};
|
|
7628
|
+
}
|
|
7629
|
+
function invertEdgeAdd(doc, op) {
|
|
7630
|
+
const previous = edgeOf(doc, op.edgeId);
|
|
7631
|
+
if (previous === void 0) return { type: "edge.remove", edgeId: op.edgeId };
|
|
7632
|
+
return { type: "edge.add", edgeId: op.edgeId, edge: previous };
|
|
7633
|
+
}
|
|
7634
|
+
function invertEdgeRemove(doc, op) {
|
|
7635
|
+
const current = edgeOf(doc, op.edgeId);
|
|
7636
|
+
if (current === void 0) return { type: "edge.remove", edgeId: op.edgeId };
|
|
7637
|
+
return { type: "edge.add", edgeId: op.edgeId, edge: current };
|
|
7638
|
+
}
|
|
7639
|
+
function invertResultSet() {
|
|
7640
|
+
return null;
|
|
7641
|
+
}
|
|
7642
|
+
function invertHistoryAppend(op) {
|
|
7643
|
+
return { type: "history.remove", nodeId: op.nodeId, resultId: op.resultId };
|
|
7644
|
+
}
|
|
7645
|
+
function invertHistoryRemove(doc, op) {
|
|
7646
|
+
const list = historyOf(doc, op.nodeId);
|
|
7647
|
+
const at = list === void 0 ? -1 : list.lastIndexOf(op.resultId);
|
|
7648
|
+
if (list === void 0 || at === -1) {
|
|
7649
|
+
return { type: "history.remove", nodeId: op.nodeId, resultId: op.resultId };
|
|
7650
|
+
}
|
|
7651
|
+
if (at === list.length - 1) {
|
|
7652
|
+
return { type: "history.append", nodeId: op.nodeId, resultId: op.resultId };
|
|
7653
|
+
}
|
|
7654
|
+
const tail = list.slice(at + 1);
|
|
7655
|
+
const ops = [];
|
|
7656
|
+
for (const resultId of [...tail].reverse()) {
|
|
7657
|
+
ops.push({ type: "history.remove", nodeId: op.nodeId, resultId });
|
|
7658
|
+
}
|
|
7659
|
+
ops.push({ type: "history.append", nodeId: op.nodeId, resultId: op.resultId });
|
|
7660
|
+
for (const resultId of tail) {
|
|
7661
|
+
ops.push({ type: "history.append", nodeId: op.nodeId, resultId });
|
|
7662
|
+
}
|
|
7663
|
+
return { type: "batch", ops };
|
|
7664
|
+
}
|
|
7665
|
+
var BOARD_FIELDS = ["title", "guide", "ialab", "assetUrls"];
|
|
7666
|
+
var InvalidBoardSetError = class extends Error {
|
|
7667
|
+
field;
|
|
7668
|
+
constructor(field, reason) {
|
|
7669
|
+
super(`board.set inv\xE1lido em ${JSON.stringify(field)}: ${reason}`);
|
|
7670
|
+
this.name = "InvalidBoardSetError";
|
|
7671
|
+
this.field = field;
|
|
7672
|
+
}
|
|
7673
|
+
};
|
|
7674
|
+
function isPlainRecord2(value) {
|
|
7675
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7676
|
+
}
|
|
7677
|
+
function isStringMap2(value) {
|
|
7678
|
+
return isPlainRecord2(value) && Object.values(value).every((item) => typeof item === "string");
|
|
7679
|
+
}
|
|
7680
|
+
function assertBoardSet(op) {
|
|
7681
|
+
const { field, key, value } = op;
|
|
7682
|
+
if (!BOARD_FIELDS.includes(field)) throw new InvalidBoardSetError(field, "campo desconhecido");
|
|
7683
|
+
if (key !== void 0) {
|
|
7684
|
+
if (field !== "assetUrls") throw new InvalidBoardSetError(field, "s\xF3 assetUrls aceita key");
|
|
7685
|
+
if (key === "" || FORBIDDEN_PATH_SEGMENTS.includes(key)) {
|
|
7686
|
+
throw new InvalidBoardSetError(field, `key recusada: ${JSON.stringify(key)}`);
|
|
7687
|
+
}
|
|
7688
|
+
}
|
|
7689
|
+
if (value.kind === "unset") {
|
|
7690
|
+
if (field === "title") throw new InvalidBoardSetError(field, "t\xEDtulo n\xE3o pode ser apagado");
|
|
7691
|
+
return;
|
|
7692
|
+
}
|
|
7693
|
+
const raw = value.value;
|
|
7694
|
+
const ok = field === "title" ? typeof raw === "string" : field === "guide" ? raw === null || typeof raw === "string" : field === "ialab" ? raw === null || isPlainRecord2(raw) : key === void 0 ? isStringMap2(raw) : typeof raw === "string";
|
|
7695
|
+
if (!ok) throw new InvalidBoardSetError(field, "valor com tipo errado");
|
|
7696
|
+
}
|
|
7697
|
+
function applyBoardSet(draft, op) {
|
|
7698
|
+
assertBoardSet(op);
|
|
7699
|
+
const { field, key, value } = op;
|
|
7700
|
+
if (field === "title") {
|
|
7701
|
+
if (value.kind === "value" && typeof value.value === "string") draft.setTitle(value.value);
|
|
7702
|
+
return;
|
|
7703
|
+
}
|
|
7704
|
+
draft.mutateMeta((meta) => {
|
|
7705
|
+
if (field === "assetUrls" && key !== void 0) return withAssetUrl(meta, key, value);
|
|
7706
|
+
return withField(meta, field, value);
|
|
7707
|
+
});
|
|
7708
|
+
}
|
|
7709
|
+
function withField(meta, field, value) {
|
|
7710
|
+
if (value.kind === "unset") {
|
|
7711
|
+
if (!Object.hasOwn(meta, field)) return meta;
|
|
7712
|
+
const next2 = { ...meta };
|
|
7713
|
+
delete next2[field];
|
|
7714
|
+
return next2;
|
|
7715
|
+
}
|
|
7716
|
+
const current = Object.hasOwn(meta, field) ? meta[field] : void 0;
|
|
7717
|
+
if (current === value.value && (value.value === null || typeof value.value === "string")) {
|
|
7718
|
+
return meta;
|
|
7719
|
+
}
|
|
7720
|
+
const next = { ...meta };
|
|
7721
|
+
writeKey(next, field, value.value);
|
|
7722
|
+
return next;
|
|
7723
|
+
}
|
|
7724
|
+
function withAssetUrl(meta, key, value) {
|
|
7725
|
+
const urls = meta.assetUrls;
|
|
7726
|
+
if (value.kind === "unset") {
|
|
7727
|
+
if (urls === void 0 || !Object.hasOwn(urls, key)) return meta;
|
|
7728
|
+
const nextUrls2 = { ...urls };
|
|
7729
|
+
delete nextUrls2[key];
|
|
7730
|
+
return { ...meta, assetUrls: nextUrls2 };
|
|
7731
|
+
}
|
|
7732
|
+
const url = value.value;
|
|
7733
|
+
if (urls !== void 0 && Object.hasOwn(urls, key) && urls[key] === url) return meta;
|
|
7734
|
+
const nextUrls = { ...urls };
|
|
7735
|
+
writeKey(nextUrls, key, url);
|
|
7736
|
+
return { ...meta, assetUrls: nextUrls };
|
|
7737
|
+
}
|
|
7738
|
+
function invertBoardSet(doc, op) {
|
|
7739
|
+
const { field, key } = op;
|
|
7740
|
+
if (field === "title") return { type: "board.set", field, value: propValue(doc.title) };
|
|
7741
|
+
const meta = doc.meta ?? {};
|
|
7742
|
+
if (field === "assetUrls" && key !== void 0) {
|
|
7743
|
+
const urls = meta.assetUrls;
|
|
7744
|
+
if (urls === void 0) return { type: "board.set", field, value: unsetPropValue() };
|
|
7745
|
+
return Object.hasOwn(urls, key) ? { type: "board.set", field, key, value: propValue(urls[key]) } : { type: "board.set", field, key, value: unsetPropValue() };
|
|
7746
|
+
}
|
|
7747
|
+
if (!Object.hasOwn(meta, field)) return { type: "board.set", field, value: unsetPropValue() };
|
|
7748
|
+
return { type: "board.set", field, value: propValue(meta[field]) };
|
|
7749
|
+
}
|
|
7750
|
+
function touchEdgeEnds(draft, source, target) {
|
|
7751
|
+
draft.touch(source);
|
|
7752
|
+
draft.touch(target);
|
|
7753
|
+
}
|
|
7754
|
+
var OPS2 = {
|
|
7755
|
+
"node.add": {
|
|
7756
|
+
apply(draft, op) {
|
|
7757
|
+
draft.putNode(op.nodeId, op.node);
|
|
7758
|
+
},
|
|
7759
|
+
invert: invertNodeAdd
|
|
7760
|
+
},
|
|
7761
|
+
"node.remove": {
|
|
7762
|
+
apply(draft, op) {
|
|
7763
|
+
draft.dropNode(op.nodeId);
|
|
7764
|
+
},
|
|
7765
|
+
invert: invertNodeRemove
|
|
7766
|
+
},
|
|
7767
|
+
"node.set": {
|
|
7768
|
+
apply(draft, op) {
|
|
7769
|
+
draft.mutateNode(
|
|
7770
|
+
op.nodeId,
|
|
7771
|
+
(node) => op.value.kind === "value" ? setPath(node, op.path, op.value.value) : unsetPath(node, op.path)
|
|
7772
|
+
);
|
|
7773
|
+
},
|
|
7774
|
+
invert: invertNodeSet
|
|
7775
|
+
},
|
|
7776
|
+
"edge.add": {
|
|
7777
|
+
apply(draft, op) {
|
|
7778
|
+
draft.putEdge(op.edgeId, op.edge);
|
|
7779
|
+
touchEdgeEnds(draft, op.edge.source, op.edge.target);
|
|
7780
|
+
},
|
|
7781
|
+
invert: invertEdgeAdd
|
|
7782
|
+
},
|
|
7783
|
+
"edge.remove": {
|
|
7784
|
+
apply(draft, op) {
|
|
7785
|
+
const current = draft.edge(op.edgeId);
|
|
7786
|
+
if (current === void 0) return;
|
|
7787
|
+
draft.dropEdge(op.edgeId);
|
|
7788
|
+
touchEdgeEnds(draft, current.source, current.target);
|
|
7789
|
+
},
|
|
7790
|
+
invert: invertEdgeRemove
|
|
7791
|
+
},
|
|
7792
|
+
"result.set": {
|
|
7793
|
+
apply(draft, op) {
|
|
7794
|
+
draft.putResult(op.resultId, op.entry);
|
|
7795
|
+
draft.touch(op.entry.nodeId);
|
|
7796
|
+
},
|
|
7797
|
+
invert: invertResultSet
|
|
7798
|
+
},
|
|
7799
|
+
"history.append": {
|
|
7800
|
+
apply(draft, op) {
|
|
7801
|
+
draft.appendHistory(op.nodeId, op.resultId);
|
|
7802
|
+
},
|
|
7803
|
+
invert: (_doc, op) => invertHistoryAppend(op)
|
|
7804
|
+
},
|
|
7805
|
+
"history.remove": {
|
|
7806
|
+
apply(draft, op) {
|
|
7807
|
+
draft.removeHistory(op.nodeId, op.resultId);
|
|
7808
|
+
},
|
|
7809
|
+
invert: invertHistoryRemove
|
|
7810
|
+
},
|
|
7811
|
+
"board.set": {
|
|
7812
|
+
apply: applyBoardSet,
|
|
7813
|
+
invert: invertBoardSet
|
|
7814
|
+
},
|
|
7815
|
+
batch: {
|
|
7816
|
+
apply(draft, op) {
|
|
7817
|
+
for (const inner of op.ops) applyOp(draft, inner);
|
|
7818
|
+
},
|
|
7819
|
+
/**
|
|
7820
|
+
* As inversas dos membros, em ordem reversa.
|
|
7821
|
+
*
|
|
7822
|
+
* O estado avança membro a membro, e não dá para fugir disso: inverter dois
|
|
7823
|
+
* `history.remove` seguidos contra o MESMO documento de entrada devolveria
|
|
7824
|
+
* dois `history.append` iguais, e a lista voltaria com um item a mais do que
|
|
7825
|
+
* tinha. Quem avança é `walkBatch`, com um rascunho de rascunho que nunca
|
|
7826
|
+
* toca o documento de quem chamou.
|
|
7827
|
+
*/
|
|
7828
|
+
invert(doc, op) {
|
|
7829
|
+
const parts = walkBatch(doc, op.ops, invert);
|
|
7830
|
+
return { type: "batch", ops: parts.reverse() };
|
|
7831
|
+
}
|
|
7832
|
+
}
|
|
7833
|
+
};
|
|
7834
|
+
function applyOp(draft, op) {
|
|
7835
|
+
const handler = OPS2[op.type];
|
|
7836
|
+
handler.apply(draft, op);
|
|
7837
|
+
}
|
|
7838
|
+
function invert(doc, op) {
|
|
7839
|
+
const handler = OPS2[op.type];
|
|
7840
|
+
return handler.invert(doc, op);
|
|
7841
|
+
}
|
|
7842
|
+
function walkBatch(doc, ops, visit) {
|
|
7843
|
+
const scratch = new Draft(doc);
|
|
7844
|
+
const collected = [];
|
|
7845
|
+
for (const op of ops) {
|
|
7846
|
+
const item = visit(scratch.finish().doc, op);
|
|
7847
|
+
if (item !== null) collected.push(item);
|
|
7848
|
+
applyOp(scratch, op);
|
|
7849
|
+
}
|
|
7850
|
+
return collected;
|
|
7851
|
+
}
|
|
7852
|
+
var MAX_OP_BYTES2 = 64 * 1024;
|
|
7853
|
+
var OpTooLargeError2 = class extends Error {
|
|
7854
|
+
/** O envelope recusado, para o `onError` da story 005 citar na mensagem. */
|
|
7855
|
+
opId;
|
|
7856
|
+
/** Quanto ele pesa, serializado em UTF-8. */
|
|
7857
|
+
bytes;
|
|
7858
|
+
/** Quanto cabia. */
|
|
7859
|
+
limit;
|
|
7860
|
+
constructor(opId, bytes, limit = MAX_OP_BYTES2) {
|
|
7861
|
+
super(`Opera\xE7\xE3o ${opId} tem ${bytes} bytes e o teto \xE9 ${limit}`);
|
|
7862
|
+
this.name = "OpTooLargeError";
|
|
7863
|
+
this.opId = opId;
|
|
7864
|
+
this.bytes = bytes;
|
|
7865
|
+
this.limit = limit;
|
|
7866
|
+
}
|
|
7867
|
+
};
|
|
7868
|
+
function utf8ByteLength(text) {
|
|
7869
|
+
let bytes = 0;
|
|
7870
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
7871
|
+
const code = text.charCodeAt(i);
|
|
7872
|
+
if (code < 128) {
|
|
7873
|
+
bytes += 1;
|
|
7874
|
+
} else if (code < 2048) {
|
|
7875
|
+
bytes += 2;
|
|
7876
|
+
} else if (code >= 55296 && code <= 56319 && i + 1 < text.length) {
|
|
7877
|
+
const next = text.charCodeAt(i + 1);
|
|
7878
|
+
if (next >= 56320 && next <= 57343) {
|
|
7879
|
+
bytes += 4;
|
|
7880
|
+
i += 1;
|
|
7881
|
+
} else {
|
|
7882
|
+
bytes += 3;
|
|
7883
|
+
}
|
|
7884
|
+
} else {
|
|
7885
|
+
bytes += 3;
|
|
7886
|
+
}
|
|
7887
|
+
}
|
|
7888
|
+
return bytes;
|
|
7889
|
+
}
|
|
7890
|
+
function opEnvelopeBytes(envelope2) {
|
|
7891
|
+
return utf8ByteLength(JSON.stringify(envelope2));
|
|
7892
|
+
}
|
|
7893
|
+
function assertOpEnvelopeFits(envelope2, limit = MAX_OP_BYTES2) {
|
|
7894
|
+
const bytes = opEnvelopeBytes(envelope2);
|
|
7895
|
+
if (bytes > limit) throw new OpTooLargeError2(envelope2.id, bytes, limit);
|
|
7896
|
+
}
|
|
7897
|
+
function applyOps(doc, ops, options = {}) {
|
|
7898
|
+
const draft = new Draft(doc, options.counts);
|
|
7899
|
+
for (const op of ops) applyOp(draft, op);
|
|
7900
|
+
return draft.finish();
|
|
7901
|
+
}
|
|
7902
|
+
function applyEnvelopes(doc, envelopes, options = {}) {
|
|
7903
|
+
for (const envelope2 of envelopes) assertOpEnvelopeFits(envelope2);
|
|
7904
|
+
return applyOps(
|
|
7905
|
+
doc,
|
|
7906
|
+
envelopes.map((envelope2) => envelope2.op),
|
|
7907
|
+
options
|
|
7908
|
+
);
|
|
7909
|
+
}
|
|
7910
|
+
function reduce(log, base) {
|
|
7911
|
+
const doc = base ?? emptyBoardFor(log);
|
|
7912
|
+
if (log.length === 0) return doc;
|
|
7913
|
+
let lastSeq = base === void 0 ? -1 : base.version;
|
|
7914
|
+
for (const envelope2 of log) {
|
|
7915
|
+
if (envelope2.seq === null) {
|
|
7916
|
+
throw new Error(
|
|
7917
|
+
`reduce recebeu o envelope ${envelope2.id} sem seq: s\xF3 entra no log o que j\xE1 foi confirmado`
|
|
7918
|
+
);
|
|
7919
|
+
}
|
|
7920
|
+
if (envelope2.seq <= lastSeq) {
|
|
7921
|
+
throw new Error(
|
|
7922
|
+
`reduce recebeu o log fora de ordem: seq ${envelope2.seq} depois de ${lastSeq}`
|
|
7923
|
+
);
|
|
7924
|
+
}
|
|
7925
|
+
lastSeq = envelope2.seq;
|
|
7926
|
+
}
|
|
7927
|
+
const applied = applyOps(
|
|
7928
|
+
doc,
|
|
7929
|
+
log.map((envelope2) => envelope2.op)
|
|
7930
|
+
);
|
|
7931
|
+
return { ...applied.doc, version: lastSeq };
|
|
7932
|
+
}
|
|
7933
|
+
function emptyBoardFor(log) {
|
|
7934
|
+
const first = log[0];
|
|
7935
|
+
if (first === void 0) {
|
|
7936
|
+
throw new Error("reduce sem base precisa de um log com ao menos um envelope");
|
|
7937
|
+
}
|
|
7938
|
+
return createEmptyBoard({ id: first.boardId, now: () => first.ts });
|
|
7939
|
+
}
|
|
7940
|
+
function removeNode(doc, nodeId3) {
|
|
7941
|
+
const ops = [];
|
|
7942
|
+
const edgeIds = Object.keys(doc.edges).filter((edgeId) => {
|
|
7943
|
+
const edge = doc.edges[edgeId];
|
|
7944
|
+
return edge !== void 0 && (edge.source === nodeId3 || edge.target === nodeId3);
|
|
7945
|
+
}).sort();
|
|
7946
|
+
for (const edgeId of edgeIds) ops.push({ type: "edge.remove", edgeId });
|
|
7947
|
+
const history = Object.hasOwn(doc.nodeHistory, nodeId3) ? doc.nodeHistory[nodeId3] : void 0;
|
|
7948
|
+
if (history !== void 0) {
|
|
7949
|
+
for (const resultId of [...history].reverse()) {
|
|
7950
|
+
ops.push({ type: "history.remove", nodeId: nodeId3, resultId });
|
|
7951
|
+
}
|
|
7952
|
+
}
|
|
7953
|
+
ops.push({ type: "node.remove", nodeId: nodeId3 });
|
|
7954
|
+
return { type: "batch", ops };
|
|
7955
|
+
}
|
|
7956
|
+
function batchOf2(ops) {
|
|
7957
|
+
const [first, ...rest] = ops;
|
|
7958
|
+
if (first !== void 0 && rest.length === 0) return first;
|
|
7959
|
+
return { type: "batch", ops: [...ops] };
|
|
7960
|
+
}
|
|
7961
|
+
function createOpIdGenerator(random = Math.random) {
|
|
7962
|
+
return () => {
|
|
7963
|
+
let out = "";
|
|
7964
|
+
for (let i = 0; i < 36; i += 1) {
|
|
7965
|
+
if (i === 8 || i === 13 || i === 18 || i === 23) {
|
|
7966
|
+
out += "-";
|
|
7967
|
+
continue;
|
|
7968
|
+
}
|
|
7969
|
+
if (i === 14) {
|
|
7970
|
+
out += "4";
|
|
7971
|
+
continue;
|
|
7972
|
+
}
|
|
7973
|
+
const value = Math.floor(random() * 16) & 15;
|
|
7974
|
+
out += (i === 19 ? value & 3 | 8 : value).toString(16);
|
|
7975
|
+
}
|
|
7976
|
+
return out;
|
|
7977
|
+
};
|
|
7978
|
+
}
|
|
7979
|
+
var newOpId = createOpIdGenerator();
|
|
7980
|
+
function touchedPaths(op, out = []) {
|
|
7981
|
+
switch (op.type) {
|
|
7982
|
+
case "node.add":
|
|
7983
|
+
case "node.remove":
|
|
7984
|
+
out.push(["node", op.nodeId]);
|
|
7985
|
+
break;
|
|
7986
|
+
case "node.set":
|
|
7987
|
+
out.push(["node", op.nodeId, ...segmentsOf(op.path)]);
|
|
7988
|
+
break;
|
|
7989
|
+
case "edge.add":
|
|
7990
|
+
case "edge.remove":
|
|
7991
|
+
out.push(["edge", op.edgeId]);
|
|
7992
|
+
break;
|
|
7993
|
+
case "result.set":
|
|
7994
|
+
out.push(["result", op.resultId]);
|
|
7995
|
+
break;
|
|
7996
|
+
case "history.append":
|
|
7997
|
+
case "history.remove":
|
|
7998
|
+
out.push(["history", op.nodeId]);
|
|
7999
|
+
break;
|
|
8000
|
+
case "board.set":
|
|
8001
|
+
out.push(op.key === void 0 ? ["board", op.field] : ["board", op.field, op.key]);
|
|
8002
|
+
break;
|
|
8003
|
+
case "batch":
|
|
8004
|
+
for (const inner of op.ops) touchedPaths(inner, out);
|
|
8005
|
+
break;
|
|
8006
|
+
}
|
|
8007
|
+
return out;
|
|
8008
|
+
}
|
|
8009
|
+
function segmentsOf(path) {
|
|
8010
|
+
try {
|
|
8011
|
+
return parsePath(path);
|
|
8012
|
+
} catch {
|
|
8013
|
+
return [];
|
|
8014
|
+
}
|
|
8015
|
+
}
|
|
8016
|
+
function pathsCross(a, b) {
|
|
8017
|
+
const length = Math.min(a.length, b.length);
|
|
8018
|
+
for (let i = 0; i < length; i += 1) if (a[i] !== b[i]) return false;
|
|
8019
|
+
return true;
|
|
8020
|
+
}
|
|
8021
|
+
function anyPathCrosses(a, b) {
|
|
8022
|
+
for (const left of a) for (const right of b) if (pathsCross(left, right)) return true;
|
|
8023
|
+
return false;
|
|
8024
|
+
}
|
|
8025
|
+
var HISTORY_LIMIT = 100;
|
|
8026
|
+
var HISTORY_MAX_BYTES = 8 * 1024 * 1024;
|
|
8027
|
+
var OBJECT_OVERHEAD = 16;
|
|
8028
|
+
var KEY_OVERHEAD = 8;
|
|
8029
|
+
var NUMBER_BYTES = 8;
|
|
8030
|
+
var SMALL_BYTES = 4;
|
|
8031
|
+
function estimateOpBytes(op) {
|
|
8032
|
+
let total = 0;
|
|
8033
|
+
const pending = [op];
|
|
8034
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8035
|
+
while (pending.length > 0) {
|
|
8036
|
+
const value = pending.pop();
|
|
8037
|
+
if (typeof value === "string") {
|
|
8038
|
+
total += KEY_OVERHEAD + value.length * 2;
|
|
8039
|
+
} else if (typeof value === "number") {
|
|
8040
|
+
total += NUMBER_BYTES;
|
|
8041
|
+
} else if (Array.isArray(value)) {
|
|
8042
|
+
if (seen.has(value)) continue;
|
|
8043
|
+
seen.add(value);
|
|
8044
|
+
total += OBJECT_OVERHEAD;
|
|
8045
|
+
for (const item of value) pending.push(item);
|
|
8046
|
+
} else if (typeof value === "object" && value !== null) {
|
|
8047
|
+
if (seen.has(value)) continue;
|
|
8048
|
+
seen.add(value);
|
|
8049
|
+
total += OBJECT_OVERHEAD;
|
|
8050
|
+
for (const [key, item] of Object.entries(value)) {
|
|
8051
|
+
total += KEY_OVERHEAD + key.length * 2;
|
|
8052
|
+
pending.push(item);
|
|
8053
|
+
}
|
|
8054
|
+
} else {
|
|
8055
|
+
total += SMALL_BYTES;
|
|
8056
|
+
}
|
|
8057
|
+
}
|
|
8058
|
+
return total;
|
|
8059
|
+
}
|
|
8060
|
+
var HistoryStack = class {
|
|
8061
|
+
entries = [];
|
|
8062
|
+
redoEntries = [];
|
|
8063
|
+
limit;
|
|
8064
|
+
maxBytes;
|
|
8065
|
+
clock;
|
|
8066
|
+
onHistoryTrimmed;
|
|
8067
|
+
/** Soma de `bytes` das entradas de desfazer, mantida incrementalmente. */
|
|
8068
|
+
totalBytes = 0;
|
|
8069
|
+
/** Grupo aberto por `startCapture`, ou nulo quando nenhum gesto está aberto. */
|
|
8070
|
+
openGroupId = null;
|
|
8071
|
+
/** Contador de grupos. O id é local à pilha, então não precisa de fonte injetada. */
|
|
8072
|
+
groupSeq = 0;
|
|
8073
|
+
constructor(options = {}) {
|
|
8074
|
+
this.limit = options.limit ?? HISTORY_LIMIT;
|
|
8075
|
+
this.maxBytes = options.maxBytes ?? HISTORY_MAX_BYTES;
|
|
8076
|
+
this.clock = options.clock ?? Date.now;
|
|
8077
|
+
this.onHistoryTrimmed = options.onHistoryTrimmed;
|
|
8078
|
+
}
|
|
8079
|
+
// ------------------------------------------------------------------ leitura
|
|
8080
|
+
get canUndo() {
|
|
8081
|
+
return this.entries.length > 0;
|
|
8082
|
+
}
|
|
8083
|
+
get canRedo() {
|
|
8084
|
+
return this.redoEntries.length > 0;
|
|
8085
|
+
}
|
|
8086
|
+
/** Quantas entradas dá para desfazer. É o que o painel da story 007 mostra. */
|
|
8087
|
+
get size() {
|
|
8088
|
+
return this.entries.length;
|
|
8089
|
+
}
|
|
8090
|
+
/** Quantas entradas dá para refazer. */
|
|
8091
|
+
get redoSize() {
|
|
8092
|
+
return this.redoEntries.length;
|
|
8093
|
+
}
|
|
8094
|
+
/** Memória somada das entradas de desfazer, estimada. */
|
|
8095
|
+
get bytes() {
|
|
8096
|
+
return this.totalBytes;
|
|
8097
|
+
}
|
|
8098
|
+
/** Tem gesto aberto? */
|
|
8099
|
+
get capturing() {
|
|
8100
|
+
return this.openGroupId !== null;
|
|
8101
|
+
}
|
|
8102
|
+
/** A entrada mais recente, sem tirá-la da pilha. Leitura, não consumo. */
|
|
8103
|
+
peek() {
|
|
8104
|
+
return this.entries[this.entries.length - 1];
|
|
8105
|
+
}
|
|
8106
|
+
// ------------------------------------------------------------------ captura
|
|
8107
|
+
/**
|
|
8108
|
+
* Abre um gesto: tudo que for capturado até `endCapture` vira uma entrada só.
|
|
8109
|
+
*
|
|
8110
|
+
* Chamada com um gesto já aberto, devolve o grupo aberto em vez de abrir
|
|
8111
|
+
* outro. Gesto dentro de gesto não existe na tela, e contar profundidade
|
|
8112
|
+
* pediria um `endCapture` por chamada, que é um jeito novo de esquecer de
|
|
8113
|
+
* fechar.
|
|
8114
|
+
*/
|
|
8115
|
+
startCapture() {
|
|
8116
|
+
if (this.openGroupId === null) {
|
|
8117
|
+
this.groupSeq += 1;
|
|
8118
|
+
this.openGroupId = `gesture-${this.groupSeq}`;
|
|
8119
|
+
}
|
|
8120
|
+
return this.openGroupId;
|
|
8121
|
+
}
|
|
8122
|
+
/** Fecha o gesto. A próxima captura abre entrada nova. */
|
|
8123
|
+
endCapture() {
|
|
8124
|
+
this.openGroupId = null;
|
|
8125
|
+
}
|
|
8126
|
+
/**
|
|
8127
|
+
* Guarda uma operação e a inversa dela.
|
|
8128
|
+
*
|
|
8129
|
+
* A inversa entra na FRENTE da lista da entrada: desfazer aplica `inverse` na
|
|
8130
|
+
* ordem do array, e a última coisa que aconteceu é a primeira a ser desfeita.
|
|
8131
|
+
*/
|
|
8132
|
+
capture(op, inverse, options = {}) {
|
|
8133
|
+
this.redoEntries.length = 0;
|
|
8134
|
+
const groupId = options.groupId ?? this.openGroupId;
|
|
8135
|
+
const bytes = estimateOpBytes(op) + estimateOpBytes(inverse);
|
|
8136
|
+
const last = this.peek();
|
|
8137
|
+
if (last !== void 0 && (options.amendLast === true || groupId !== null && last.groupId === groupId)) {
|
|
8138
|
+
last.ops.push(op);
|
|
8139
|
+
last.inverse.unshift(inverse);
|
|
8140
|
+
touchedPaths(op, last.paths);
|
|
8141
|
+
last.bytes += bytes;
|
|
8142
|
+
last.ts = this.clock();
|
|
8143
|
+
this.totalBytes += bytes;
|
|
8144
|
+
this.trim();
|
|
8145
|
+
return last;
|
|
8146
|
+
}
|
|
8147
|
+
const entry = {
|
|
8148
|
+
ops: [op],
|
|
8149
|
+
inverse: [inverse],
|
|
8150
|
+
groupId,
|
|
8151
|
+
ts: this.clock(),
|
|
8152
|
+
bytes,
|
|
8153
|
+
paths: touchedPaths(op),
|
|
8154
|
+
stale: false
|
|
8155
|
+
};
|
|
8156
|
+
this.entries.push(entry);
|
|
8157
|
+
this.totalBytes += bytes;
|
|
8158
|
+
this.trim();
|
|
8159
|
+
return entry;
|
|
8160
|
+
}
|
|
8161
|
+
// ------------------------------------------------------- desfazer e refazer
|
|
8162
|
+
/**
|
|
8163
|
+
* Tira a entrada mais recente e a passa para o refazer.
|
|
8164
|
+
*
|
|
8165
|
+
* A pilha não aplica nada: quem aplica é o store, com a inversa recarimbada.
|
|
8166
|
+
* Devolver a entrada em vez de aplicá-la é o que mantém o núcleo do histórico
|
|
8167
|
+
* sem opinião sobre transporte, relógio e id.
|
|
8168
|
+
*/
|
|
8169
|
+
undo() {
|
|
8170
|
+
const entry = this.entries.pop();
|
|
8171
|
+
if (entry === void 0) return void 0;
|
|
8172
|
+
this.totalBytes -= entry.bytes;
|
|
8173
|
+
if (!entry.stale) this.redoEntries.push(entry);
|
|
8174
|
+
return entry;
|
|
8175
|
+
}
|
|
8176
|
+
/**
|
|
8177
|
+
* Devolve à pilha de desfazer a entrada que `undo` acabou de tirar, quando a
|
|
8178
|
+
* inversa dela não pôde ser aplicada (recusada pelo teto de tamanho). Sem
|
|
8179
|
+
* isto, um desfazer recusado perderia o passo.
|
|
8180
|
+
*/
|
|
8181
|
+
revertUndo(entry) {
|
|
8182
|
+
if (this.redoEntries[this.redoEntries.length - 1] === entry) this.redoEntries.pop();
|
|
8183
|
+
this.entries.push(entry);
|
|
8184
|
+
this.totalBytes += entry.bytes;
|
|
8185
|
+
}
|
|
8186
|
+
/** O par de `revertUndo` para o refazer. */
|
|
8187
|
+
revertRedo(entry) {
|
|
8188
|
+
if (this.entries[this.entries.length - 1] === entry) {
|
|
8189
|
+
this.entries.pop();
|
|
8190
|
+
this.totalBytes -= entry.bytes;
|
|
8191
|
+
}
|
|
8192
|
+
this.redoEntries.push(entry);
|
|
8193
|
+
}
|
|
8194
|
+
/**
|
|
8195
|
+
* Outra pessoa tocou estes caminhos: as entradas que cruzam com eles, nas duas
|
|
8196
|
+
* pilhas, ficam marcadas como velhas. Não apaga nada aqui: quem descarta, e
|
|
8197
|
+
* avisa, é o desfazer, no momento em que a pessoa pede.
|
|
8198
|
+
*/
|
|
8199
|
+
invalidate(paths) {
|
|
8200
|
+
if (paths.length === 0) return 0;
|
|
8201
|
+
let marked = 0;
|
|
8202
|
+
for (const entry of [...this.entries, ...this.redoEntries]) {
|
|
8203
|
+
if (entry.stale || !anyPathCrosses(entry.paths, paths)) continue;
|
|
8204
|
+
entry.stale = true;
|
|
8205
|
+
marked += 1;
|
|
8206
|
+
}
|
|
8207
|
+
return marked;
|
|
8208
|
+
}
|
|
8209
|
+
/**
|
|
8210
|
+
* Tira a entrada mais recente do refazer e a devolve para o desfazer.
|
|
8211
|
+
*
|
|
8212
|
+
* Não precisa de poda: o que volta já esteve na pilha dentro do teto, e
|
|
8213
|
+
* qualquer captura no meio do caminho teria zerado o refazer.
|
|
8214
|
+
*/
|
|
8215
|
+
redo() {
|
|
8216
|
+
const entry = this.redoEntries.pop();
|
|
8217
|
+
if (entry === void 0) return void 0;
|
|
8218
|
+
if (entry.stale) return entry;
|
|
8219
|
+
this.entries.push(entry);
|
|
8220
|
+
this.totalBytes += entry.bytes;
|
|
8221
|
+
return entry;
|
|
8222
|
+
}
|
|
8223
|
+
/** Esvazia as duas pilhas. O documento não muda; a memória, sim. */
|
|
8224
|
+
clear() {
|
|
8225
|
+
this.entries.length = 0;
|
|
8226
|
+
this.redoEntries.length = 0;
|
|
8227
|
+
this.totalBytes = 0;
|
|
8228
|
+
this.openGroupId = null;
|
|
8229
|
+
}
|
|
8230
|
+
// --------------------------------------------------------------------- teto
|
|
8231
|
+
/**
|
|
8232
|
+
* Aplica os dois tetos, o de contagem e o de memória.
|
|
8233
|
+
*
|
|
8234
|
+
* A entrada mais recente nunca é descartada pelo teto de memória, mesmo
|
|
8235
|
+
* sozinha acima dele: o documento já mudou, e descartá-la deixaria o Marco sem
|
|
8236
|
+
* como desfazer o que ele acabou de fazer. Quando é esse o caso, o total fica
|
|
8237
|
+
* acima do teto e nenhum aviso é forjado, porque nada foi descartado.
|
|
8238
|
+
*/
|
|
8239
|
+
trim() {
|
|
8240
|
+
const excess = this.entries.length - this.limit;
|
|
8241
|
+
if (excess > 0) {
|
|
8242
|
+
const dropped = this.entries.splice(0, excess);
|
|
8243
|
+
for (const entry of dropped) this.totalBytes -= entry.bytes;
|
|
8244
|
+
this.report("count", dropped);
|
|
8245
|
+
}
|
|
8246
|
+
let cut = 0;
|
|
8247
|
+
let running = this.totalBytes;
|
|
8248
|
+
for (const entry of this.entries) {
|
|
8249
|
+
if (running <= this.maxBytes || cut >= this.entries.length - 1) break;
|
|
8250
|
+
running -= entry.bytes;
|
|
8251
|
+
cut += 1;
|
|
8252
|
+
}
|
|
8253
|
+
if (cut > 0) {
|
|
8254
|
+
const dropped = this.entries.splice(0, cut);
|
|
8255
|
+
this.totalBytes = running;
|
|
8256
|
+
this.report("bytes", dropped);
|
|
8257
|
+
}
|
|
8258
|
+
}
|
|
8259
|
+
report(reason, dropped) {
|
|
8260
|
+
if (this.onHistoryTrimmed === void 0) return;
|
|
8261
|
+
this.onHistoryTrimmed({ reason, dropped, bytes: this.totalBytes });
|
|
8262
|
+
}
|
|
8263
|
+
};
|
|
8264
|
+
function isLocalEnvelope(envelope2, localActorId) {
|
|
8265
|
+
return envelope2.actorId === localActorId;
|
|
8266
|
+
}
|
|
8267
|
+
function captureOf(doc, op) {
|
|
8268
|
+
if (op.type === "batch") {
|
|
8269
|
+
const parts = walkBatch(doc, op.ops, captureOf);
|
|
8270
|
+
if (parts.length === 0) return null;
|
|
8271
|
+
return {
|
|
8272
|
+
op: { type: "batch", ops: parts.map((part) => part.op) },
|
|
8273
|
+
inverse: { type: "batch", ops: parts.map((part) => part.inverse).reverse() }
|
|
8274
|
+
};
|
|
8275
|
+
}
|
|
8276
|
+
const inverse = invert(doc, op);
|
|
8277
|
+
if (inverse === null) return null;
|
|
8278
|
+
return { op, inverse };
|
|
8279
|
+
}
|
|
8280
|
+
function trackCapture(doc, envelope2, localActorId) {
|
|
8281
|
+
if (!isLocalEnvelope(envelope2, localActorId)) return null;
|
|
8282
|
+
return captureOf(doc, envelope2.op);
|
|
8283
|
+
}
|
|
8284
|
+
var EMPTY_INTERACTION = Object.freeze({
|
|
8285
|
+
drag: null,
|
|
8286
|
+
resize: null,
|
|
8287
|
+
selection: Object.freeze([])
|
|
8288
|
+
});
|
|
8289
|
+
function sameNodeIds(a, b) {
|
|
8290
|
+
if (a.length !== b.length) return false;
|
|
8291
|
+
for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
|
|
8292
|
+
return true;
|
|
8293
|
+
}
|
|
8294
|
+
function sameBox(a, b) {
|
|
8295
|
+
if (a == null || b == null) return (a ?? null) === (b ?? null);
|
|
8296
|
+
return a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;
|
|
8297
|
+
}
|
|
8298
|
+
function isOpList(value) {
|
|
8299
|
+
return Array.isArray(value);
|
|
8300
|
+
}
|
|
8301
|
+
var BoardStore = class {
|
|
8302
|
+
current;
|
|
8303
|
+
interaction = EMPTY_INTERACTION;
|
|
8304
|
+
options;
|
|
8305
|
+
stack;
|
|
8306
|
+
clock;
|
|
8307
|
+
newId;
|
|
8308
|
+
listeners = /* @__PURE__ */ new Set();
|
|
8309
|
+
envelopeListeners = /* @__PURE__ */ new Set();
|
|
8310
|
+
last = null;
|
|
8311
|
+
lastFromSync = false;
|
|
8312
|
+
constructor(doc, options) {
|
|
8313
|
+
this.current = doc;
|
|
8314
|
+
this.options = options;
|
|
8315
|
+
this.clock = options.clock ?? Date.now;
|
|
8316
|
+
this.newId = options.newId ?? newOpId;
|
|
8317
|
+
this.stack = new HistoryStack({
|
|
8318
|
+
limit: options.history?.limit,
|
|
8319
|
+
maxBytes: options.history?.maxBytes,
|
|
8320
|
+
clock: this.clock,
|
|
8321
|
+
onHistoryTrimmed: options.onHistoryTrimmed
|
|
8322
|
+
});
|
|
8323
|
+
}
|
|
8324
|
+
// ------------------------------------------------------------------ leitura
|
|
8325
|
+
/**
|
|
8326
|
+
* O documento de agora. Estável por referência entre mudanças.
|
|
8327
|
+
*
|
|
8328
|
+
* Propriedade de seta, e não método, porque ela é passada direto para
|
|
8329
|
+
* `useSyncExternalStore`: assim não precisa de `bind`, e o React não reassina
|
|
8330
|
+
* a cada render por receber uma função nova. `subscribe` e `getInteraction`
|
|
8331
|
+
* seguem a mesma forma, e as três mudam juntas ou nenhuma: metade convertida
|
|
8332
|
+
* faz o React reassinar sem erro visível.
|
|
8333
|
+
*/
|
|
8334
|
+
getDoc = () => this.current;
|
|
8335
|
+
/** O estado efêmero de agora. Mesma regra de estabilidade do documento. */
|
|
8336
|
+
getInteraction = () => this.interaction;
|
|
8337
|
+
/** Assina mudanças. Devolve a função que cancela a assinatura. */
|
|
8338
|
+
subscribe = (listener) => {
|
|
8339
|
+
this.listeners.add(listener);
|
|
8340
|
+
return () => {
|
|
8341
|
+
this.listeners.delete(listener);
|
|
8342
|
+
};
|
|
8343
|
+
};
|
|
8344
|
+
/** A pilha, para quem mostra o estado dela na tela (story 007). */
|
|
8345
|
+
get history() {
|
|
8346
|
+
return this.stack;
|
|
8347
|
+
}
|
|
8348
|
+
get canUndo() {
|
|
8349
|
+
return this.stack.canUndo;
|
|
8350
|
+
}
|
|
8351
|
+
get canRedo() {
|
|
8352
|
+
return this.stack.canRedo;
|
|
8353
|
+
}
|
|
8354
|
+
/**
|
|
8355
|
+
* O último envelope aplicado, nosso ou de fora. É por ele que quem assina
|
|
8356
|
+
* sabe se a mudança que acabou de acordá-lo nasceu nesta aba (`clientId`
|
|
8357
|
+
* igual ao da sessão) e, portanto, se deve derivar operação a partir dela
|
|
8358
|
+
* (SV2b). Nulo antes do primeiro despacho.
|
|
8359
|
+
*/
|
|
8360
|
+
get lastEnvelope() {
|
|
8361
|
+
return this.last;
|
|
8362
|
+
}
|
|
8363
|
+
/**
|
|
8364
|
+
* A última troca do documento veio de `replaceDoc` (a sincronização trocou a
|
|
8365
|
+
* foto: remotas mais as pendentes reaplicadas), e não de um despacho. Para
|
|
8366
|
+
* quem deriva operação, isso conta como mudança de fora: as pendentes desta
|
|
8367
|
+
* aba já derivaram quando foram despachadas pela primeira vez.
|
|
8368
|
+
*/
|
|
8369
|
+
get lastChangeFromSync() {
|
|
8370
|
+
return this.lastFromSync;
|
|
8371
|
+
}
|
|
8372
|
+
// ------------------------------------------------------------------ gestos
|
|
8373
|
+
/** Abre um gesto: o que for despachado até `endCapture` vira uma entrada só. */
|
|
8374
|
+
startCapture() {
|
|
8375
|
+
return this.stack.startCapture();
|
|
8376
|
+
}
|
|
8377
|
+
/** Fecha o gesto. */
|
|
8378
|
+
endCapture() {
|
|
8379
|
+
this.stack.endCapture();
|
|
8380
|
+
}
|
|
8381
|
+
// ---------------------------------------------------------------- interação
|
|
8382
|
+
/**
|
|
8383
|
+
* Troca a seleção. Não é documento, não é op, não entra na pilha.
|
|
8384
|
+
*
|
|
8385
|
+
* Seleção igual sai de graça: sem troca de referência ninguém é acordado.
|
|
8386
|
+
*/
|
|
8387
|
+
select(nodeIds) {
|
|
8388
|
+
if (sameNodeIds(this.interaction.selection, nodeIds)) return;
|
|
8389
|
+
this.interaction = { ...this.interaction, selection: [...nodeIds] };
|
|
8390
|
+
this.notify();
|
|
8391
|
+
}
|
|
8392
|
+
/**
|
|
8393
|
+
* Abre um gesto de arraste, capturando a posição de partida de cada nó.
|
|
8394
|
+
*
|
|
8395
|
+
* Id que não existe no documento é ignorado, e um gesto sem nenhum nó válido
|
|
8396
|
+
* não abre nem notifica. Gesto já aberto também não reabre: o primeiro frame
|
|
8397
|
+
* é quem define a base da op do soltar, e recapturar a base no meio do
|
|
8398
|
+
* caminho mediria o gesto pela metade.
|
|
8399
|
+
*/
|
|
8400
|
+
beginDrag(nodeIds) {
|
|
8401
|
+
if (this.interaction.drag !== null) return;
|
|
8402
|
+
const origin = {};
|
|
8403
|
+
const ids = [];
|
|
8404
|
+
for (const id of nodeIds) {
|
|
8405
|
+
const node = this.current.nodes[id];
|
|
8406
|
+
if (node === void 0) continue;
|
|
8407
|
+
origin[id] = { x: node.position.x, y: node.position.y };
|
|
8408
|
+
ids.push(id);
|
|
8409
|
+
}
|
|
8410
|
+
if (ids.length === 0) return;
|
|
8411
|
+
this.interaction = { ...this.interaction, drag: { nodeIds: ids, origin, live: origin } };
|
|
8412
|
+
this.notify();
|
|
8413
|
+
}
|
|
8414
|
+
/**
|
|
8415
|
+
* Move o gesto vivo. Sem op, sem histórico, sem tocar no documento.
|
|
8416
|
+
*
|
|
8417
|
+
* Posição repetida sai de graça, e é isso que impede um `pointermove` que não
|
|
8418
|
+
* andou de custar um render. Id fora do gesto é ignorado.
|
|
8419
|
+
*/
|
|
8420
|
+
moveDrag(positions) {
|
|
8421
|
+
const drag = this.interaction.drag;
|
|
8422
|
+
if (drag === null) return;
|
|
8423
|
+
let changed = false;
|
|
8424
|
+
const live = { ...drag.live };
|
|
8425
|
+
for (const id of drag.nodeIds) {
|
|
8426
|
+
const next = positions[id];
|
|
8427
|
+
if (next === void 0) continue;
|
|
8428
|
+
const current = live[id];
|
|
8429
|
+
if (current !== void 0 && current.x === next.x && current.y === next.y) continue;
|
|
8430
|
+
live[id] = { x: next.x, y: next.y };
|
|
8431
|
+
changed = true;
|
|
8432
|
+
}
|
|
8433
|
+
if (!changed) return;
|
|
8434
|
+
this.interaction = { ...this.interaction, drag: { ...drag, live } };
|
|
8435
|
+
this.notify();
|
|
8436
|
+
}
|
|
8437
|
+
/**
|
|
8438
|
+
* Fecha o gesto: uma op de topo, uma entrada de histórico, uma notificação.
|
|
8439
|
+
*
|
|
8440
|
+
* **A troca é atômica.** A camada efêmera é limpa ANTES de o despacho
|
|
8441
|
+
* notificar, então a única notificação que sai já carrega o documento com a
|
|
8442
|
+
* posição nova e o gesto encerrado. Nenhum assinante consegue observar o par
|
|
8443
|
+
* (posição velha, arraste já encerrado), que é o piscar de um frame que o
|
|
8444
|
+
* desenho de dois donos de estado produz.
|
|
8445
|
+
*
|
|
8446
|
+
* `positions` é a posição final vinda de quem viu o gesto acontecer (o
|
|
8447
|
+
* `change.position` da lib), e a camada efêmera entra só como reserva: uma
|
|
8448
|
+
* fonte de verdade por valor, com a segunda cobrindo o dia em que a primeira
|
|
8449
|
+
* faltar. Nó que voltou para onde começou não emite nada, e gesto em que
|
|
8450
|
+
* ninguém andou não emite op nenhuma.
|
|
8451
|
+
*/
|
|
8452
|
+
endDrag(positions = {}) {
|
|
8453
|
+
const drag = this.interaction.drag;
|
|
8454
|
+
if (drag === null) return null;
|
|
8455
|
+
const ops = [];
|
|
8456
|
+
for (const id of drag.nodeIds) {
|
|
8457
|
+
const from = drag.origin[id];
|
|
8458
|
+
const to = positions[id] ?? drag.live[id];
|
|
8459
|
+
if (from === void 0 || to === void 0) continue;
|
|
8460
|
+
if (from.x === to.x && from.y === to.y) continue;
|
|
8461
|
+
ops.push({
|
|
8462
|
+
type: "node.set",
|
|
8463
|
+
nodeId: id,
|
|
8464
|
+
path: "position",
|
|
8465
|
+
value: propValue({ x: to.x, y: to.y })
|
|
8466
|
+
});
|
|
8467
|
+
}
|
|
8468
|
+
if (ops.length === 0) {
|
|
8469
|
+
this.cancelDrag();
|
|
8470
|
+
return null;
|
|
8471
|
+
}
|
|
8472
|
+
this.interaction = { ...this.interaction, drag: null };
|
|
8473
|
+
const result = this.dispatch(ops, { silent: true });
|
|
8474
|
+
this.notify();
|
|
8475
|
+
return result;
|
|
8476
|
+
}
|
|
8477
|
+
/**
|
|
8478
|
+
* Saída do gesto interrompido: `Escape`, `pointercancel` e a aba perdendo o
|
|
8479
|
+
* foco. Zero op, zero entrada de histórico, e o nó volta para a posição do
|
|
8480
|
+
* documento porque é ela que sempre esteve lá.
|
|
8481
|
+
*/
|
|
8482
|
+
cancelDrag() {
|
|
8483
|
+
if (this.interaction.drag === null) return;
|
|
8484
|
+
this.interaction = { ...this.interaction, drag: null };
|
|
8485
|
+
this.notify();
|
|
8486
|
+
}
|
|
8487
|
+
/**
|
|
8488
|
+
* Abre um gesto de redimensionar (SV2b). Mesmo desenho do arraste: nada vira
|
|
8489
|
+
* operação até o soltar. Nó ausente não abre.
|
|
8490
|
+
*/
|
|
8491
|
+
beginResize(nodeId3) {
|
|
8492
|
+
const node = this.current.nodes[nodeId3];
|
|
8493
|
+
if (node === void 0) return;
|
|
8494
|
+
const origin = { ...node.position, ...node.size };
|
|
8495
|
+
this.interaction = { ...this.interaction, resize: { nodeId: nodeId3, origin, live: origin } };
|
|
8496
|
+
this.notify();
|
|
8497
|
+
}
|
|
8498
|
+
/** A caixa do frame atual. Sem op, sem histórico. Caixa igual sai de graça. */
|
|
8499
|
+
moveResize(box) {
|
|
8500
|
+
const resize = this.interaction.resize;
|
|
8501
|
+
if (resize == null || sameBox(resize.live, box)) return;
|
|
8502
|
+
const live = { x: box.x, y: box.y, w: box.w, h: box.h };
|
|
8503
|
+
this.interaction = { ...this.interaction, resize: { ...resize, live } };
|
|
8504
|
+
this.notify();
|
|
8505
|
+
}
|
|
8506
|
+
/**
|
|
8507
|
+
* Fecha o gesto: uma op, uma entrada de histórico, uma notificação. A troca
|
|
8508
|
+
* é atômica pela mesma razão de `endDrag`. Caixa final igual à de partida
|
|
8509
|
+
* não emite nada.
|
|
8510
|
+
*/
|
|
8511
|
+
endResize(box) {
|
|
8512
|
+
const resize = this.interaction.resize;
|
|
8513
|
+
if (resize == null) return null;
|
|
8514
|
+
const to = box ?? resize.live;
|
|
8515
|
+
const from = resize.origin;
|
|
8516
|
+
const ops = [];
|
|
8517
|
+
if (from.w !== to.w || from.h !== to.h) {
|
|
8518
|
+
ops.push({
|
|
8519
|
+
type: "node.set",
|
|
8520
|
+
nodeId: resize.nodeId,
|
|
8521
|
+
path: "size",
|
|
8522
|
+
value: propValue({ w: to.w, h: to.h })
|
|
8523
|
+
});
|
|
8524
|
+
}
|
|
8525
|
+
if (from.x !== to.x || from.y !== to.y) {
|
|
8526
|
+
ops.push({
|
|
8527
|
+
type: "node.set",
|
|
8528
|
+
nodeId: resize.nodeId,
|
|
8529
|
+
path: "position",
|
|
8530
|
+
value: propValue({ x: to.x, y: to.y })
|
|
8531
|
+
});
|
|
8532
|
+
}
|
|
8533
|
+
this.interaction = { ...this.interaction, resize: null };
|
|
8534
|
+
if (ops.length === 0 || this.current.nodes[resize.nodeId] === void 0) {
|
|
8535
|
+
this.notify();
|
|
8536
|
+
return null;
|
|
8537
|
+
}
|
|
8538
|
+
const result = this.dispatch(ops, { silent: true });
|
|
8539
|
+
this.notify();
|
|
8540
|
+
return result;
|
|
8541
|
+
}
|
|
8542
|
+
/** Gesto interrompido: zero op, e o nó volta ao tamanho do documento. */
|
|
8543
|
+
cancelResize() {
|
|
8544
|
+
if (this.interaction.resize == null) return;
|
|
8545
|
+
this.interaction = { ...this.interaction, resize: null };
|
|
8546
|
+
this.notify();
|
|
8547
|
+
}
|
|
8548
|
+
// ----------------------------------------------------------------- despacho
|
|
8549
|
+
/**
|
|
8550
|
+
* Despacha operação nossa: carimba o envelope com a sessão local e aplica.
|
|
8551
|
+
*
|
|
8552
|
+
* Lista com mais de uma operação vira um `batch`, porque um envelope carrega
|
|
8553
|
+
* UMA operação de topo, e um `batch` é uma operação, logo um `seq`
|
|
8554
|
+
* (`dev/PLANO-FASE-0.md` §3).
|
|
8555
|
+
*/
|
|
8556
|
+
dispatch(ops, options = {}) {
|
|
8557
|
+
const op = isOpList(ops) ? batchOf2(ops) : ops;
|
|
8558
|
+
return this.dispatchEnvelope(this.stamp(op), options);
|
|
8559
|
+
}
|
|
8560
|
+
/**
|
|
8561
|
+
* Despacha um envelope já carimbado.
|
|
8562
|
+
*
|
|
8563
|
+
* É a porta por onde entra o que NÃO nasceu nesta aba: o motor de execução da
|
|
8564
|
+
* fase 4 e, um dia, o `pull` da colaboração. O filtro de captura compara o
|
|
8565
|
+
* `actorId` do envelope com o da sessão, e é por isso que a regra do autor
|
|
8566
|
+
* mora no envelope em vez de virar um parâmetro do despacho.
|
|
8567
|
+
*/
|
|
8568
|
+
dispatchEnvelope(envelope2, options = {}) {
|
|
8569
|
+
const before = this.current;
|
|
8570
|
+
const ours = envelope2.clientId === this.options.session.clientId;
|
|
8571
|
+
const split = ours && options.unbounded !== true ? this.wireEnvelopes(envelope2) : [envelope2];
|
|
8572
|
+
const envelopes = split === null && this.envelopeListeners.size > 0 ? [envelope2] : split;
|
|
8573
|
+
if (envelopes === null) {
|
|
8574
|
+
const rejected = {
|
|
8575
|
+
code: "op-too-large",
|
|
8576
|
+
message: "Essa altera\xE7\xE3o \xE9 grande demais para ir de uma vez s\xF3 (mais de 64 KB numa opera\xE7\xE3o) e n\xE3o foi aplicada.",
|
|
8577
|
+
boardId: this.current.id,
|
|
8578
|
+
opId: envelope2.id
|
|
8579
|
+
};
|
|
8580
|
+
this.options.onError(rejected);
|
|
8581
|
+
return { envelope: envelope2, doc: before, changedNodeIds: [], entry: null, envelopes: [], rejected };
|
|
8582
|
+
}
|
|
8583
|
+
const capture = options.tracked === false ? null : trackCapture(before, envelope2, this.options.session.actorId);
|
|
8584
|
+
const applied = applyOps(before, [envelope2.op]);
|
|
8585
|
+
const entry = capture === null ? null : this.stack.capture(capture.op, capture.inverse, {
|
|
8586
|
+
groupId: options.groupId,
|
|
8587
|
+
amendLast: options.amendLast
|
|
8588
|
+
});
|
|
8589
|
+
if (envelope2.actorId !== null && envelope2.actorId !== this.options.session.actorId) {
|
|
8590
|
+
this.stack.invalidate(touchedPaths(envelope2.op));
|
|
8591
|
+
}
|
|
8592
|
+
this.current = applied.doc;
|
|
8593
|
+
this.last = envelope2;
|
|
8594
|
+
this.lastFromSync = false;
|
|
8595
|
+
for (const listener of this.envelopeListeners) for (const wire of envelopes) listener(wire);
|
|
8596
|
+
if (options.silent !== true && applied.doc !== before) this.notify();
|
|
8597
|
+
return {
|
|
8598
|
+
envelope: envelope2,
|
|
8599
|
+
doc: applied.doc,
|
|
8600
|
+
changedNodeIds: applied.changedNodeIds,
|
|
8601
|
+
entry,
|
|
8602
|
+
envelopes,
|
|
8603
|
+
rejected: null
|
|
8604
|
+
};
|
|
8605
|
+
}
|
|
8606
|
+
// ----------------------------------------------------------- sincronização
|
|
8607
|
+
/**
|
|
8608
|
+
* Assina os envelopes que ESTA aba aplicou pelo despacho (edição, desfazer,
|
|
8609
|
+
* refazer, soltar de arraste). É por aqui que o cliente de sincronização
|
|
8610
|
+
* (`transport/`) monta a fila de pendentes. Avisado só depois de o apply
|
|
8611
|
+
* passar: envelope que lançou nunca vira pendente.
|
|
8612
|
+
*
|
|
8613
|
+
* Sem assinante, o despacho se comporta exatamente como antes.
|
|
8614
|
+
*/
|
|
8615
|
+
subscribeEnvelopes = (listener) => {
|
|
8616
|
+
this.envelopeListeners.add(listener);
|
|
8617
|
+
return () => {
|
|
8618
|
+
this.envelopeListeners.delete(listener);
|
|
8619
|
+
};
|
|
8620
|
+
};
|
|
8621
|
+
/**
|
|
8622
|
+
* Troca o documento inteiro pelo que a sincronização calculou (foto confirmada
|
|
8623
|
+
* + remotas + pendentes reaplicadas). Não entra no histórico, não avisa
|
|
8624
|
+
* `subscribeEnvelopes` (senão o remoto voltaria como pendente) e só notifica
|
|
8625
|
+
* quando a referência muda.
|
|
8626
|
+
*/
|
|
8627
|
+
replaceDoc(doc) {
|
|
8628
|
+
if (doc === this.current) return;
|
|
8629
|
+
this.current = doc;
|
|
8630
|
+
this.lastFromSync = true;
|
|
8631
|
+
this.notify();
|
|
8632
|
+
}
|
|
8633
|
+
/**
|
|
8634
|
+
* O envelope como vai ao fio, em pedaços que cabem no teto.
|
|
8635
|
+
*
|
|
8636
|
+
* Cabe inteiro: sai como está, e é o caso de quase todo despacho. Não cabe e
|
|
8637
|
+
* é `batch`: os membros (com `batch` aninhado aberto, a ordem preservada) são
|
|
8638
|
+
* empacotados em envelopes consecutivos. Uma folha sozinha acima do teto não
|
|
8639
|
+
* tem como ir: devolve nulo, e o despacho é recusado inteiro.
|
|
8640
|
+
*/
|
|
8641
|
+
wireEnvelopes(envelope2) {
|
|
8642
|
+
if (opEnvelopeBytes(envelope2) <= MAX_OP_BYTES2) return [envelope2];
|
|
8643
|
+
if (envelope2.op.type !== "batch") return null;
|
|
8644
|
+
const leaves = [];
|
|
8645
|
+
const open3 = (op) => {
|
|
8646
|
+
if (op.type === "batch") for (const inner of op.ops) open3(inner);
|
|
8647
|
+
else leaves.push(op);
|
|
8648
|
+
};
|
|
8649
|
+
open3(envelope2.op);
|
|
8650
|
+
const slack = 64;
|
|
8651
|
+
const overhead = opEnvelopeBytes({ ...envelope2, op: { type: "batch", ops: [] } }) + slack;
|
|
8652
|
+
const chunks = [];
|
|
8653
|
+
let chunk = [];
|
|
8654
|
+
let bytes = overhead;
|
|
8655
|
+
for (const leaf of leaves) {
|
|
8656
|
+
const size = utf8ByteLength(JSON.stringify(leaf));
|
|
8657
|
+
if (overhead + size > MAX_OP_BYTES2) return null;
|
|
8658
|
+
const added = chunk.length === 0 ? size : size + 1;
|
|
8659
|
+
if (chunk.length > 0 && bytes + added > MAX_OP_BYTES2) {
|
|
8660
|
+
chunks.push(chunk);
|
|
8661
|
+
chunk = [leaf];
|
|
8662
|
+
bytes = overhead + size;
|
|
8663
|
+
} else {
|
|
8664
|
+
chunk.push(leaf);
|
|
8665
|
+
bytes += added;
|
|
8666
|
+
}
|
|
8667
|
+
}
|
|
8668
|
+
if (chunk.length > 0) chunks.push(chunk);
|
|
8669
|
+
return chunks.map((ops, index) => ({
|
|
8670
|
+
...envelope2,
|
|
8671
|
+
// O primeiro pedaço herda o id: é por ele que quem despachou reconhece o eco.
|
|
8672
|
+
id: index === 0 ? envelope2.id : this.newId(),
|
|
8673
|
+
op: ops.length === 1 ? ops[0] : { type: "batch", ops }
|
|
8674
|
+
}));
|
|
8675
|
+
}
|
|
8676
|
+
// -------------------------------------------------------- desfazer e refazer
|
|
8677
|
+
/**
|
|
8678
|
+
* Desfaz o último gesto.
|
|
8679
|
+
*
|
|
8680
|
+
* Cada inversa sai recarimbada com id novo e o `clientId` local, embrulhada em
|
|
8681
|
+
* `batch` quando a entrada juntou mais de um despacho, e despachada com
|
|
8682
|
+
* `{tracked:false}`. A entrada vai para a pilha de refazer inteira, do jeito
|
|
8683
|
+
* que estava.
|
|
8684
|
+
*/
|
|
8685
|
+
undo() {
|
|
8686
|
+
const entry = this.stack.undo();
|
|
8687
|
+
if (entry === void 0) return { applied: false, changedNodeIds: [], envelope: null };
|
|
8688
|
+
if (entry.stale) return this.discard("desfazer");
|
|
8689
|
+
const result = this.replay(entry.inverse);
|
|
8690
|
+
if (!result.applied) this.stack.revertUndo(entry);
|
|
8691
|
+
return result;
|
|
8692
|
+
}
|
|
8693
|
+
/** Refaz o gesto desfeito mais recente, pelas operações originais e na ordem delas. */
|
|
8694
|
+
redo() {
|
|
8695
|
+
const entry = this.stack.redo();
|
|
8696
|
+
if (entry === void 0) return { applied: false, changedNodeIds: [], envelope: null };
|
|
8697
|
+
if (entry.stale) return this.discard("refazer");
|
|
8698
|
+
const result = this.replay(entry.ops);
|
|
8699
|
+
if (!result.applied) this.stack.revertRedo(entry);
|
|
8700
|
+
return result;
|
|
8701
|
+
}
|
|
8702
|
+
// ------------------------------------------------------------------ privados
|
|
8703
|
+
/** O passo velho sai da pilha sem tocar no documento, com aviso. */
|
|
8704
|
+
discard(verb) {
|
|
8705
|
+
this.options.onError({
|
|
8706
|
+
code: "undo-conflict",
|
|
8707
|
+
message: `Outra pessoa mexeu no mesmo lugar depois. Esse passo de ${verb} foi descartado para n\xE3o apagar o trabalho dela.`,
|
|
8708
|
+
boardId: this.current.id
|
|
8709
|
+
});
|
|
8710
|
+
this.notify();
|
|
8711
|
+
return { applied: false, changedNodeIds: [], envelope: null, discarded: true };
|
|
8712
|
+
}
|
|
8713
|
+
/** Despacha uma lista guardada na pilha, sem deixá-la voltar para a pilha. */
|
|
8714
|
+
replay(ops) {
|
|
8715
|
+
const result = this.dispatch(batchOf2(ops), { tracked: false });
|
|
8716
|
+
if (result.rejected !== null) return { applied: false, changedNodeIds: [], envelope: null };
|
|
8717
|
+
return { applied: true, changedNodeIds: result.changedNodeIds, envelope: result.envelope };
|
|
8718
|
+
}
|
|
8719
|
+
/** O envelope de uma operação nossa. `seq` nasce nulo: quem confirma é o commit. */
|
|
8720
|
+
stamp(op) {
|
|
8721
|
+
return {
|
|
8722
|
+
id: this.newId(),
|
|
8723
|
+
boardId: this.current.id,
|
|
8724
|
+
clientId: this.options.session.clientId,
|
|
8725
|
+
actorId: this.options.session.actorId,
|
|
8726
|
+
seq: null,
|
|
8727
|
+
ts: this.clock(),
|
|
8728
|
+
op
|
|
8729
|
+
};
|
|
8730
|
+
}
|
|
8731
|
+
notify() {
|
|
8732
|
+
for (const listener of this.listeners) listener();
|
|
8733
|
+
}
|
|
8734
|
+
};
|
|
8735
|
+
function resolveGap(gap) {
|
|
8736
|
+
return typeof gap === "number" ? { x: gap, y: gap } : { x: gap.x, y: gap.y };
|
|
8737
|
+
}
|
|
8738
|
+
function rectOf2(node) {
|
|
8739
|
+
return { x: node.position.x, y: node.position.y, w: node.size.w, h: node.size.h };
|
|
8740
|
+
}
|
|
8741
|
+
function rectsCollide(a, b, gap) {
|
|
8742
|
+
return a.x < b.x + b.w + gap.x && b.x < a.x + a.w + gap.x && a.y < b.y + b.h + gap.y && b.y < a.y + a.h + gap.y;
|
|
8743
|
+
}
|
|
8744
|
+
function boundsOf(rects) {
|
|
8745
|
+
let minX = Number.POSITIVE_INFINITY;
|
|
8746
|
+
let minY = Number.POSITIVE_INFINITY;
|
|
8747
|
+
let maxX = Number.NEGATIVE_INFINITY;
|
|
8748
|
+
let maxY = Number.NEGATIVE_INFINITY;
|
|
8749
|
+
for (const rect of rects) {
|
|
8750
|
+
minX = Math.min(minX, rect.x);
|
|
8751
|
+
minY = Math.min(minY, rect.y);
|
|
8752
|
+
maxX = Math.max(maxX, rect.x + rect.w);
|
|
8753
|
+
maxY = Math.max(maxY, rect.y + rect.h);
|
|
8754
|
+
}
|
|
8755
|
+
if (rects.length === 0) return { x: 0, y: 0, w: 0, h: 0 };
|
|
8756
|
+
return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
|
|
8757
|
+
}
|
|
8758
|
+
function compareText(a, b) {
|
|
8759
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
8760
|
+
}
|
|
8761
|
+
function byScreenOrder(a, b) {
|
|
8762
|
+
return a.position.y - b.position.y || a.position.x - b.position.x || compareText(a.id, b.id);
|
|
8763
|
+
}
|
|
8764
|
+
function obstaclesOf(doc, ignore = []) {
|
|
8765
|
+
const skipped = new Set(ignore);
|
|
8766
|
+
return Object.values(doc.nodes).filter((node) => node.parentId === null && !skipped.has(node.id)).sort(byScreenOrder).map(rectOf2);
|
|
8767
|
+
}
|
|
8768
|
+
var DEFAULT_MAX_PER_COLUMN = 8;
|
|
8769
|
+
function positiveInt(value, fallback) {
|
|
8770
|
+
if (value === void 0 || !Number.isFinite(value)) return fallback;
|
|
8771
|
+
return Math.max(1, Math.floor(value));
|
|
8772
|
+
}
|
|
8773
|
+
function fanOutPositions(input) {
|
|
8774
|
+
const count = Number.isFinite(input.count) ? Math.floor(input.count) : 0;
|
|
8775
|
+
if (count < 1) return [];
|
|
8776
|
+
const gap = resolveGap(input.gap);
|
|
8777
|
+
const maxPerColumn = positiveInt(input.maxPerColumn, DEFAULT_MAX_PER_COLUMN);
|
|
8778
|
+
const columns = Math.min(count, positiveInt(input.columns, Math.ceil(count / maxPerColumn)));
|
|
8779
|
+
const rows = Math.ceil(count / columns);
|
|
8780
|
+
const { position, size } = input.source;
|
|
8781
|
+
const blockHeight = rows * input.nodeSize.h + (rows - 1) * gap.y;
|
|
8782
|
+
const left = Math.round(position.x + size.w + gap.x);
|
|
8783
|
+
const top = Math.round(position.y + size.h / 2 - blockHeight / 2);
|
|
8784
|
+
const positions = [];
|
|
8785
|
+
for (let index = 0; index < count; index += 1) {
|
|
8786
|
+
const column = index % columns;
|
|
8787
|
+
const row = Math.floor(index / columns);
|
|
8788
|
+
positions.push({
|
|
8789
|
+
x: left + column * (input.nodeSize.w + gap.x),
|
|
8790
|
+
y: top + row * (input.nodeSize.h + gap.y)
|
|
8791
|
+
});
|
|
8792
|
+
}
|
|
8793
|
+
return positions;
|
|
8794
|
+
}
|
|
8795
|
+
var DEFAULT_PLACEMENT_GAP = 40;
|
|
8796
|
+
function uniqueAscending(values) {
|
|
8797
|
+
return [...new Set(values)].sort((a, b) => a - b);
|
|
8798
|
+
}
|
|
8799
|
+
function blockIsFree(rects, bounds, dx, dy, obstacles, gap) {
|
|
8800
|
+
const movedBounds = { ...bounds, x: bounds.x + dx, y: bounds.y + dy };
|
|
8801
|
+
for (const obstacle of obstacles) {
|
|
8802
|
+
if (!rectsCollide(movedBounds, obstacle, gap)) continue;
|
|
8803
|
+
for (const rect of rects) {
|
|
8804
|
+
if (rectsCollide({ ...rect, x: rect.x + dx, y: rect.y + dy }, obstacle, gap)) return false;
|
|
8805
|
+
}
|
|
8806
|
+
}
|
|
8807
|
+
return true;
|
|
8808
|
+
}
|
|
8809
|
+
function placeWithoutOverlap(doc, rects, options) {
|
|
8810
|
+
if (rects.length === 0) return [];
|
|
8811
|
+
const gap = resolveGap(options.gap);
|
|
8812
|
+
const original = boundsOf(rects);
|
|
8813
|
+
const baseDx = options.near === void 0 ? 0 : options.near.x - original.x;
|
|
8814
|
+
const baseDy = options.near === void 0 ? 0 : options.near.y - original.y;
|
|
8815
|
+
const block = rects.map((rect) => ({ ...rect, x: rect.x + baseDx, y: rect.y + baseDy }));
|
|
8816
|
+
const bounds = boundsOf(block);
|
|
8817
|
+
const obstacles = obstaclesOf(doc, options.ignore);
|
|
8818
|
+
const maxDown = options.maxDown ?? 3 * (bounds.h + gap.y);
|
|
8819
|
+
const rightSteps = uniqueAscending([
|
|
8820
|
+
0,
|
|
8821
|
+
...obstacles.map((o) => o.x + o.w + gap.x - bounds.x).filter((dx) => dx > 0)
|
|
8822
|
+
]);
|
|
8823
|
+
const downSteps = uniqueAscending([
|
|
8824
|
+
0,
|
|
8825
|
+
...obstacles.map((o) => o.y + o.h + gap.y - bounds.y).filter((dy) => dy > 0 && dy <= maxDown)
|
|
8826
|
+
]);
|
|
8827
|
+
for (const dx of rightSteps) {
|
|
8828
|
+
for (const dy of downSteps) {
|
|
8829
|
+
if (blockIsFree(block, bounds, dx, dy, obstacles, gap)) {
|
|
8830
|
+
return block.map((rect) => ({ ...rect, x: rect.x + dx, y: rect.y + dy }));
|
|
8831
|
+
}
|
|
8832
|
+
}
|
|
8833
|
+
}
|
|
8834
|
+
return block;
|
|
8835
|
+
}
|
|
8836
|
+
function byDistance(a, b) {
|
|
8837
|
+
return a.distance - b.distance || b.y - a.y || b.x - a.x;
|
|
8838
|
+
}
|
|
8839
|
+
function findFreeSpot(doc, size, near, options = {}) {
|
|
8840
|
+
const gap = resolveGap(options.gap ?? DEFAULT_PLACEMENT_GAP);
|
|
8841
|
+
const obstacles = obstaclesOf(doc, options.ignore);
|
|
8842
|
+
const xs = uniqueAscending([
|
|
8843
|
+
near.x,
|
|
8844
|
+
...obstacles.flatMap((o) => [o.x + o.w + gap.x, o.x - gap.x - size.w])
|
|
8845
|
+
]);
|
|
8846
|
+
const candidates = xs.map((x) => {
|
|
8847
|
+
const blocked = obstacles.filter((o) => x < o.x + o.w + gap.x && o.x < x + size.w + gap.x).map((o) => ({ from: o.y - gap.y - size.h, to: o.y + o.h + gap.y })).sort((a, b) => a.from - b.from);
|
|
8848
|
+
let y = near.y;
|
|
8849
|
+
let wall;
|
|
8850
|
+
for (const interval of blocked) {
|
|
8851
|
+
if (wall !== void 0 && interval.from < wall.to) {
|
|
8852
|
+
wall.to = Math.max(wall.to, interval.to);
|
|
8853
|
+
} else if (wall !== void 0 && wall.from < near.y && near.y < wall.to) {
|
|
8854
|
+
break;
|
|
8855
|
+
} else {
|
|
8856
|
+
wall = { ...interval };
|
|
8857
|
+
}
|
|
8858
|
+
}
|
|
8859
|
+
if (wall !== void 0 && wall.from < near.y && near.y < wall.to) {
|
|
8860
|
+
y = wall.to - near.y <= near.y - wall.from ? wall.to : wall.from;
|
|
8861
|
+
}
|
|
8862
|
+
return { x, y, distance: Math.hypot(x - near.x, y - near.y) };
|
|
8863
|
+
});
|
|
8864
|
+
const [best] = candidates.sort(byDistance);
|
|
8865
|
+
if (best === void 0) return { x: near.x, y: near.y };
|
|
8866
|
+
return { x: best.x, y: best.y };
|
|
8867
|
+
}
|
|
8868
|
+
function topLevelOf(doc, nodeId3) {
|
|
8869
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8870
|
+
let current = nodeId3;
|
|
8871
|
+
for (; ; ) {
|
|
8872
|
+
if (seen.has(current) || !Object.hasOwn(doc.nodes, current)) return void 0;
|
|
8873
|
+
seen.add(current);
|
|
8874
|
+
const node = doc.nodes[current];
|
|
8875
|
+
if (node === void 0) return void 0;
|
|
8876
|
+
if (node.parentId === null) return current;
|
|
8877
|
+
current = node.parentId;
|
|
8878
|
+
}
|
|
8879
|
+
}
|
|
8880
|
+
function pushTo(map, key, value) {
|
|
8881
|
+
const list = map.get(key);
|
|
8882
|
+
if (list === void 0) map.set(key, [value]);
|
|
8883
|
+
else if (!list.includes(value)) list.push(value);
|
|
8884
|
+
}
|
|
8885
|
+
function buildLayoutGraph(doc, nodeIds) {
|
|
8886
|
+
const wanted = nodeIds === void 0 ? void 0 : new Set(nodeIds);
|
|
8887
|
+
const nodes = Object.values(doc.nodes).filter((node) => node.parentId === null && (wanted === void 0 || wanted.has(node.id))).sort(byScreenOrder);
|
|
8888
|
+
const rank = new Map(nodes.map((node, index) => [node.id, index]));
|
|
8889
|
+
const byRank = (a, b) => (rank.get(a) ?? 0) - (rank.get(b) ?? 0);
|
|
8890
|
+
const forward = /* @__PURE__ */ new Map();
|
|
8891
|
+
const neighbors = /* @__PURE__ */ new Map();
|
|
8892
|
+
for (const node of nodes) {
|
|
8893
|
+
forward.set(node.id, []);
|
|
8894
|
+
neighbors.set(node.id, []);
|
|
8895
|
+
}
|
|
8896
|
+
const branchSiblings = /* @__PURE__ */ new Map();
|
|
8897
|
+
const inputSiblings = /* @__PURE__ */ new Map();
|
|
8898
|
+
const edgeIds = Object.keys(doc.edges).sort(compareText);
|
|
8899
|
+
for (const edgeId of edgeIds) {
|
|
8900
|
+
const edge = doc.edges[edgeId];
|
|
8901
|
+
if (edge === void 0) continue;
|
|
8902
|
+
const source = topLevelOf(doc, edge.source);
|
|
8903
|
+
const target = topLevelOf(doc, edge.target);
|
|
8904
|
+
if (source === void 0 || target === void 0 || source === target) continue;
|
|
8905
|
+
if (!rank.has(source) || !rank.has(target)) continue;
|
|
8906
|
+
pushTo(forward, source, target);
|
|
8907
|
+
pushTo(neighbors, source, target);
|
|
8908
|
+
pushTo(neighbors, target, source);
|
|
8909
|
+
if (typeof edge.data["branch"] !== "number") {
|
|
8910
|
+
pushTo(branchSiblings, `${edge.source}\0${edge.sourcePort}`, target);
|
|
8911
|
+
}
|
|
8912
|
+
if (typeof edge.data["order"] !== "number") {
|
|
8913
|
+
pushTo(inputSiblings, `${edge.target}\0${edge.targetPort}`, source);
|
|
8914
|
+
}
|
|
8915
|
+
}
|
|
8916
|
+
for (const list of forward.values()) list.sort(byRank);
|
|
8917
|
+
for (const list of neighbors.values()) list.sort(byRank);
|
|
8918
|
+
const successors = withoutBackEdges(nodes, forward);
|
|
8919
|
+
const predecessors = new Map(nodes.map((node) => [node.id, []]));
|
|
8920
|
+
for (const node of nodes) {
|
|
8921
|
+
for (const target of successors.get(node.id) ?? []) predecessors.get(target)?.push(node.id);
|
|
8922
|
+
}
|
|
8923
|
+
const orderedSiblings = [...branchSiblings.values(), ...inputSiblings.values()].filter((group) => group.length > 1).map((group) => [...group].sort(byRank));
|
|
8924
|
+
return { nodes, rank, successors, predecessors, neighbors, orderedSiblings };
|
|
8925
|
+
}
|
|
8926
|
+
function withoutBackEdges(nodes, forward) {
|
|
8927
|
+
const hasIncoming = /* @__PURE__ */ new Set();
|
|
8928
|
+
for (const targets of forward.values()) for (const target of targets) hasIncoming.add(target);
|
|
8929
|
+
const starts = [
|
|
8930
|
+
...nodes.filter((node) => !hasIncoming.has(node.id)),
|
|
8931
|
+
...nodes.filter((node) => hasIncoming.has(node.id)).sort(
|
|
8932
|
+
(a, b) => a.position.x - b.position.x || a.position.y - b.position.y || compareText(a.id, b.id)
|
|
8933
|
+
)
|
|
8934
|
+
];
|
|
8935
|
+
const kept = new Map(nodes.map((node) => [node.id, []]));
|
|
8936
|
+
const state = /* @__PURE__ */ new Map();
|
|
8937
|
+
for (const start of starts) {
|
|
8938
|
+
if (state.has(start.id)) continue;
|
|
8939
|
+
const stack = [{ id: start.id, next: 0 }];
|
|
8940
|
+
state.set(start.id, "open");
|
|
8941
|
+
for (let frame = stack[stack.length - 1]; frame !== void 0; frame = stack[stack.length - 1]) {
|
|
8942
|
+
const targets = forward.get(frame.id) ?? [];
|
|
8943
|
+
const target = targets[frame.next];
|
|
8944
|
+
if (target === void 0) {
|
|
8945
|
+
state.set(frame.id, "done");
|
|
8946
|
+
stack.pop();
|
|
8947
|
+
continue;
|
|
8948
|
+
}
|
|
8949
|
+
frame.next += 1;
|
|
8950
|
+
const seen = state.get(target);
|
|
8951
|
+
if (seen === "open") continue;
|
|
8952
|
+
kept.get(frame.id)?.push(target);
|
|
8953
|
+
if (seen === void 0) {
|
|
8954
|
+
state.set(target, "open");
|
|
8955
|
+
stack.push({ id: target, next: 0 });
|
|
8956
|
+
}
|
|
8957
|
+
}
|
|
8958
|
+
}
|
|
8959
|
+
return kept;
|
|
8960
|
+
}
|
|
8961
|
+
function assignLayers(graph, ids) {
|
|
8962
|
+
const pending = /* @__PURE__ */ new Map();
|
|
8963
|
+
for (const id of ids) pending.set(id, graph.predecessors.get(id)?.length ?? 0);
|
|
8964
|
+
const layer = /* @__PURE__ */ new Map();
|
|
8965
|
+
const queue = ids.filter((id) => pending.get(id) === 0);
|
|
8966
|
+
for (const id of queue) layer.set(id, 0);
|
|
8967
|
+
for (let head = 0; head < queue.length; head += 1) {
|
|
8968
|
+
const id = queue[head];
|
|
8969
|
+
if (id === void 0) continue;
|
|
8970
|
+
const current = layer.get(id) ?? 0;
|
|
8971
|
+
for (const target of graph.successors.get(id) ?? []) {
|
|
8972
|
+
layer.set(target, Math.max(layer.get(target) ?? 0, current + 1));
|
|
8973
|
+
const left = (pending.get(target) ?? 0) - 1;
|
|
8974
|
+
pending.set(target, left);
|
|
8975
|
+
if (left === 0) queue.push(target);
|
|
8976
|
+
}
|
|
8977
|
+
}
|
|
8978
|
+
for (const id of ids) {
|
|
8979
|
+
const targets = graph.successors.get(id) ?? [];
|
|
8980
|
+
if ((graph.predecessors.get(id)?.length ?? 0) > 0 || targets.length === 0) continue;
|
|
8981
|
+
layer.set(id, Math.min(...targets.map((target) => layer.get(target) ?? 1)) - 1);
|
|
8982
|
+
}
|
|
8983
|
+
return layer;
|
|
8984
|
+
}
|
|
8985
|
+
function splitComponents(graph) {
|
|
8986
|
+
const components = [];
|
|
8987
|
+
const isolated = [];
|
|
8988
|
+
const visited = /* @__PURE__ */ new Set();
|
|
8989
|
+
for (const node of graph.nodes) {
|
|
8990
|
+
if (visited.has(node.id)) continue;
|
|
8991
|
+
visited.add(node.id);
|
|
8992
|
+
if ((graph.neighbors.get(node.id)?.length ?? 0) === 0) {
|
|
8993
|
+
isolated.push(node.id);
|
|
8994
|
+
continue;
|
|
8995
|
+
}
|
|
8996
|
+
const members = [node.id];
|
|
8997
|
+
for (let head = 0; head < members.length; head += 1) {
|
|
8998
|
+
const id = members[head];
|
|
8999
|
+
if (id === void 0) continue;
|
|
9000
|
+
for (const next of graph.neighbors.get(id) ?? []) {
|
|
9001
|
+
if (visited.has(next)) continue;
|
|
9002
|
+
visited.add(next);
|
|
9003
|
+
members.push(next);
|
|
9004
|
+
}
|
|
9005
|
+
}
|
|
9006
|
+
members.sort((a, b) => (graph.rank.get(a) ?? 0) - (graph.rank.get(b) ?? 0));
|
|
9007
|
+
components.push(members);
|
|
9008
|
+
}
|
|
9009
|
+
return { components, isolated };
|
|
9010
|
+
}
|
|
9011
|
+
function countCrossings(graph, layers) {
|
|
9012
|
+
let crossings = 0;
|
|
9013
|
+
for (let index = 0; index + 1 < layers.length; index += 1) {
|
|
9014
|
+
const left = layers[index] ?? [];
|
|
9015
|
+
const right = new Map((layers[index + 1] ?? []).map((id, slot) => [id, slot]));
|
|
9016
|
+
const spans = [];
|
|
9017
|
+
left.forEach((id, slot) => {
|
|
9018
|
+
for (const target of graph.successors.get(id) ?? []) {
|
|
9019
|
+
const targetSlot = right.get(target);
|
|
9020
|
+
if (targetSlot !== void 0) spans.push([slot, targetSlot]);
|
|
9021
|
+
}
|
|
9022
|
+
});
|
|
9023
|
+
for (let a = 0; a < spans.length; a += 1) {
|
|
9024
|
+
for (let b = a + 1; b < spans.length; b += 1) {
|
|
9025
|
+
const first = spans[a];
|
|
9026
|
+
const second = spans[b];
|
|
9027
|
+
if (first === void 0 || second === void 0) continue;
|
|
9028
|
+
if ((first[0] - second[0]) * (first[1] - second[1]) < 0) crossings += 1;
|
|
9029
|
+
}
|
|
9030
|
+
}
|
|
9031
|
+
}
|
|
9032
|
+
return crossings;
|
|
9033
|
+
}
|
|
9034
|
+
function reorderLayer(layer, reference, neighborsOf) {
|
|
9035
|
+
const slotOf = new Map(reference.map((id, slot) => [id, slot]));
|
|
9036
|
+
const weight = /* @__PURE__ */ new Map();
|
|
9037
|
+
for (const id of layer) {
|
|
9038
|
+
const slots = neighborsOf(id).flatMap((neighbor) => {
|
|
9039
|
+
const slot = slotOf.get(neighbor);
|
|
9040
|
+
return slot === void 0 ? [] : [slot];
|
|
9041
|
+
});
|
|
9042
|
+
if (slots.length > 0) weight.set(id, slots.reduce((sum, slot) => sum + slot, 0) / slots.length);
|
|
9043
|
+
}
|
|
9044
|
+
const current = new Map(layer.map((id, slot) => [id, slot]));
|
|
9045
|
+
const movable = layer.filter((id) => weight.has(id)).sort(
|
|
9046
|
+
(a, b) => (weight.get(a) ?? 0) - (weight.get(b) ?? 0) || (current.get(a) ?? 0) - (current.get(b) ?? 0)
|
|
9047
|
+
);
|
|
9048
|
+
let next = 0;
|
|
9049
|
+
return layer.map((id) => weight.has(id) ? movable[next++] ?? id : id);
|
|
9050
|
+
}
|
|
9051
|
+
function restoreSiblingOrder(graph, layer) {
|
|
9052
|
+
const result = [...layer];
|
|
9053
|
+
for (const group of graph.orderedSiblings) {
|
|
9054
|
+
const members = new Set(group);
|
|
9055
|
+
const slots = [];
|
|
9056
|
+
result.forEach((id, slot) => {
|
|
9057
|
+
if (members.has(id)) slots.push(slot);
|
|
9058
|
+
});
|
|
9059
|
+
if (slots.length < 2) continue;
|
|
9060
|
+
const present = group.filter((id) => result.includes(id));
|
|
9061
|
+
slots.forEach((slot, index) => {
|
|
9062
|
+
const id = present[index];
|
|
9063
|
+
if (id !== void 0) result[slot] = id;
|
|
9064
|
+
});
|
|
9065
|
+
}
|
|
9066
|
+
return result;
|
|
9067
|
+
}
|
|
9068
|
+
function orderLayers(graph, initial, sweeps) {
|
|
9069
|
+
let layers = initial.map((layer) => [...layer]);
|
|
9070
|
+
let best = layers;
|
|
9071
|
+
let bestCrossings = countCrossings(graph, layers);
|
|
9072
|
+
for (let pass = 0; pass < sweeps && bestCrossings > 0; pass += 1) {
|
|
9073
|
+
const forward = pass % 2 === 0;
|
|
9074
|
+
const next = layers.map((layer) => [...layer]);
|
|
9075
|
+
const order = next.map((_, index) => index);
|
|
9076
|
+
if (!forward) order.reverse();
|
|
9077
|
+
for (const index of order) {
|
|
9078
|
+
const reference = next[forward ? index - 1 : index + 1];
|
|
9079
|
+
const layer = next[index];
|
|
9080
|
+
if (reference === void 0 || layer === void 0) continue;
|
|
9081
|
+
const neighborsOf = (id) => (forward ? graph.predecessors.get(id) : graph.successors.get(id)) ?? [];
|
|
9082
|
+
next[index] = restoreSiblingOrder(graph, reorderLayer(layer, reference, neighborsOf));
|
|
9083
|
+
}
|
|
9084
|
+
layers = next;
|
|
9085
|
+
const crossings = countCrossings(graph, layers);
|
|
9086
|
+
if (crossings < bestCrossings) {
|
|
9087
|
+
best = layers;
|
|
9088
|
+
bestCrossings = crossings;
|
|
9089
|
+
}
|
|
9090
|
+
}
|
|
9091
|
+
return best;
|
|
9092
|
+
}
|
|
9093
|
+
var DEFAULT_TIDY_GAP_X = 120;
|
|
9094
|
+
var DEFAULT_TIDY_GAP_Y = 48;
|
|
9095
|
+
var DEFAULT_TIDY_SWEEPS = 4;
|
|
9096
|
+
function layoutComponent(doc, graph, members, gapX, gapY, sweeps) {
|
|
9097
|
+
const layerOf = assignLayers(graph, members);
|
|
9098
|
+
const initial = [];
|
|
9099
|
+
for (const id of members) {
|
|
9100
|
+
const index = layerOf.get(id) ?? 0;
|
|
9101
|
+
(initial[index] ??= []).push(id);
|
|
9102
|
+
}
|
|
9103
|
+
const layers = orderLayers(
|
|
9104
|
+
graph,
|
|
9105
|
+
Array.from(initial, (layer) => layer ?? []).filter((layer) => layer.length > 0),
|
|
9106
|
+
sweeps
|
|
9107
|
+
);
|
|
9108
|
+
const columns = layers.map((layer) => {
|
|
9109
|
+
const nodes = layer.flatMap((id) => {
|
|
9110
|
+
const node = doc.nodes[id];
|
|
9111
|
+
return node === void 0 ? [] : [node];
|
|
9112
|
+
});
|
|
9113
|
+
const width2 = Math.max(...nodes.map((node) => node.size.w));
|
|
9114
|
+
const height = nodes.reduce((sum, node) => sum + node.size.h, 0) + (nodes.length - 1) * gapY;
|
|
9115
|
+
return { nodes, width: width2, height };
|
|
9116
|
+
});
|
|
9117
|
+
const tallest = Math.max(...columns.map((column) => column.height));
|
|
9118
|
+
const placed = [];
|
|
9119
|
+
let x = 0;
|
|
9120
|
+
for (const column of columns) {
|
|
9121
|
+
let y = Math.round((tallest - column.height) / 2);
|
|
9122
|
+
for (const node of column.nodes) {
|
|
9123
|
+
placed.push({ id: node.id, rect: { x, y, w: node.size.w, h: node.size.h } });
|
|
9124
|
+
y += node.size.h + gapY;
|
|
9125
|
+
}
|
|
9126
|
+
x += column.width + gapX;
|
|
9127
|
+
}
|
|
9128
|
+
return placed;
|
|
9129
|
+
}
|
|
9130
|
+
function layoutStrip(nodes, width2, gapX, gapY) {
|
|
9131
|
+
const placed = [];
|
|
9132
|
+
let x = 0;
|
|
9133
|
+
let y = 0;
|
|
9134
|
+
let shelfHeight = 0;
|
|
9135
|
+
for (const node of nodes) {
|
|
9136
|
+
if (x > 0 && x + node.size.w > width2) {
|
|
9137
|
+
x = 0;
|
|
9138
|
+
y += shelfHeight + gapY;
|
|
9139
|
+
shelfHeight = 0;
|
|
9140
|
+
}
|
|
9141
|
+
placed.push({ id: node.id, rect: { x, y, w: node.size.w, h: node.size.h } });
|
|
9142
|
+
x += node.size.w + gapX;
|
|
9143
|
+
shelfHeight = Math.max(shelfHeight, node.size.h);
|
|
9144
|
+
}
|
|
9145
|
+
return placed;
|
|
9146
|
+
}
|
|
9147
|
+
function shifted(placed, dx, dy) {
|
|
9148
|
+
return placed.map(({ id, rect }) => ({ id, rect: { ...rect, x: rect.x + dx, y: rect.y + dy } }));
|
|
9149
|
+
}
|
|
9150
|
+
function tidyUp(doc, options = {}) {
|
|
9151
|
+
const gapX = options.gapX ?? DEFAULT_TIDY_GAP_X;
|
|
9152
|
+
const gapY = options.gapY ?? DEFAULT_TIDY_GAP_Y;
|
|
9153
|
+
const componentGap = options.componentGap ?? gapY * 2;
|
|
9154
|
+
const sweeps = options.sweeps ?? DEFAULT_TIDY_SWEEPS;
|
|
9155
|
+
const graph = buildLayoutGraph(doc, options.nodeIds);
|
|
9156
|
+
if (graph.nodes.length === 0) return /* @__PURE__ */ new Map();
|
|
9157
|
+
const { components, isolated } = splitComponents(graph);
|
|
9158
|
+
let placed = [];
|
|
9159
|
+
let cursorY = 0;
|
|
9160
|
+
let widest = 0;
|
|
9161
|
+
for (const members of components) {
|
|
9162
|
+
const block = layoutComponent(doc, graph, members, gapX, gapY, sweeps);
|
|
9163
|
+
const bounds = boundsOf(block.map((item) => item.rect));
|
|
9164
|
+
placed = placed.concat(shifted(block, 0, cursorY));
|
|
9165
|
+
cursorY += bounds.h + componentGap;
|
|
9166
|
+
widest = Math.max(widest, bounds.w);
|
|
9167
|
+
}
|
|
9168
|
+
if (isolated.length > 0) {
|
|
9169
|
+
const loose = graph.nodes.filter((node) => isolated.includes(node.id));
|
|
9170
|
+
const area = loose.reduce((sum, node) => sum + (node.size.w + gapX) * (node.size.h + gapY), 0);
|
|
9171
|
+
const stripWidth = Math.max(widest, Math.sqrt(area * 1.6));
|
|
9172
|
+
placed = placed.concat(shifted(layoutStrip(loose, stripWidth, gapX, gapY), 0, cursorY));
|
|
9173
|
+
}
|
|
9174
|
+
const anchor = boundsOf(graph.nodes.map(rectOf2));
|
|
9175
|
+
const anchored = shifted(placed, Math.round(anchor.x), Math.round(anchor.y));
|
|
9176
|
+
const scope = graph.nodes.map((node) => node.id);
|
|
9177
|
+
const others = obstaclesOf(doc, scope);
|
|
9178
|
+
const touching = { x: 0, y: 0 };
|
|
9179
|
+
const covers = anchored.some(
|
|
9180
|
+
({ rect }) => others.some((other) => rectsCollide(rect, other, touching))
|
|
9181
|
+
);
|
|
9182
|
+
const rects = covers ? placeWithoutOverlap(
|
|
9183
|
+
doc,
|
|
9184
|
+
anchored.map((item) => item.rect),
|
|
9185
|
+
{ gap: { x: gapX, y: gapY }, ignore: scope }
|
|
9186
|
+
) : anchored.map((item) => item.rect);
|
|
9187
|
+
const positions = /* @__PURE__ */ new Map();
|
|
9188
|
+
anchored.forEach(({ id }, index) => {
|
|
9189
|
+
const rect = rects[index];
|
|
9190
|
+
if (rect !== void 0) positions.set(id, { x: rect.x, y: rect.y });
|
|
9191
|
+
});
|
|
9192
|
+
return positions;
|
|
9193
|
+
}
|
|
9194
|
+
function moveOps(positions) {
|
|
9195
|
+
const latest = /* @__PURE__ */ new Map();
|
|
9196
|
+
for (const [nodeId3, point2] of positions) latest.set(nodeId3, point2);
|
|
9197
|
+
const ops = [...latest.keys()].sort(compareText).flatMap((nodeId3) => {
|
|
9198
|
+
const point2 = latest.get(nodeId3);
|
|
9199
|
+
if (point2 === void 0) return [];
|
|
9200
|
+
return [
|
|
9201
|
+
{ type: "node.set", nodeId: nodeId3, path: "position", value: propValue({ x: point2.x, y: point2.y }) }
|
|
9202
|
+
];
|
|
9203
|
+
});
|
|
9204
|
+
return { type: "batch", ops };
|
|
9205
|
+
}
|
|
9206
|
+
function tidyUpOps(doc, options = {}) {
|
|
9207
|
+
const moved = [...tidyUp(doc, options)].filter(([nodeId3, point2]) => {
|
|
9208
|
+
const node = doc.nodes[nodeId3];
|
|
9209
|
+
return node !== void 0 && (node.position.x !== point2.x || node.position.y !== point2.y);
|
|
9210
|
+
});
|
|
9211
|
+
return moveOps(moved);
|
|
9212
|
+
}
|
|
9213
|
+
var MAX_REPLAY = 200;
|
|
9214
|
+
function tryApplyOp(doc, op) {
|
|
9215
|
+
const result = step(doc, op);
|
|
9216
|
+
return typeof result === "string" ? { ok: false, reason: result } : { ok: true, doc: result };
|
|
9217
|
+
}
|
|
9218
|
+
function tryApplyEnvelope(doc, envelope2) {
|
|
9219
|
+
if (opEnvelopeBytes(envelope2) > MAX_OP_BYTES2) return { ok: false, reason: "too-large" };
|
|
9220
|
+
return tryApplyOp(doc, envelope2.op);
|
|
9221
|
+
}
|
|
9222
|
+
function applyConfirmed2(doc, envelope2) {
|
|
9223
|
+
if (envelope2.seq === null) {
|
|
9224
|
+
throw new Error(`applyConfirmed recebeu o envelope ${envelope2.id} sem seq`);
|
|
9225
|
+
}
|
|
9226
|
+
const next = applyOps(doc, [envelope2.op]).doc;
|
|
9227
|
+
return { ...next, version: envelope2.seq };
|
|
9228
|
+
}
|
|
9229
|
+
function step(doc, op) {
|
|
9230
|
+
switch (op.type) {
|
|
9231
|
+
case "batch": {
|
|
9232
|
+
let current = doc;
|
|
9233
|
+
for (const inner of op.ops) {
|
|
9234
|
+
const result = step(current, inner);
|
|
9235
|
+
if (typeof result === "string") return result;
|
|
9236
|
+
current = result;
|
|
9237
|
+
}
|
|
9238
|
+
return current;
|
|
9239
|
+
}
|
|
9240
|
+
case "node.set":
|
|
9241
|
+
case "history.append":
|
|
9242
|
+
if (doc.nodes[op.nodeId] === void 0) return "node-missing";
|
|
9243
|
+
break;
|
|
9244
|
+
case "edge.add":
|
|
9245
|
+
if (doc.nodes[op.edge.source] === void 0 || doc.nodes[op.edge.target] === void 0) {
|
|
9246
|
+
return "edge-endpoint-missing";
|
|
9247
|
+
}
|
|
9248
|
+
break;
|
|
9249
|
+
default:
|
|
9250
|
+
break;
|
|
9251
|
+
}
|
|
9252
|
+
try {
|
|
9253
|
+
return applyOps(doc, [op]).doc;
|
|
9254
|
+
} catch {
|
|
9255
|
+
return "invalid-op";
|
|
9256
|
+
}
|
|
9257
|
+
}
|
|
9258
|
+
function defaultScheduler() {
|
|
9259
|
+
const host = globalThis;
|
|
9260
|
+
return {
|
|
9261
|
+
setTimeout: (callback, ms) => host.setTimeout(callback, ms),
|
|
9262
|
+
clearTimeout: (handle) => host.clearTimeout(handle)
|
|
9263
|
+
};
|
|
9264
|
+
}
|
|
9265
|
+
var OpSyncClient = class {
|
|
9266
|
+
store;
|
|
9267
|
+
transport;
|
|
9268
|
+
scheduler;
|
|
9269
|
+
batchMs;
|
|
9270
|
+
gapGraceMs;
|
|
9271
|
+
retryMs;
|
|
9272
|
+
maxRetryMs;
|
|
9273
|
+
maxBatch;
|
|
9274
|
+
onDiscard;
|
|
9275
|
+
onTransportError;
|
|
9276
|
+
confirmed;
|
|
9277
|
+
lastSeq;
|
|
9278
|
+
buffer = /* @__PURE__ */ new Map();
|
|
9279
|
+
pending = [];
|
|
9280
|
+
online = false;
|
|
9281
|
+
started = false;
|
|
9282
|
+
stopped = false;
|
|
9283
|
+
commitInFlight = false;
|
|
9284
|
+
syncInFlight = false;
|
|
9285
|
+
snapshotInFlight = false;
|
|
9286
|
+
flushTimer = null;
|
|
9287
|
+
gapTimer = null;
|
|
9288
|
+
retryTimer = null;
|
|
9289
|
+
retryDelay;
|
|
9290
|
+
unsubscribe = [];
|
|
9291
|
+
stats = {
|
|
9292
|
+
commits: 0,
|
|
9293
|
+
commitFailures: 0,
|
|
9294
|
+
syncs: 0,
|
|
9295
|
+
gapSyncs: 0,
|
|
9296
|
+
snapshots: 0,
|
|
9297
|
+
discarded: 0,
|
|
9298
|
+
echoes: 0
|
|
9299
|
+
};
|
|
9300
|
+
constructor(options) {
|
|
9301
|
+
this.store = options.store;
|
|
9302
|
+
this.transport = options.transport;
|
|
9303
|
+
this.scheduler = options.scheduler ?? defaultScheduler();
|
|
9304
|
+
this.batchMs = options.batchMs ?? 200;
|
|
9305
|
+
this.gapGraceMs = options.gapGraceMs ?? 300;
|
|
9306
|
+
this.retryMs = options.retryMs ?? 1e3;
|
|
9307
|
+
this.maxRetryMs = options.maxRetryMs ?? 3e4;
|
|
9308
|
+
this.maxBatch = options.maxBatch ?? 100;
|
|
9309
|
+
this.onDiscard = options.onDiscard;
|
|
9310
|
+
this.onTransportError = options.onTransportError;
|
|
9311
|
+
this.retryDelay = this.retryMs;
|
|
9312
|
+
this.lastSeq = options.seq;
|
|
9313
|
+
this.confirmed = { ...this.store.getDoc(), version: options.seq };
|
|
9314
|
+
}
|
|
9315
|
+
/** Entra na sala, passa a ouvir o store e pede o que perdeu desde `seq`. */
|
|
9316
|
+
start() {
|
|
9317
|
+
if (this.started) return;
|
|
9318
|
+
this.started = true;
|
|
9319
|
+
this.unsubscribe.push(
|
|
9320
|
+
this.store.subscribeEnvelopes((envelope2) => this.enqueue(envelope2)),
|
|
9321
|
+
this.transport.subscribe({
|
|
9322
|
+
onOps: (envelopes) => this.receive(envelopes),
|
|
9323
|
+
onResync: () => this.requestSnapshot(),
|
|
9324
|
+
onConnectionChange: (online) => this.setOnline(online)
|
|
9325
|
+
})
|
|
9326
|
+
);
|
|
9327
|
+
this.online = this.transport.isOnline();
|
|
9328
|
+
if (this.online) this.requestSync();
|
|
9329
|
+
}
|
|
9330
|
+
/** Sai da sala e para os relógios. Pendentes ficam onde estão (`pendingEnvelopes`). */
|
|
9331
|
+
stop() {
|
|
9332
|
+
this.stopped = true;
|
|
9333
|
+
for (const off of this.unsubscribe) off();
|
|
9334
|
+
this.unsubscribe = [];
|
|
9335
|
+
this.clearTimer("flushTimer");
|
|
9336
|
+
this.clearTimer("gapTimer");
|
|
9337
|
+
this.clearTimer("retryTimer");
|
|
9338
|
+
}
|
|
9339
|
+
/** Commita já, sem esperar a janela do lote. */
|
|
9340
|
+
flushNow() {
|
|
9341
|
+
this.clearTimer("flushTimer");
|
|
9342
|
+
this.flush();
|
|
9343
|
+
}
|
|
9344
|
+
getStatus() {
|
|
9345
|
+
const inFlight = this.pending.filter((item) => item.inFlight).length;
|
|
9346
|
+
return {
|
|
9347
|
+
online: this.online,
|
|
9348
|
+
lastSeq: this.lastSeq,
|
|
9349
|
+
pending: this.pending.length,
|
|
9350
|
+
inFlight,
|
|
9351
|
+
buffered: this.buffer.size,
|
|
9352
|
+
settled: this.pending.length === 0 && this.buffer.size === 0 && !this.commitInFlight && !this.syncInFlight && !this.snapshotInFlight
|
|
9353
|
+
};
|
|
9354
|
+
}
|
|
9355
|
+
/** A foto confirmada, sem pendentes. */
|
|
9356
|
+
getConfirmedDoc() {
|
|
9357
|
+
return this.confirmed;
|
|
9358
|
+
}
|
|
9359
|
+
/** As pendentes, em ordem. Para o cache local guardar até voltarem. */
|
|
9360
|
+
pendingEnvelopes() {
|
|
9361
|
+
return this.pending.map((item) => item.envelope);
|
|
9362
|
+
}
|
|
9363
|
+
// ------------------------------------------------------------------ entrada
|
|
9364
|
+
enqueue(envelope2) {
|
|
9365
|
+
if (this.stopped) return;
|
|
9366
|
+
if (opEnvelopeBytes(envelope2) > MAX_OP_BYTES2) {
|
|
9367
|
+
this.discard(envelope2, "too-large", "too-large");
|
|
9368
|
+
this.rebuild();
|
|
9369
|
+
return;
|
|
9370
|
+
}
|
|
9371
|
+
this.pending.push({ envelope: envelope2, sent: false, inFlight: false });
|
|
9372
|
+
this.scheduleFlush();
|
|
9373
|
+
}
|
|
9374
|
+
receive(envelopes) {
|
|
9375
|
+
if (this.stopped) return;
|
|
9376
|
+
let changed = false;
|
|
9377
|
+
for (const envelope2 of envelopes) {
|
|
9378
|
+
if (envelope2.seq === null) continue;
|
|
9379
|
+
if (this.findPending(envelope2.id) >= 0) this.stats.echoes += 1;
|
|
9380
|
+
if (this.confirm(envelope2.id, envelope2.seq, envelope2)) changed = true;
|
|
9381
|
+
}
|
|
9382
|
+
if (changed) this.settle();
|
|
9383
|
+
else this.checkGap();
|
|
9384
|
+
}
|
|
9385
|
+
/**
|
|
9386
|
+
* Registra que `opId` foi confirmado com `seq`. Se é pendente nossa, sai da
|
|
9387
|
+
* fila (eco, resposta do commit ou replay: tanto faz qual chega primeiro).
|
|
9388
|
+
* Devolve se algo mudou.
|
|
9389
|
+
*/
|
|
9390
|
+
confirm(opId, seq, wire) {
|
|
9391
|
+
const index = this.findPending(opId);
|
|
9392
|
+
let envelope2 = wire;
|
|
9393
|
+
if (index >= 0) {
|
|
9394
|
+
const [item] = this.pending.splice(index, 1);
|
|
9395
|
+
envelope2 = item?.envelope;
|
|
9396
|
+
}
|
|
9397
|
+
if (seq <= this.lastSeq) return index >= 0;
|
|
9398
|
+
if (envelope2 === void 0) return index >= 0;
|
|
9399
|
+
if (!this.buffer.has(seq)) this.buffer.set(seq, { ...envelope2, seq });
|
|
9400
|
+
return true;
|
|
9401
|
+
}
|
|
9402
|
+
// ---------------------------------------------------------------- commit
|
|
9403
|
+
scheduleFlush() {
|
|
9404
|
+
if (this.flushTimer !== null || this.stopped) return;
|
|
9405
|
+
this.flushTimer = this.scheduler.setTimeout(() => {
|
|
9406
|
+
this.flushTimer = null;
|
|
9407
|
+
this.flush();
|
|
9408
|
+
}, this.batchMs);
|
|
9409
|
+
}
|
|
9410
|
+
flush() {
|
|
9411
|
+
if (this.stopped || !this.online || this.commitInFlight) return;
|
|
9412
|
+
const batch = this.pending.slice(0, this.maxBatch);
|
|
9413
|
+
if (batch.length === 0) return;
|
|
9414
|
+
for (const item of batch) {
|
|
9415
|
+
item.sent = true;
|
|
9416
|
+
item.inFlight = true;
|
|
9417
|
+
}
|
|
9418
|
+
this.commitInFlight = true;
|
|
9419
|
+
this.stats.commits += 1;
|
|
9420
|
+
this.transport.commit(batch.map((item) => item.envelope)).then(
|
|
9421
|
+
(response) => this.onCommitted(batch, response),
|
|
9422
|
+
(error2) => this.onCommitFailed(batch, error2)
|
|
9423
|
+
);
|
|
9424
|
+
}
|
|
9425
|
+
onCommitted(batch, response) {
|
|
9426
|
+
this.commitInFlight = false;
|
|
9427
|
+
for (const item of batch) item.inFlight = false;
|
|
9428
|
+
if (this.stopped) return;
|
|
9429
|
+
this.retryDelay = this.retryMs;
|
|
9430
|
+
let changed = false;
|
|
9431
|
+
for (const outcome of response.outcomes) {
|
|
9432
|
+
if ("seq" in outcome) {
|
|
9433
|
+
if (this.confirm(outcome.opId, outcome.seq)) changed = true;
|
|
9434
|
+
} else {
|
|
9435
|
+
const index = this.findPending(outcome.opId);
|
|
9436
|
+
if (index < 0) continue;
|
|
9437
|
+
const [item] = this.pending.splice(index, 1);
|
|
9438
|
+
if (item !== void 0) this.discard(item.envelope, "rejected", outcome.rejected);
|
|
9439
|
+
changed = true;
|
|
9440
|
+
}
|
|
9441
|
+
}
|
|
9442
|
+
if (changed) this.settle();
|
|
9443
|
+
if (this.pending.length > 0) this.flush();
|
|
9444
|
+
}
|
|
9445
|
+
onCommitFailed(batch, error2) {
|
|
9446
|
+
this.commitInFlight = false;
|
|
9447
|
+
for (const item of batch) item.inFlight = false;
|
|
9448
|
+
if (this.stopped) return;
|
|
9449
|
+
this.stats.commitFailures += 1;
|
|
9450
|
+
this.onTransportError?.(error2);
|
|
9451
|
+
this.scheduleRetry();
|
|
9452
|
+
}
|
|
9453
|
+
// ------------------------------------------------------- sync e foto
|
|
9454
|
+
requestSync() {
|
|
9455
|
+
if (this.stopped || !this.online || this.syncInFlight) return;
|
|
9456
|
+
this.syncInFlight = true;
|
|
9457
|
+
this.stats.syncs += 1;
|
|
9458
|
+
this.transport.sync(this.lastSeq).then(
|
|
9459
|
+
(response) => this.onSynced(response),
|
|
9460
|
+
(error2) => {
|
|
9461
|
+
this.syncInFlight = false;
|
|
9462
|
+
if (this.stopped) return;
|
|
9463
|
+
this.onTransportError?.(error2);
|
|
9464
|
+
this.scheduleRetry();
|
|
9465
|
+
}
|
|
9466
|
+
);
|
|
9467
|
+
}
|
|
9468
|
+
onSynced(response) {
|
|
9469
|
+
this.syncInFlight = false;
|
|
9470
|
+
if (this.stopped) return;
|
|
9471
|
+
if (response.status === "resync") {
|
|
9472
|
+
this.requestSnapshot();
|
|
9473
|
+
return;
|
|
9474
|
+
}
|
|
9475
|
+
this.receive(response.envelopes);
|
|
9476
|
+
}
|
|
9477
|
+
requestSnapshot() {
|
|
9478
|
+
if (this.stopped || !this.online || this.snapshotInFlight) return;
|
|
9479
|
+
this.snapshotInFlight = true;
|
|
9480
|
+
this.stats.snapshots += 1;
|
|
9481
|
+
this.transport.snapshot().then(
|
|
9482
|
+
(snapshot) => {
|
|
9483
|
+
this.snapshotInFlight = false;
|
|
9484
|
+
if (this.stopped) return;
|
|
9485
|
+
if (snapshot.seq < this.lastSeq) return;
|
|
9486
|
+
this.confirmed = { ...snapshot.doc, version: snapshot.seq };
|
|
9487
|
+
this.lastSeq = snapshot.seq;
|
|
9488
|
+
this.settle();
|
|
9489
|
+
this.flush();
|
|
9490
|
+
},
|
|
9491
|
+
(error2) => {
|
|
9492
|
+
this.snapshotInFlight = false;
|
|
9493
|
+
if (this.stopped) return;
|
|
9494
|
+
this.onTransportError?.(error2);
|
|
9495
|
+
this.scheduleRetry();
|
|
9496
|
+
}
|
|
9497
|
+
);
|
|
9498
|
+
}
|
|
9499
|
+
// --------------------------------------------------------------- conexão
|
|
9500
|
+
setOnline(online) {
|
|
9501
|
+
if (this.stopped) return;
|
|
9502
|
+
this.online = online;
|
|
9503
|
+
if (!online) return;
|
|
9504
|
+
this.retryDelay = this.retryMs;
|
|
9505
|
+
this.clearTimer("retryTimer");
|
|
9506
|
+
this.resume();
|
|
9507
|
+
}
|
|
9508
|
+
resume() {
|
|
9509
|
+
this.requestSync();
|
|
9510
|
+
this.flush();
|
|
9511
|
+
}
|
|
9512
|
+
scheduleRetry() {
|
|
9513
|
+
if (this.retryTimer !== null || !this.online) return;
|
|
9514
|
+
const delay = this.retryDelay;
|
|
9515
|
+
this.retryDelay = Math.min(this.retryDelay * 2, this.maxRetryMs);
|
|
9516
|
+
this.retryTimer = this.scheduler.setTimeout(() => {
|
|
9517
|
+
this.retryTimer = null;
|
|
9518
|
+
this.resume();
|
|
9519
|
+
}, delay);
|
|
9520
|
+
}
|
|
9521
|
+
// ---------------------------------------------------------- foto e tela
|
|
9522
|
+
/** Avança a foto pelo que é contíguo, reconstrói a tela e confere buraco. */
|
|
9523
|
+
settle() {
|
|
9524
|
+
for (const seq of [...this.buffer.keys()]) {
|
|
9525
|
+
if (seq <= this.lastSeq) this.buffer.delete(seq);
|
|
9526
|
+
}
|
|
9527
|
+
for (; ; ) {
|
|
9528
|
+
const next = this.buffer.get(this.lastSeq + 1);
|
|
9529
|
+
if (next === void 0) break;
|
|
9530
|
+
this.buffer.delete(this.lastSeq + 1);
|
|
9531
|
+
try {
|
|
9532
|
+
this.confirmed = applyConfirmed2(this.confirmed, next);
|
|
9533
|
+
} catch {
|
|
9534
|
+
this.buffer.clear();
|
|
9535
|
+
this.requestSnapshot();
|
|
9536
|
+
break;
|
|
9537
|
+
}
|
|
9538
|
+
this.lastSeq += 1;
|
|
9539
|
+
}
|
|
9540
|
+
this.rebuild();
|
|
9541
|
+
this.checkGap();
|
|
9542
|
+
}
|
|
9543
|
+
/**
|
|
9544
|
+
* A tela = foto confirmada + confirmados à frente do buraco + pendentes.
|
|
9545
|
+
*
|
|
9546
|
+
* Pendente que nunca saiu e não vale mais é descartada aqui. A que já saiu
|
|
9547
|
+
* fica fora da tela, mas na fila, até o servidor dizer o que houve com ela.
|
|
9548
|
+
*/
|
|
9549
|
+
rebuild() {
|
|
9550
|
+
let doc = this.confirmed;
|
|
9551
|
+
for (const seq of [...this.buffer.keys()].sort((a, b) => a - b)) {
|
|
9552
|
+
const envelope2 = this.buffer.get(seq);
|
|
9553
|
+
if (envelope2 === void 0) continue;
|
|
9554
|
+
const verdict = tryApplyEnvelope(doc, envelope2);
|
|
9555
|
+
if (verdict.ok) doc = verdict.doc;
|
|
9556
|
+
}
|
|
9557
|
+
const kept = [];
|
|
9558
|
+
for (const item of this.pending) {
|
|
9559
|
+
const verdict = tryApplyEnvelope(doc, item.envelope);
|
|
9560
|
+
if (verdict.ok) {
|
|
9561
|
+
doc = verdict.doc;
|
|
9562
|
+
kept.push(item);
|
|
9563
|
+
} else if (item.sent) {
|
|
9564
|
+
kept.push(item);
|
|
9565
|
+
} else {
|
|
9566
|
+
this.discard(item.envelope, "not-applicable", verdict.reason);
|
|
9567
|
+
}
|
|
9568
|
+
}
|
|
9569
|
+
this.pending = kept;
|
|
9570
|
+
this.store.replaceDoc(doc.version === this.lastSeq ? doc : { ...doc, version: this.lastSeq });
|
|
9571
|
+
}
|
|
9572
|
+
checkGap() {
|
|
9573
|
+
if (this.buffer.size === 0) {
|
|
9574
|
+
this.clearTimer("gapTimer");
|
|
9575
|
+
return;
|
|
9576
|
+
}
|
|
9577
|
+
if (this.gapTimer !== null) return;
|
|
9578
|
+
this.gapTimer = this.scheduler.setTimeout(() => {
|
|
9579
|
+
this.gapTimer = null;
|
|
9580
|
+
if (this.buffer.size === 0) return;
|
|
9581
|
+
this.stats.gapSyncs += 1;
|
|
9582
|
+
this.requestSync();
|
|
9583
|
+
}, this.gapGraceMs);
|
|
9584
|
+
}
|
|
9585
|
+
// -------------------------------------------------------------- miúdos
|
|
9586
|
+
discard(envelope2, reason, detail) {
|
|
9587
|
+
this.stats.discarded += 1;
|
|
9588
|
+
this.onDiscard?.({ envelope: envelope2, reason, detail });
|
|
9589
|
+
}
|
|
9590
|
+
findPending(opId) {
|
|
9591
|
+
return this.pending.findIndex((item) => item.envelope.id === opId);
|
|
9592
|
+
}
|
|
9593
|
+
clearTimer(name) {
|
|
9594
|
+
const handle = this[name];
|
|
9595
|
+
if (handle === null) return;
|
|
9596
|
+
this.scheduler.clearTimeout(handle);
|
|
9597
|
+
this[name] = null;
|
|
9598
|
+
}
|
|
9599
|
+
};
|
|
9600
|
+
}
|
|
9601
|
+
});
|
|
9602
|
+
|
|
6888
9603
|
// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
|
|
6889
9604
|
import process2 from "process";
|
|
6890
9605
|
|
|
@@ -21172,8 +23887,19 @@ var LoginExpiredError = class extends ApiError {
|
|
|
21172
23887
|
this.name = "LoginExpiredError";
|
|
21173
23888
|
}
|
|
21174
23889
|
};
|
|
23890
|
+
var ServerBusyError = class extends ApiError {
|
|
23891
|
+
constructor(status, waitS, what) {
|
|
23892
|
+
super(
|
|
23893
|
+
status,
|
|
23894
|
+
`O servidor da BePlus est\xE1 ocupado agora (${status === 0 ? "falha de rede" : `HTTP ${status}`} em ${what}). Nada foi alterado por esta chamada. Tente de novo em ${waitS} s, sem repetir em sequ\xEAncia.`
|
|
23895
|
+
);
|
|
23896
|
+
this.waitS = waitS;
|
|
23897
|
+
this.name = "ServerBusyError";
|
|
23898
|
+
}
|
|
23899
|
+
waitS;
|
|
23900
|
+
};
|
|
21175
23901
|
function apiErrorToUserMessage(err) {
|
|
21176
|
-
if (err instanceof LoginExpiredError) return err.message;
|
|
23902
|
+
if (err instanceof LoginExpiredError || err instanceof ServerBusyError) return err.message;
|
|
21177
23903
|
if (err instanceof ApiError) {
|
|
21178
23904
|
const detail = err.message || "";
|
|
21179
23905
|
switch (err.httpStatus) {
|
|
@@ -21533,6 +24259,26 @@ async function fetchWithAuth(cfg, url, init, what) {
|
|
|
21533
24259
|
}
|
|
21534
24260
|
|
|
21535
24261
|
// src/api/client.ts
|
|
24262
|
+
var retryPolicy = {
|
|
24263
|
+
retries: 4,
|
|
24264
|
+
baseMs: 1e3,
|
|
24265
|
+
capMs: 3e4,
|
|
24266
|
+
/** Passou disso esperando, desiste e devolve "tente em N s" ao agente em vez de segurar a tool. */
|
|
24267
|
+
budgetMs: 45e3,
|
|
24268
|
+
random: Math.random,
|
|
24269
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)))
|
|
24270
|
+
};
|
|
24271
|
+
var RETRYABLE = /* @__PURE__ */ new Set([0, 429, 503]);
|
|
24272
|
+
function retryAfterMs(res) {
|
|
24273
|
+
const raw = res.headers.get("retry-after");
|
|
24274
|
+
if (!raw) return null;
|
|
24275
|
+
const secs = Number(raw);
|
|
24276
|
+
if (Number.isFinite(secs)) return Math.max(0, secs * 1e3);
|
|
24277
|
+
const at = Date.parse(raw);
|
|
24278
|
+
return Number.isFinite(at) ? Math.max(0, at - Date.now()) : null;
|
|
24279
|
+
}
|
|
24280
|
+
var costCachePolicy = { ttlMs: 10 * 6e4, capacity: 256, now: () => Date.now() };
|
|
24281
|
+
var costCache = /* @__PURE__ */ new Map();
|
|
21536
24282
|
var BeplusClient = class {
|
|
21537
24283
|
constructor(cfg) {
|
|
21538
24284
|
this.cfg = cfg;
|
|
@@ -21540,23 +24286,63 @@ var BeplusClient = class {
|
|
|
21540
24286
|
cfg;
|
|
21541
24287
|
/** Público para os módulos de rota própria (ex.: Canvas) reaproveitarem auth, timeout e erros. */
|
|
21542
24288
|
async request(method, path, opts = {}) {
|
|
24289
|
+
return (await this.requestMeta(method, path, opts)).data;
|
|
24290
|
+
}
|
|
24291
|
+
/** Igual a `request`, mas devolve status e ETag, e trata 304 como resposta (sem corpo). */
|
|
24292
|
+
async requestMeta(method, path, opts = {}) {
|
|
21543
24293
|
const url = new URL(`${opts.base ?? this.cfg.apiBase}${path}`);
|
|
21544
24294
|
if (opts.query) {
|
|
21545
24295
|
for (const [k, v] of Object.entries(opts.query)) {
|
|
21546
24296
|
if (v !== void 0 && v !== null && v !== "") url.searchParams.set(k, String(v));
|
|
21547
24297
|
}
|
|
21548
24298
|
}
|
|
21549
|
-
const
|
|
21550
|
-
|
|
21551
|
-
|
|
21552
|
-
|
|
21553
|
-
|
|
21554
|
-
|
|
21555
|
-
|
|
21556
|
-
|
|
21557
|
-
|
|
21558
|
-
|
|
21559
|
-
|
|
24299
|
+
const retry = opts.retry ?? method === "GET";
|
|
24300
|
+
const p = retryPolicy;
|
|
24301
|
+
const started = Date.now();
|
|
24302
|
+
for (let attempt = 0; ; attempt++) {
|
|
24303
|
+
let res = null;
|
|
24304
|
+
let failure2 = null;
|
|
24305
|
+
try {
|
|
24306
|
+
res = await fetchWithAuth(
|
|
24307
|
+
this.cfg,
|
|
24308
|
+
url,
|
|
24309
|
+
{
|
|
24310
|
+
method,
|
|
24311
|
+
headers: { ...opts.body ? { "Content-Type": "application/json" } : {}, ...opts.headers },
|
|
24312
|
+
body: opts.body ? JSON.stringify(opts.body) : void 0,
|
|
24313
|
+
timeoutMs: opts.timeoutMs ?? 3e4
|
|
24314
|
+
},
|
|
24315
|
+
path
|
|
24316
|
+
);
|
|
24317
|
+
} catch (e) {
|
|
24318
|
+
if (!(e instanceof ApiError) || e.httpStatus !== 0) throw e;
|
|
24319
|
+
failure2 = e;
|
|
24320
|
+
}
|
|
24321
|
+
const status = res ? res.status : 0;
|
|
24322
|
+
if (!retry || !RETRYABLE.has(status)) {
|
|
24323
|
+
if (failure2) throw failure2;
|
|
24324
|
+
return this.read(res, path);
|
|
24325
|
+
}
|
|
24326
|
+
const step = Math.min(p.capMs, p.baseMs * 2 ** attempt);
|
|
24327
|
+
const asked = res ? retryAfterMs(res) : null;
|
|
24328
|
+
const wait = asked ?? step / 2 + p.random() * (step / 2);
|
|
24329
|
+
if (attempt >= p.retries || asked !== null && asked > p.capMs || Date.now() - started + wait > p.budgetMs) {
|
|
24330
|
+
await res?.body?.cancel().catch(() => {
|
|
24331
|
+
});
|
|
24332
|
+
throw new ServerBusyError(status, Math.max(1, Math.ceil(Math.max(wait, p.baseMs) / 1e3)), path);
|
|
24333
|
+
}
|
|
24334
|
+
await res?.body?.cancel().catch(() => {
|
|
24335
|
+
});
|
|
24336
|
+
await p.sleep(wait);
|
|
24337
|
+
}
|
|
24338
|
+
}
|
|
24339
|
+
async read(res, path) {
|
|
24340
|
+
const etag = res.headers.get("etag");
|
|
24341
|
+
if (res.status === 304) {
|
|
24342
|
+
await res.body?.cancel().catch(() => {
|
|
24343
|
+
});
|
|
24344
|
+
return { status: 304, etag, data: null, bytes: 0 };
|
|
24345
|
+
}
|
|
21560
24346
|
let text;
|
|
21561
24347
|
try {
|
|
21562
24348
|
text = await res.text();
|
|
@@ -21574,7 +24360,8 @@ var BeplusClient = class {
|
|
|
21574
24360
|
const message = json2?.message || (Array.isArray(json2?.error?.formatted) ? json2.error.formatted.join(", ") : void 0) || res.statusText || `HTTP ${res.status}`;
|
|
21575
24361
|
throw new ApiError(res.status, message, json2);
|
|
21576
24362
|
}
|
|
21577
|
-
|
|
24363
|
+
const data = json2 && typeof json2 === "object" && "result" in json2 ? json2.result : json2;
|
|
24364
|
+
return { status: res.status, etag, data, bytes: text.length };
|
|
21578
24365
|
}
|
|
21579
24366
|
startGeneration(body2) {
|
|
21580
24367
|
return this.request("POST", "/generations", { body: body2 });
|
|
@@ -21651,11 +24438,47 @@ var BeplusClient = class {
|
|
|
21651
24438
|
);
|
|
21652
24439
|
return r?.state ?? null;
|
|
21653
24440
|
}
|
|
24441
|
+
// `retry: false` nas leituras de apoio: 503 aqui é "não configurado" e não pode segurar list_models nem check_generation.
|
|
24442
|
+
elevenLabsCatalog(opts = {}) {
|
|
24443
|
+
return this.request("GET", "/elevenlabs/catalog", { timeoutMs: 15e3, ...opts });
|
|
24444
|
+
}
|
|
24445
|
+
elevenLabsVoices(query) {
|
|
24446
|
+
return this.request("GET", "/elevenlabs/voices", { query, timeoutMs: 2e4 });
|
|
24447
|
+
}
|
|
24448
|
+
deleteElevenLabsVoice(id) {
|
|
24449
|
+
return this.request("DELETE", `/elevenlabs/voices/${encodeURIComponent(id)}`, { timeoutMs: 3e4 });
|
|
24450
|
+
}
|
|
24451
|
+
saveElevenLabsVoice(body2) {
|
|
24452
|
+
return this.request("POST", "/elevenlabs/voices/design/save", { body: body2, timeoutMs: 6e4 });
|
|
24453
|
+
}
|
|
24454
|
+
elevenLabsEstimate(body2) {
|
|
24455
|
+
return this.request("POST", "/elevenlabs/estimate", { body: body2, timeoutMs: 6e4 });
|
|
24456
|
+
}
|
|
24457
|
+
// Sem repetição: este POST cobra. Ferramenta longa volta `processing` logo, a rápida segura até a resposta.
|
|
24458
|
+
elevenLabsGenerate(body2) {
|
|
24459
|
+
return this.request("POST", "/elevenlabs/generate", { body: body2, timeoutMs: 18e4 });
|
|
24460
|
+
}
|
|
24461
|
+
elevenLabsJob(id, opts = {}) {
|
|
24462
|
+
return this.request("GET", `/elevenlabs/generations/${encodeURIComponent(id)}`, { timeoutMs: 15e3, ...opts });
|
|
24463
|
+
}
|
|
21654
24464
|
models() {
|
|
21655
24465
|
return this.request("GET", "/models");
|
|
21656
24466
|
}
|
|
24467
|
+
/** Cache por parâmetros: o preço não muda entre chamadas, e o agente estima o mesmo modelo várias vezes. */
|
|
21657
24468
|
calculateCost(query) {
|
|
21658
|
-
|
|
24469
|
+
const normalized = Object.entries(query).filter(([, v]) => v !== void 0 && v !== null && v !== "").map(([k, v]) => [k, String(v)]).sort(([a], [b]) => a.localeCompare(b));
|
|
24470
|
+
const key = `${this.cfg.apiBase}|${JSON.stringify(normalized)}`;
|
|
24471
|
+
const now = costCachePolicy.now();
|
|
24472
|
+
const hit = costCache.get(key);
|
|
24473
|
+
if (hit && (hit.expiresAt === null || hit.expiresAt > now)) return hit.value;
|
|
24474
|
+
const value = this.request("GET", "/calculate-cost", { query });
|
|
24475
|
+
costCache.set(key, { value, expiresAt: null });
|
|
24476
|
+
value.then(
|
|
24477
|
+
() => costCache.set(key, { value, expiresAt: costCachePolicy.now() + costCachePolicy.ttlMs }),
|
|
24478
|
+
() => costCache.delete(key)
|
|
24479
|
+
);
|
|
24480
|
+
while (costCache.size > costCachePolicy.capacity) costCache.delete(costCache.keys().next().value);
|
|
24481
|
+
return value;
|
|
21659
24482
|
}
|
|
21660
24483
|
/** `billing: 'personal'` pula o budget do projeto ativo no preview do saldo. */
|
|
21661
24484
|
balance(billing) {
|
|
@@ -21754,6 +24577,9 @@ import { readFile as readFile2, stat as stat2 } from "fs/promises";
|
|
|
21754
24577
|
import { lookup } from "dns/promises";
|
|
21755
24578
|
import { isIP } from "net";
|
|
21756
24579
|
var remote = false;
|
|
24580
|
+
function isRemoteMode() {
|
|
24581
|
+
return remote;
|
|
24582
|
+
}
|
|
21757
24583
|
function refuseLocalPath(ref) {
|
|
21758
24584
|
if (!remote) return;
|
|
21759
24585
|
throw new ApiError(
|
|
@@ -22032,6 +24858,11 @@ async function uploadBytes(cfg, file) {
|
|
|
22032
24858
|
}
|
|
22033
24859
|
return fileUrl;
|
|
22034
24860
|
}
|
|
24861
|
+
async function toStorageUrl(cfg, ref) {
|
|
24862
|
+
if (!isRemoteRef(ref)) return uploadBytes(cfg, await loadLocal(ref));
|
|
24863
|
+
if (new URL(ref).host === BEPLUS_STORAGE_HOST) return ref;
|
|
24864
|
+
return uploadBytes(cfg, await loadRemote(ref));
|
|
24865
|
+
}
|
|
22035
24866
|
async function uploadFile(cfg, ref) {
|
|
22036
24867
|
return uploadBytes(cfg, await loadLocal(ref));
|
|
22037
24868
|
}
|
|
@@ -22327,6 +25158,19 @@ var ASPECT_RATIOS = ["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3", "4:5", "
|
|
|
22327
25158
|
var VIDEO_ASPECT_RATIOS = [...ASPECT_RATIOS, "adaptive"];
|
|
22328
25159
|
var IMAGE_RESOLUTIONS = ["1K", "2K", "4K"];
|
|
22329
25160
|
var VIDEO_RESOLUTIONS = ["480p", "720p", "1080p", "4K"];
|
|
25161
|
+
var ELEVENLABS_TOOLS = [
|
|
25162
|
+
"tts",
|
|
25163
|
+
"dialogue",
|
|
25164
|
+
"sfx",
|
|
25165
|
+
"isolate",
|
|
25166
|
+
"voice_change",
|
|
25167
|
+
"transcribe",
|
|
25168
|
+
"align",
|
|
25169
|
+
"music",
|
|
25170
|
+
"stems",
|
|
25171
|
+
"video_music",
|
|
25172
|
+
"voice_design"
|
|
25173
|
+
];
|
|
22330
25174
|
var DEFAULTS = {
|
|
22331
25175
|
imageModel: "google/nano-banana-2.1",
|
|
22332
25176
|
imageAspect: "1:1",
|
|
@@ -22585,6 +25429,433 @@ function formatToolResult(state, fullWords) {
|
|
|
22585
25429
|
return lines.join("\n") || "(sem resultado)";
|
|
22586
25430
|
}
|
|
22587
25431
|
|
|
25432
|
+
// src/tools/elevenlabs.ts
|
|
25433
|
+
import { randomUUID } from "crypto";
|
|
25434
|
+
var elevenLabsPolling = {
|
|
25435
|
+
intervalMs: 3e3,
|
|
25436
|
+
budgetMs: 9e4,
|
|
25437
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, ms))
|
|
25438
|
+
};
|
|
25439
|
+
var MAX_TEXT_CHARS = 2e4;
|
|
25440
|
+
var SITE_ONLY_TOOLS = /* @__PURE__ */ new Set(["dub", "voice_clone"]);
|
|
25441
|
+
var SITE_ONLY_LABEL = "s\xF3 no site da BePlus, na aba \xC1udio do IA Lab";
|
|
25442
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
25443
|
+
var DESTINATION_NOTE = " Vai para o cliente e projeto ativos: confirme o destino com o usu\xE1rio antes (list_clients, list_projects).";
|
|
25444
|
+
var COST_NOTE = " Gasta diamantes; dry_run: true mostra o custo sem gastar.";
|
|
25445
|
+
var SOURCE_HELP = "Arquivo local (s\xF3 no stdio), URL ou id de uma gera\xE7\xE3o sua. Arquivo e URL de fora sobem para a BePlus antes (at\xE9 95 MB; acima disso, s\xF3 pelo site).";
|
|
25446
|
+
var TOO_LARGE_MESSAGE = "Este arquivo passa de 95 MB, o limite de envio por aqui. Use a mesma ferramenta no site da BePlus, na aba \xC1udio do IA Lab, que aceita arquivos maiores.";
|
|
25447
|
+
var COMMON_FIELDS = {
|
|
25448
|
+
project: external_exports.string().max(64).optional().describe("Projeto (uuid ou code curto). Omita para usar o projeto ativo."),
|
|
25449
|
+
billing: external_exports.enum(["personal"]).optional().describe('"personal" cobra do seu saldo pessoal e ignora o projeto, mesmo o ativo. Incompat\xEDvel com project.'),
|
|
25450
|
+
dry_run: external_exports.boolean().optional().describe("true devolve o custo em diamantes sem gerar nem gastar.")
|
|
25451
|
+
};
|
|
25452
|
+
function contractMessage(e) {
|
|
25453
|
+
if (!(e instanceof ApiError)) return void 0;
|
|
25454
|
+
const body2 = e.body;
|
|
25455
|
+
const message = body2?.error?.message ?? body2?.result?.error?.message;
|
|
25456
|
+
return typeof message === "string" && message ? message : void 0;
|
|
25457
|
+
}
|
|
25458
|
+
async function failure(client, e) {
|
|
25459
|
+
const ready = contractMessage(e);
|
|
25460
|
+
const raw = ready ?? (e instanceof Error ? e.message : "");
|
|
25461
|
+
if (isTeamGatingError(raw)) return errorResult(await buildPickProjectMessage(client));
|
|
25462
|
+
const text = ready ?? apiErrorToUserMessage(e);
|
|
25463
|
+
return errorResult(isBudgetBlockedError(raw) ? `${text}
|
|
25464
|
+
${BUDGET_BLOCKED_GUIDANCE}` : text);
|
|
25465
|
+
}
|
|
25466
|
+
var VOICE_ORIGIN = { premade: "padr\xE3o", library: "biblioteca", mine: "sua" };
|
|
25467
|
+
function voiceLine(v) {
|
|
25468
|
+
const traits = [v.language, v.gender, v.accent].filter(Boolean).join(", ");
|
|
25469
|
+
const description = v.description ? ` | ${v.description.length > 110 ? `${v.description.slice(0, 107)}...` : v.description}` : "";
|
|
25470
|
+
return `${v.id} | ${v.name} | ${VOICE_ORIGIN[v.source]}${traits ? ` | ${traits}` : ""}${description}`;
|
|
25471
|
+
}
|
|
25472
|
+
function jobFooter(job) {
|
|
25473
|
+
const balance = job.balance === void 0 ? "" : ` \xB7 Saldo: ${job.balance} \u{1F48E}`;
|
|
25474
|
+
return `Gera\xE7\xE3o: ${job.generationId}
|
|
25475
|
+
Custo: ${job.diamonds} \u{1F48E}${balance}`;
|
|
25476
|
+
}
|
|
25477
|
+
function formatJob(job) {
|
|
25478
|
+
if (job.status === "failed") return errorResult(`${job.error?.message ?? "A gera\xE7\xE3o falhou."}
|
|
25479
|
+
${jobFooter(job)}`);
|
|
25480
|
+
if (job.status === "processing") {
|
|
25481
|
+
return textResult(
|
|
25482
|
+
`\u23F3 Ainda em processamento. N\xE3o gere de novo: use check_generation com o id abaixo.
|
|
25483
|
+
${jobFooter(job)}`
|
|
25484
|
+
);
|
|
25485
|
+
}
|
|
25486
|
+
const out = job.output ?? {};
|
|
25487
|
+
const lines = [`\u2705 Pronto (${job.tool}).`];
|
|
25488
|
+
for (const f of out.files ?? []) {
|
|
25489
|
+
const duration3 = f.durationSec === void 0 ? "" : ` (${f.durationSec.toFixed(1)}s)`;
|
|
25490
|
+
lines.push(`${f.label ? `${f.label}: ` : ""}${f.url}${duration3}`);
|
|
25491
|
+
}
|
|
25492
|
+
if (out.text) {
|
|
25493
|
+
const cut = out.text.length > MAX_TEXT_CHARS;
|
|
25494
|
+
lines.push(cut ? `${out.text.slice(0, MAX_TEXT_CHARS)}
|
|
25495
|
+
[texto cortado em ${MAX_TEXT_CHARS} caracteres]` : out.text);
|
|
25496
|
+
}
|
|
25497
|
+
if (out.words?.length) {
|
|
25498
|
+
const speakers = new Set(out.words.map((w) => w.speaker).filter(Boolean)).size;
|
|
25499
|
+
lines.push(`${out.words.length} palavras com tempo${speakers ? `, ${speakers} locutores` : ""}.`);
|
|
25500
|
+
}
|
|
25501
|
+
if (out.srtUrl) lines.push(`Legenda: ${out.srtUrl}`);
|
|
25502
|
+
if (out.previews?.length) {
|
|
25503
|
+
lines.push("Pr\xE9vias (id | \xE1udio):", ...out.previews.map((p) => `${p.id} | ${p.url}`));
|
|
25504
|
+
lines.push("Mostre as pr\xE9vias ao usu\xE1rio. A escolhida vira voz com elevenlabs_voice_design_save.");
|
|
25505
|
+
}
|
|
25506
|
+
if (out.voice) lines.push(`Voz: ${voiceLine(out.voice)}`);
|
|
25507
|
+
lines.push(jobFooter(job));
|
|
25508
|
+
return textResult(lines.join("\n"));
|
|
25509
|
+
}
|
|
25510
|
+
async function waitForJob(client, first) {
|
|
25511
|
+
const { intervalMs, budgetMs, sleep: sleep4 } = elevenLabsPolling;
|
|
25512
|
+
let job = first;
|
|
25513
|
+
for (let waited = 0; job.status === "processing" && waited < budgetMs; waited += intervalMs) {
|
|
25514
|
+
await sleep4(intervalMs);
|
|
25515
|
+
try {
|
|
25516
|
+
job = await client.elevenLabsJob(first.generationId);
|
|
25517
|
+
} catch {
|
|
25518
|
+
return job;
|
|
25519
|
+
}
|
|
25520
|
+
}
|
|
25521
|
+
return job;
|
|
25522
|
+
}
|
|
25523
|
+
async function toSource(cfg, ref) {
|
|
25524
|
+
if (UUID.test(ref)) return { generationId: ref };
|
|
25525
|
+
try {
|
|
25526
|
+
return { fileUrl: await toStorageUrl(cfg, ref) };
|
|
25527
|
+
} catch (e) {
|
|
25528
|
+
if (e instanceof ApiError && e.httpStatus === 413) throw new ApiError(413, TOO_LARGE_MESSAGE);
|
|
25529
|
+
throw e;
|
|
25530
|
+
}
|
|
25531
|
+
}
|
|
25532
|
+
function uploadedHint(body2) {
|
|
25533
|
+
const url = body2.source?.fileUrl;
|
|
25534
|
+
return url ? `
|
|
25535
|
+
Arquivo na BePlus: ${url}. Use esta URL em source para n\xE3o subir de novo.` : "";
|
|
25536
|
+
}
|
|
25537
|
+
async function estimate(client, body2) {
|
|
25538
|
+
const res = await client.elevenLabsEstimate(body2);
|
|
25539
|
+
const duration3 = res.durationSec === void 0 ? "" : ` para ${res.durationSec.toFixed(1)}s`;
|
|
25540
|
+
return textResult(`Custo estimado: ${res.diamonds} \u{1F48E}${duration3}. Nada foi gerado nem cobrado.${uploadedHint(body2)}`);
|
|
25541
|
+
}
|
|
25542
|
+
async function generate(client, body2) {
|
|
25543
|
+
let job;
|
|
25544
|
+
try {
|
|
25545
|
+
job = await client.elevenLabsGenerate({ ...body2, idempotencyKey: randomUUID() });
|
|
25546
|
+
} catch (e) {
|
|
25547
|
+
if (e instanceof ApiError && (e.httpStatus === 0 || e.httpStatus === 408)) {
|
|
25548
|
+
return errorResult(
|
|
25549
|
+
"A resposta n\xE3o chegou, ent\xE3o a gera\xE7\xE3o pode ter come\xE7ado e sido cobrada. N\xE3o repita: confira em list_generations antes."
|
|
25550
|
+
);
|
|
25551
|
+
}
|
|
25552
|
+
throw e;
|
|
25553
|
+
}
|
|
25554
|
+
return formatJob(await waitForJob(client, job));
|
|
25555
|
+
}
|
|
25556
|
+
async function estimateElevenLabsModel(client, cfg, model, params, file) {
|
|
25557
|
+
const [, tool, variant] = model.split("/");
|
|
25558
|
+
if (!ELEVENLABS_TOOLS.includes(tool ?? "")) {
|
|
25559
|
+
return errorResult(`Ferramenta desconhecida em "${model}". Use elevenlabs/<ferramenta>: ${ELEVENLABS_TOOLS.join(", ")}.`);
|
|
25560
|
+
}
|
|
25561
|
+
try {
|
|
25562
|
+
const body2 = { ...params, tool };
|
|
25563
|
+
if (variant) body2.model = variant;
|
|
25564
|
+
if (file) body2.source = await toSource(cfg, file);
|
|
25565
|
+
return await estimate(client, body2);
|
|
25566
|
+
} catch (e) {
|
|
25567
|
+
return failure(client, e);
|
|
25568
|
+
}
|
|
25569
|
+
}
|
|
25570
|
+
function elevenLabsCatalogBlock(catalog) {
|
|
25571
|
+
if (!catalog?.enabled) return "";
|
|
25572
|
+
const lines = catalog.tools.filter((t) => t.available).map((t) => {
|
|
25573
|
+
if (SITE_ONLY_TOOLS.has(t.tool)) return `\u2022 ${t.label}: ${SITE_ONLY_LABEL}.`;
|
|
25574
|
+
const models = t.models?.length ? ` Modelos: ${t.models.map((m) => m.id).join(", ")}.` : "";
|
|
25575
|
+
return `\u2022 elevenlabs_${t.tool}: ${t.label}, ${t.diamondsPerUnitHint}.${models}`;
|
|
25576
|
+
});
|
|
25577
|
+
return lines.length ? `
|
|
25578
|
+
|
|
25579
|
+
ElevenLabs (detalhes e limites em elevenlabs_catalog):
|
|
25580
|
+
${lines.join("\n")}` : "";
|
|
25581
|
+
}
|
|
25582
|
+
function registerElevenLabsTools(server, client, cfg) {
|
|
25583
|
+
function spendTool(name, title, description, shape, build2) {
|
|
25584
|
+
server.registerTool(
|
|
25585
|
+
name,
|
|
25586
|
+
{
|
|
25587
|
+
title,
|
|
25588
|
+
description: description + COST_NOTE + DESTINATION_NOTE,
|
|
25589
|
+
inputSchema: { ...shape, ...COMMON_FIELDS },
|
|
25590
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
|
|
25591
|
+
},
|
|
25592
|
+
(async (args) => {
|
|
25593
|
+
try {
|
|
25594
|
+
const body2 = compact({
|
|
25595
|
+
...await build2(args),
|
|
25596
|
+
project: resolveProjectArg(args.project, args.billing, cfg.activeProject),
|
|
25597
|
+
billing: args.billing
|
|
25598
|
+
});
|
|
25599
|
+
return await (args.dry_run ? estimate(client, body2) : generate(client, body2));
|
|
25600
|
+
} catch (e) {
|
|
25601
|
+
return failure(client, e);
|
|
25602
|
+
}
|
|
25603
|
+
})
|
|
25604
|
+
);
|
|
25605
|
+
}
|
|
25606
|
+
const modelField = (example) => external_exports.string().min(1).describe(`Id do modelo, ex.: ${example}. A lista sai de elevenlabs_catalog.`);
|
|
25607
|
+
const voiceField = external_exports.string().min(1).describe("Id de uma voz de elevenlabs_list_voices. Outra voz \xE9 recusada.");
|
|
25608
|
+
const sourceField = external_exports.string().min(1).describe(SOURCE_HELP);
|
|
25609
|
+
server.registerTool(
|
|
25610
|
+
"elevenlabs_catalog",
|
|
25611
|
+
{
|
|
25612
|
+
title: "ElevenLabs: ferramentas e modelos",
|
|
25613
|
+
description: "Mostra o que a ElevenLabs oferece agora na BePlus: ferramentas ligadas, modelos, pre\xE7o aproximado e limites. Chame antes da primeira gera\xE7\xE3o para escolher o model. Somente leitura, sem custo.",
|
|
25614
|
+
inputSchema: {},
|
|
25615
|
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
|
25616
|
+
},
|
|
25617
|
+
async () => {
|
|
25618
|
+
try {
|
|
25619
|
+
const catalog = await client.elevenLabsCatalog();
|
|
25620
|
+
if (!catalog.enabled) return textResult("A ElevenLabs est\xE1 desligada na plataforma agora.");
|
|
25621
|
+
const lines = catalog.tools.map((t) => {
|
|
25622
|
+
if (SITE_ONLY_TOOLS.has(t.tool)) return `${t.label}: ${SITE_ONLY_LABEL}. N\xE3o h\xE1 tool para isso aqui.`;
|
|
25623
|
+
const head = `elevenlabs_${t.tool} | ${t.label} | ${t.available ? t.diamondsPerUnitHint : "indispon\xEDvel agora"}`;
|
|
25624
|
+
const models = (t.models ?? []).map((m) => ` ${m.id}: ${m.label}. ${m.description}`);
|
|
25625
|
+
return [head, ` ${t.description}`, ` Limites: ${JSON.stringify(t.limits)}`, ...models].join("\n");
|
|
25626
|
+
});
|
|
25627
|
+
return textResult(lines.join("\n"));
|
|
25628
|
+
} catch (e) {
|
|
25629
|
+
return failure(client, e);
|
|
25630
|
+
}
|
|
25631
|
+
}
|
|
25632
|
+
);
|
|
25633
|
+
server.registerTool(
|
|
25634
|
+
"elevenlabs_list_voices",
|
|
25635
|
+
{
|
|
25636
|
+
title: "ElevenLabs: listar vozes",
|
|
25637
|
+
description: "Lista as vozes que voc\xEA pode usar nas ferramentas elevenlabs_*: as da biblioteca, as padr\xE3o e as que voc\xEA criou. N\xE3o serve para generate_audio, que tem vozes pr\xF3prias. Somente leitura, sem custo.",
|
|
25638
|
+
inputSchema: {
|
|
25639
|
+
search: external_exports.string().max(100).optional().describe("Texto livre: nome, descri\xE7\xE3o, sotaque."),
|
|
25640
|
+
language: external_exports.string().max(12).optional().describe("Idioma, ex.: pt, en."),
|
|
25641
|
+
gender: external_exports.string().max(20).optional(),
|
|
25642
|
+
page: external_exports.number().int().min(1).optional().describe("Padr\xE3o 1.")
|
|
25643
|
+
},
|
|
25644
|
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
|
25645
|
+
},
|
|
25646
|
+
async (args) => {
|
|
25647
|
+
try {
|
|
25648
|
+
const res = await client.elevenLabsVoices(compact(args));
|
|
25649
|
+
if (!res.voices.length) return textResult("Nenhuma voz encontrada com esses filtros.");
|
|
25650
|
+
const more = res.hasMore ? `
|
|
25651
|
+
Use page=${res.page + 1} para ver mais.` : "";
|
|
25652
|
+
return textResult(`Vozes, p\xE1gina ${res.page} (id | nome | origem | detalhes):
|
|
25653
|
+
${res.voices.map(voiceLine).join("\n")}${more}`);
|
|
25654
|
+
} catch (e) {
|
|
25655
|
+
return failure(client, e);
|
|
25656
|
+
}
|
|
25657
|
+
}
|
|
25658
|
+
);
|
|
25659
|
+
server.registerTool(
|
|
25660
|
+
"elevenlabs_delete_voice",
|
|
25661
|
+
{
|
|
25662
|
+
title: "ElevenLabs: apagar voz sua",
|
|
25663
|
+
description: "DESTRUTIVO e sem volta: apaga uma voz que voc\xEA criou e libera a vaga. \xC1udios j\xE1 gerados continuam tocando. N\xE3o devolve diamantes. Confirme com o usu\xE1rio antes.",
|
|
25664
|
+
inputSchema: { id: external_exports.string().min(1).describe('Id da voz em elevenlabs_list_voices, com origem "sua".') },
|
|
25665
|
+
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }
|
|
25666
|
+
},
|
|
25667
|
+
async ({ id }) => {
|
|
25668
|
+
try {
|
|
25669
|
+
await client.deleteElevenLabsVoice(id);
|
|
25670
|
+
return textResult(`\u2705 Voz ${id} apagada.`);
|
|
25671
|
+
} catch (e) {
|
|
25672
|
+
return failure(client, e);
|
|
25673
|
+
}
|
|
25674
|
+
}
|
|
25675
|
+
);
|
|
25676
|
+
server.registerTool(
|
|
25677
|
+
"elevenlabs_voice_design_save",
|
|
25678
|
+
{
|
|
25679
|
+
title: "ElevenLabs: salvar voz criada",
|
|
25680
|
+
description: "Transforma uma pr\xE9via de elevenlabs_voice_design em voz sua, para usar nas ferramentas elevenlabs_*. Ocupa uma vaga de voz: salve s\xF3 a pr\xE9via que o usu\xE1rio escolheu.",
|
|
25681
|
+
inputSchema: {
|
|
25682
|
+
preview_id: external_exports.string().min(1).describe("Id da pr\xE9via escolhida."),
|
|
25683
|
+
name: external_exports.string().min(1).max(40).describe("Nome da voz.")
|
|
25684
|
+
},
|
|
25685
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
|
|
25686
|
+
},
|
|
25687
|
+
async ({ preview_id, name }) => {
|
|
25688
|
+
try {
|
|
25689
|
+
const voice = await client.saveElevenLabsVoice({ previewId: preview_id, name });
|
|
25690
|
+
return textResult(`\u2705 Voz salva.
|
|
25691
|
+
${voiceLine(voice)}`);
|
|
25692
|
+
} catch (e) {
|
|
25693
|
+
return failure(client, e);
|
|
25694
|
+
}
|
|
25695
|
+
}
|
|
25696
|
+
);
|
|
25697
|
+
spendTool(
|
|
25698
|
+
"elevenlabs_tts",
|
|
25699
|
+
"ElevenLabs: texto em fala",
|
|
25700
|
+
"Narra\xE7\xE3o com uma voz s\xF3, com a qualidade da ElevenLabs. Para duas ou mais vozes conversando use elevenlabs_dialogue. Para o TTS do Gemini e o SeedAudio use generate_audio.",
|
|
25701
|
+
{
|
|
25702
|
+
text: external_exports.string().min(1).describe("Texto a falar. O teto depende do modelo."),
|
|
25703
|
+
voice: voiceField,
|
|
25704
|
+
model: modelField("eleven_v4"),
|
|
25705
|
+
language: external_exports.string().max(12).optional().describe("Idioma do texto, ex.: pt."),
|
|
25706
|
+
stability: external_exports.number().min(0).max(1).optional(),
|
|
25707
|
+
similarity: external_exports.number().min(0).max(1).optional(),
|
|
25708
|
+
style: external_exports.number().min(0).max(1).optional().describe("N\xE3o vale nos modelos eleven_v4."),
|
|
25709
|
+
speed: external_exports.number().positive().optional().describe("N\xE3o vale nos modelos eleven_v4.")
|
|
25710
|
+
},
|
|
25711
|
+
({ text, voice, model, language, stability, similarity, style, speed }) => {
|
|
25712
|
+
if (model.startsWith("eleven_v4") && (style !== void 0 || speed !== void 0)) {
|
|
25713
|
+
throw new Error("Os modelos eleven_v4 n\xE3o aceitam style nem speed. Tire esses campos ou troque o modelo.");
|
|
25714
|
+
}
|
|
25715
|
+
const settings = compact({ stability, similarity, style, speed });
|
|
25716
|
+
return { tool: "tts", text, voice, model, language, settings: Object.keys(settings).length ? settings : void 0 };
|
|
25717
|
+
}
|
|
25718
|
+
);
|
|
25719
|
+
spendTool(
|
|
25720
|
+
"elevenlabs_dialogue",
|
|
25721
|
+
"ElevenLabs: di\xE1logo",
|
|
25722
|
+
"Conversa entre duas ou mais vozes num \xE1udio s\xF3, na ordem das falas. Para uma voz s\xF3 use elevenlabs_tts.",
|
|
25723
|
+
{
|
|
25724
|
+
lines: external_exports.array(external_exports.object({ voice: voiceField, text: external_exports.string().min(1) })).min(2).describe("Falas em ordem, cada uma com a sua voz. At\xE9 2.000 caracteres somando todas."),
|
|
25725
|
+
model: modelField("eleven_v3")
|
|
25726
|
+
},
|
|
25727
|
+
({ lines, model }) => ({ tool: "dialogue", lines, model })
|
|
25728
|
+
);
|
|
25729
|
+
spendTool(
|
|
25730
|
+
"elevenlabs_sfx",
|
|
25731
|
+
"ElevenLabs: efeito sonoro",
|
|
25732
|
+
"Cria um efeito sonoro a partir de uma descri\xE7\xE3o (porta batendo, chuva, whoosh). Para trilha musical use elevenlabs_music.",
|
|
25733
|
+
{
|
|
25734
|
+
text: external_exports.string().min(1).describe("Descri\xE7\xE3o do som."),
|
|
25735
|
+
model: modelField("eleven_text_to_sound_v2"),
|
|
25736
|
+
duration_sec: external_exports.number().positive().optional().describe("De 0,5 a 30 s. Omita para o modelo decidir."),
|
|
25737
|
+
loop: external_exports.boolean().optional().describe("true faz o som emendar sem corte."),
|
|
25738
|
+
prompt_influence: external_exports.number().min(0).max(1).optional().describe("Quanto seguir a descri\xE7\xE3o ao p\xE9 da letra.")
|
|
25739
|
+
},
|
|
25740
|
+
({ text, model, duration_sec, loop, prompt_influence }) => ({
|
|
25741
|
+
tool: "sfx",
|
|
25742
|
+
text,
|
|
25743
|
+
model,
|
|
25744
|
+
durationSec: duration_sec,
|
|
25745
|
+
loop,
|
|
25746
|
+
promptInfluence: prompt_influence
|
|
25747
|
+
})
|
|
25748
|
+
);
|
|
25749
|
+
spendTool(
|
|
25750
|
+
"elevenlabs_isolate",
|
|
25751
|
+
"ElevenLabs: isolar voz",
|
|
25752
|
+
"Tira ru\xEDdo e fundo de uma grava\xE7\xE3o e deixa s\xF3 a voz. Para separar instrumentos de uma m\xFAsica use elevenlabs_stems.",
|
|
25753
|
+
{ source: sourceField },
|
|
25754
|
+
async ({ source }) => ({ tool: "isolate", source: await toSource(cfg, source) })
|
|
25755
|
+
);
|
|
25756
|
+
spendTool(
|
|
25757
|
+
"elevenlabs_voice_change",
|
|
25758
|
+
"ElevenLabs: trocar a voz",
|
|
25759
|
+
"Refala uma grava\xE7\xE3o com outra voz, mantendo ritmo e emo\xE7\xE3o. Use s\xF3 em grava\xE7\xE3o que o usu\xE1rio pode alterar.",
|
|
25760
|
+
{
|
|
25761
|
+
source: sourceField,
|
|
25762
|
+
voice: voiceField,
|
|
25763
|
+
model: external_exports.string().min(1).optional().describe("Id do modelo, ex.: eleven_multilingual_sts_v2."),
|
|
25764
|
+
remove_noise: external_exports.boolean().optional().describe("true limpa o ru\xEDdo da grava\xE7\xE3o antes.")
|
|
25765
|
+
},
|
|
25766
|
+
async ({ source, voice, model, remove_noise }) => ({
|
|
25767
|
+
tool: "voice_change",
|
|
25768
|
+
source: await toSource(cfg, source),
|
|
25769
|
+
voice,
|
|
25770
|
+
model,
|
|
25771
|
+
removeNoise: remove_noise
|
|
25772
|
+
})
|
|
25773
|
+
);
|
|
25774
|
+
spendTool(
|
|
25775
|
+
"elevenlabs_transcribe",
|
|
25776
|
+
"ElevenLabs: transcrever",
|
|
25777
|
+
"Transforma \xE1udio ou v\xEDdeo em texto, com tempo por palavra e legenda. Se j\xE1 tem o texto e s\xF3 quer o tempo, use elevenlabs_align. Reuni\xE3o gravada da equipe j\xE1 est\xE1 em search_calls.",
|
|
25778
|
+
{
|
|
25779
|
+
source: sourceField,
|
|
25780
|
+
language: external_exports.string().max(12).optional().describe("Idioma falado. Omita para detectar."),
|
|
25781
|
+
diarize: external_exports.boolean().optional().describe("true separa quem falou o qu\xEA."),
|
|
25782
|
+
num_speakers: external_exports.number().int().min(1).optional().describe("Quantas pessoas falam, se souber."),
|
|
25783
|
+
audio_events: external_exports.boolean().optional().describe("true marca risos, palmas e outros sons."),
|
|
25784
|
+
keyterms: external_exports.array(external_exports.string().min(1)).optional().describe("Nomes e termos dif\xEDceis para acertar a grafia.")
|
|
25785
|
+
},
|
|
25786
|
+
async ({ source, language, diarize, num_speakers, audio_events, keyterms }) => ({
|
|
25787
|
+
tool: "transcribe",
|
|
25788
|
+
source: await toSource(cfg, source),
|
|
25789
|
+
language,
|
|
25790
|
+
diarize,
|
|
25791
|
+
numSpeakers: num_speakers,
|
|
25792
|
+
audioEvents: audio_events,
|
|
25793
|
+
keyterms
|
|
25794
|
+
})
|
|
25795
|
+
);
|
|
25796
|
+
spendTool(
|
|
25797
|
+
"elevenlabs_align",
|
|
25798
|
+
"ElevenLabs: alinhar texto ao \xE1udio",
|
|
25799
|
+
"Recebe o \xE1udio e o texto j\xE1 pronto e devolve o tempo de cada palavra, para legenda exata. Sem o texto, use elevenlabs_transcribe.",
|
|
25800
|
+
{ source: sourceField, text: external_exports.string().min(1).describe("Texto exato do que \xE9 falado.") },
|
|
25801
|
+
async ({ source, text }) => ({ tool: "align", source: await toSource(cfg, source), text })
|
|
25802
|
+
);
|
|
25803
|
+
spendTool(
|
|
25804
|
+
"elevenlabs_music",
|
|
25805
|
+
"ElevenLabs: m\xFAsica",
|
|
25806
|
+
"Cria m\xFAsica a partir de uma descri\xE7\xE3o, com letra ou instrumental. Para Suno use generate_music. Para trilha casada com um v\xEDdeo use elevenlabs_video_music.",
|
|
25807
|
+
{
|
|
25808
|
+
prompt: external_exports.string().min(1).describe("Estilo, clima e instrumentos."),
|
|
25809
|
+
model: external_exports.string().min(1).optional().describe("Id do modelo. Omita para o padr\xE3o."),
|
|
25810
|
+
duration_sec: external_exports.number().min(3).optional().describe("Dura\xE7\xE3o em segundos, m\xEDnimo 3."),
|
|
25811
|
+
instrumental: external_exports.boolean().optional(),
|
|
25812
|
+
lyrics: external_exports.string().min(1).optional().describe("Letra pr\xF3pria.")
|
|
25813
|
+
},
|
|
25814
|
+
({ prompt, model, duration_sec, instrumental, lyrics }) => ({
|
|
25815
|
+
tool: "music",
|
|
25816
|
+
prompt,
|
|
25817
|
+
model,
|
|
25818
|
+
durationSec: duration_sec,
|
|
25819
|
+
instrumental,
|
|
25820
|
+
lyrics
|
|
25821
|
+
})
|
|
25822
|
+
);
|
|
25823
|
+
spendTool(
|
|
25824
|
+
"elevenlabs_stems",
|
|
25825
|
+
"ElevenLabs: separar faixas",
|
|
25826
|
+
"Separa uma m\xFAsica em faixas (voz, bateria, baixo e outras). Para limpar uma fala gravada use elevenlabs_isolate.",
|
|
25827
|
+
{ source: sourceField },
|
|
25828
|
+
async ({ source }) => ({ tool: "stems", source: await toSource(cfg, source) })
|
|
25829
|
+
);
|
|
25830
|
+
spendTool(
|
|
25831
|
+
"elevenlabs_video_music",
|
|
25832
|
+
"ElevenLabs: trilha para v\xEDdeo",
|
|
25833
|
+
"Cria trilha que acompanha um v\xEDdeo existente. Para m\xFAsica sem v\xEDdeo use elevenlabs_music.",
|
|
25834
|
+
{
|
|
25835
|
+
source: sourceField,
|
|
25836
|
+
description: external_exports.string().min(1).optional().describe("Clima desejado."),
|
|
25837
|
+
add_sfx: external_exports.boolean().optional().describe("true acrescenta efeitos sonoros.")
|
|
25838
|
+
},
|
|
25839
|
+
async ({ source, description, add_sfx }) => ({
|
|
25840
|
+
tool: "video_music",
|
|
25841
|
+
source: await toSource(cfg, source),
|
|
25842
|
+
description,
|
|
25843
|
+
addSfx: add_sfx
|
|
25844
|
+
})
|
|
25845
|
+
);
|
|
25846
|
+
spendTool(
|
|
25847
|
+
"elevenlabs_voice_design",
|
|
25848
|
+
"ElevenLabs: criar voz por descri\xE7\xE3o",
|
|
25849
|
+
"Gera pr\xE9vias de uma voz nova a partir de uma descri\xE7\xE3o. N\xE3o cria a voz ainda: mostre as pr\xE9vias e salve a escolhida com elevenlabs_voice_design_save. Para vozes do Gemini use design_voice.",
|
|
25850
|
+
{
|
|
25851
|
+
description: external_exports.string().min(20).describe("Idade, timbre, sotaque e jeito de falar. M\xEDnimo 20 caracteres."),
|
|
25852
|
+
text: external_exports.string().min(1).optional().describe("Frase que as pr\xE9vias v\xE3o falar."),
|
|
25853
|
+
model: external_exports.string().min(1).optional().describe("Id do modelo. Omita para o padr\xE3o.")
|
|
25854
|
+
},
|
|
25855
|
+
({ description, text, model }) => ({ tool: "voice_design", description, text, model })
|
|
25856
|
+
);
|
|
25857
|
+
}
|
|
25858
|
+
|
|
22588
25859
|
// src/tools/generation.ts
|
|
22589
25860
|
var IMAGE_BUDGET_MS = 9e4;
|
|
22590
25861
|
var VIDEO_BUDGET_MS = 12e4;
|
|
@@ -23117,13 +26388,15 @@ ${BUDGET_BLOCKED_GUIDANCE}`);
|
|
|
23117
26388
|
"check_generation",
|
|
23118
26389
|
{
|
|
23119
26390
|
title: "Checar gera\xE7\xE3o",
|
|
23120
|
-
description: "Consulta o status de uma gera\xE7\xE3o ass\xEDncrona (imagem
|
|
26391
|
+
description: "Consulta o status de uma gera\xE7\xE3o ass\xEDncrona (imagem, v\xEDdeo ou ElevenLabs) pelo id. Use depois de generate_video, de um generate_image que estourou o tempo ou de uma elevenlabs_* em processamento. Retorna status, progresso e (quando pronto) as URLs.",
|
|
23121
26392
|
inputSchema: {
|
|
23122
|
-
generation_id: external_exports.string().min(1).describe("O id retornado por generate_image
|
|
26393
|
+
generation_id: external_exports.string().min(1).describe("O id retornado por generate_image, generate_video ou elevenlabs_*.")
|
|
23123
26394
|
}
|
|
23124
26395
|
},
|
|
23125
26396
|
async ({ generation_id }) => {
|
|
23126
26397
|
try {
|
|
26398
|
+
const job = await client.elevenLabsJob(generation_id, { retry: false }).catch(() => null);
|
|
26399
|
+
if (job?.generationId) return formatJob(job);
|
|
23127
26400
|
const status = await client.getStatus(generation_id);
|
|
23128
26401
|
if (status.status === "completed") {
|
|
23129
26402
|
const urls = outputUrls(status);
|
|
@@ -23199,6 +26472,7 @@ ${list}${flagsLine(status)}${draftHint}` }, ...blocks] };
|
|
|
23199
26472
|
await client.cancel(generation_id);
|
|
23200
26473
|
return textResult(`\u2705 Gera\xE7\xE3o ${generation_id} cancelada (diamantes estornados quando aplic\xE1vel).`);
|
|
23201
26474
|
} catch (e) {
|
|
26475
|
+
if (e instanceof ApiError && e.httpStatus === 409) return textResult(e.message);
|
|
23202
26476
|
return errorResult(apiErrorToUserMessage(e));
|
|
23203
26477
|
}
|
|
23204
26478
|
}
|
|
@@ -24094,7 +27368,7 @@ Use o valor de "voice" no generate_audio com um modelo 3.8 (sem multi_speaker).`
|
|
|
24094
27368
|
}
|
|
24095
27369
|
|
|
24096
27370
|
// src/tools/account.ts
|
|
24097
|
-
function registerAccountTools(server, client,
|
|
27371
|
+
function registerAccountTools(server, client, cfg) {
|
|
24098
27372
|
server.registerTool(
|
|
24099
27373
|
"whoami",
|
|
24100
27374
|
{
|
|
@@ -24151,14 +27425,17 @@ ${budget}` : "")
|
|
|
24151
27425
|
},
|
|
24152
27426
|
async () => {
|
|
24153
27427
|
try {
|
|
24154
|
-
const m = await
|
|
27428
|
+
const [m, elevenLabs] = await Promise.all([
|
|
27429
|
+
client.models(),
|
|
27430
|
+
client.elevenLabsCatalog({ retry: false }).catch(() => null)
|
|
27431
|
+
]);
|
|
24155
27432
|
const lines = m.models.map((x) => {
|
|
24156
27433
|
const price = typeof x.pricing === "number" ? `$${x.pricing}` : JSON.stringify(x.pricing);
|
|
24157
27434
|
return `\u2022 ${x.model} \u2014 ${price} (base USD)`;
|
|
24158
27435
|
});
|
|
24159
27436
|
const analyzeBlock = analyzeCatalogBlock(m.analyze);
|
|
24160
27437
|
const txt = `Modelos de gera\xE7\xE3o:
|
|
24161
|
-
${lines.join("\n") || "(nenhum)"}` + analyzeBlock + `
|
|
27438
|
+
${lines.join("\n") || "(nenhum)"}` + analyzeBlock + elevenLabsCatalogBlock(elevenLabs) + `
|
|
24162
27439
|
|
|
24163
27440
|
Limites simult\xE2neos por usu\xE1rio: imagem=${m.limits.perUserMaxImage}, v\xEDdeo=${m.limits.perUserMaxVideo}, \xE1udio=${m.limits.perUserMaxAudio}.
|
|
24164
27441
|
1 \u{1F48E} \u2248 $${m.pricing.diamondValueUsd} (margem ${m.pricing.diamondMargin}x, m\xEDn ${m.pricing.minDiamonds} \u{1F48E}). Use estimate_cost para o custo exato em diamantes (gera\xE7\xE3o).`;
|
|
@@ -24172,9 +27449,10 @@ Limites simult\xE2neos por usu\xE1rio: imagem=${m.limits.perUserMaxImage}, v\xED
|
|
|
24172
27449
|
"estimate_cost",
|
|
24173
27450
|
{
|
|
24174
27451
|
title: "Estimar custo",
|
|
24175
|
-
description: "Retorna o custo autoritativo em diamantes ANTES de gerar. Para \xE1udio (TTS) o custo \xE9 por segundo e s\xF3 \xE9 conhecido ap\xF3s a s\xEDntese.",
|
|
27452
|
+
description: "Retorna o custo autoritativo em diamantes ANTES de gerar. Para \xE1udio (TTS) o custo \xE9 por segundo e s\xF3 \xE9 conhecido ap\xF3s a s\xEDntese. ElevenLabs: model = elevenlabs/<ferramenta>[/<modelo>], os campos da gera\xE7\xE3o em elevenlabs_params e o arquivo em file (ou dry_run: true na pr\xF3pria ferramenta elevenlabs_*).",
|
|
24176
27453
|
inputSchema: {
|
|
24177
27454
|
model: external_exports.string().min(1).describe("Id do modelo (ex.: google/nano-banana-pro, bytedance/seedance-2.0)."),
|
|
27455
|
+
elevenlabs_params: external_exports.record(external_exports.unknown()).optional().describe('[ElevenLabs] Campos do pedido no formato da API, ex.: { "voice": "...", "text": "..." }.'),
|
|
24178
27456
|
resolution: external_exports.string().optional(),
|
|
24179
27457
|
duration: external_exports.number().int().optional(),
|
|
24180
27458
|
mode: external_exports.string().optional(),
|
|
@@ -24200,6 +27478,9 @@ Limites simult\xE2neos por usu\xE1rio: imagem=${m.limits.perUserMaxImage}, v\xED
|
|
|
24200
27478
|
}
|
|
24201
27479
|
},
|
|
24202
27480
|
async (args) => {
|
|
27481
|
+
if (args.model.startsWith("elevenlabs/")) {
|
|
27482
|
+
return estimateElevenLabsModel(client, cfg, args.model, args.elevenlabs_params, args.file);
|
|
27483
|
+
}
|
|
24203
27484
|
try {
|
|
24204
27485
|
let width2 = args.source_width;
|
|
24205
27486
|
let height = args.source_height;
|
|
@@ -24566,9 +27847,11 @@ ${calls.map(callLine).join("\n\n")}`);
|
|
|
24566
27847
|
}
|
|
24567
27848
|
|
|
24568
27849
|
// src/tools/canvas.ts
|
|
24569
|
-
import { createHash } from "crypto";
|
|
27850
|
+
import { createHash as createHash2 } from "crypto";
|
|
24570
27851
|
|
|
24571
27852
|
// src/canvas/api.ts
|
|
27853
|
+
import { createHash } from "crypto";
|
|
27854
|
+
var import_canvas_core = __toESM(require_canvas_core(), 1);
|
|
24572
27855
|
var PINNED_CORE_VERSION = "ca7b3b406184c7f679f555c3a008013197182b23";
|
|
24573
27856
|
var RUN_REQUEST_TIMEOUT_MS = 4e4;
|
|
24574
27857
|
var FOCUS_REQUEST_TIMEOUT_MS = 12e3;
|
|
@@ -24583,6 +27866,54 @@ var commentPacing = {
|
|
|
24583
27866
|
now: () => Date.now(),
|
|
24584
27867
|
sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)))
|
|
24585
27868
|
};
|
|
27869
|
+
var boardCachePolicy = {
|
|
27870
|
+
/** Contrato 5: duas leituras do mesmo board com menos que isso reaproveitam a anterior sem rede. */
|
|
27871
|
+
minIntervalMs: 2e3,
|
|
27872
|
+
stdio: { entries: 4, bytes: 256 * 1024 * 1024 },
|
|
27873
|
+
/** Dentro do academy-api: o doc em cache ocupa a memória da própria API. */
|
|
27874
|
+
remote: { entries: 2, bytes: 64 * 1024 * 1024 },
|
|
27875
|
+
/** Envelopes guardados para o conflito do edit() sem ir à rede (o servidor manda reler acima de 200). */
|
|
27876
|
+
recentMax: 200,
|
|
27877
|
+
now: () => Date.now()
|
|
27878
|
+
};
|
|
27879
|
+
var boardStore = /* @__PURE__ */ new Map();
|
|
27880
|
+
var boardLoads = /* @__PURE__ */ new Map();
|
|
27881
|
+
function storeEntry(key, entry) {
|
|
27882
|
+
const limit = isRemoteMode() ? boardCachePolicy.remote : boardCachePolicy.stdio;
|
|
27883
|
+
boardStore.delete(key);
|
|
27884
|
+
if (entry.bytes > limit.bytes) return;
|
|
27885
|
+
boardStore.set(key, entry);
|
|
27886
|
+
let total = 0;
|
|
27887
|
+
for (const e of boardStore.values()) total += e.bytes;
|
|
27888
|
+
for (const [k, e] of boardStore) {
|
|
27889
|
+
if (boardStore.size <= limit.entries && total <= limit.bytes) break;
|
|
27890
|
+
boardStore.delete(k);
|
|
27891
|
+
total -= e.bytes;
|
|
27892
|
+
}
|
|
27893
|
+
}
|
|
27894
|
+
function touchEntry(key, entry) {
|
|
27895
|
+
boardStore.delete(key);
|
|
27896
|
+
boardStore.set(key, entry);
|
|
27897
|
+
}
|
|
27898
|
+
function applyDelta(snap, envelopes) {
|
|
27899
|
+
let doc = snap.doc;
|
|
27900
|
+
let seq = snap.seq;
|
|
27901
|
+
try {
|
|
27902
|
+
for (const env of envelopes) {
|
|
27903
|
+
if (env.seq <= seq) continue;
|
|
27904
|
+
if (!knownOp(env.op)) return null;
|
|
27905
|
+
doc = (0, import_canvas_core.applyConfirmed)(doc, env);
|
|
27906
|
+
seq = env.seq;
|
|
27907
|
+
}
|
|
27908
|
+
} catch {
|
|
27909
|
+
return null;
|
|
27910
|
+
}
|
|
27911
|
+
return seq === snap.seq ? snap : { ...snap, doc, seq, title: doc.title };
|
|
27912
|
+
}
|
|
27913
|
+
function knownOp(op) {
|
|
27914
|
+
if (!Object.hasOwn(import_canvas_core.OPS, op.type)) return false;
|
|
27915
|
+
return op.type !== "batch" || Array.isArray(op.ops) && op.ops.every((o) => knownOp(o));
|
|
27916
|
+
}
|
|
24586
27917
|
var CanvasApi = class {
|
|
24587
27918
|
constructor(client, cfg) {
|
|
24588
27919
|
this.client = client;
|
|
@@ -24612,11 +27943,87 @@ var CanvasApi = class {
|
|
|
24612
27943
|
createBoard(body2) {
|
|
24613
27944
|
return this.req("POST", "/boards", { body: body2 });
|
|
24614
27945
|
}
|
|
24615
|
-
|
|
24616
|
-
|
|
27946
|
+
cacheKey(boardId4) {
|
|
27947
|
+
const who2 = createHash("sha256").update(this.cfg.token).digest("hex").slice(0, 16);
|
|
27948
|
+
return `${this.cfg.canvasBase}|${who2}|${boardId4}`;
|
|
27949
|
+
}
|
|
27950
|
+
/** Board pelo cache: delta quando dá, inteiro com If-None-Match quando não. Um GET em voo por board. */
|
|
27951
|
+
async snapshot(boardId4, opts = {}) {
|
|
27952
|
+
const key = this.cacheKey(boardId4);
|
|
27953
|
+
const entry = boardStore.get(key);
|
|
27954
|
+
if (entry && !opts.fresh && !opts.runs && boardCachePolicy.now() - entry.checkedAt < boardCachePolicy.minIntervalMs) {
|
|
27955
|
+
touchEntry(key, entry);
|
|
27956
|
+
return entry.snap;
|
|
27957
|
+
}
|
|
27958
|
+
const loadKey = opts.runs ? `${key}|runs` : key;
|
|
27959
|
+
const inFlight = boardLoads.get(loadKey);
|
|
27960
|
+
if (inFlight) return inFlight;
|
|
27961
|
+
const load = this.load(boardId4, key, !!opts.runs).finally(() => boardLoads.delete(loadKey));
|
|
27962
|
+
boardLoads.set(loadKey, load);
|
|
27963
|
+
return load;
|
|
27964
|
+
}
|
|
27965
|
+
async load(boardId4, key, needRuns) {
|
|
27966
|
+
const entry = boardStore.get(key);
|
|
27967
|
+
if (entry && !needRuns && this.coreVersion === PINNED_CORE_VERSION) {
|
|
27968
|
+
const envelopes = await this.fetchOpsAfter(boardId4, entry.snap.seq);
|
|
27969
|
+
const next = envelopes && applyDelta(entry.snap, envelopes);
|
|
27970
|
+
if (next) {
|
|
27971
|
+
let recent = entry.recent;
|
|
27972
|
+
let logFrom = entry.logFrom;
|
|
27973
|
+
if (next !== entry.snap) {
|
|
27974
|
+
recent = [...recent, ...envelopes.filter((e) => e.seq > entry.snap.seq)];
|
|
27975
|
+
if (recent.length > boardCachePolicy.recentMax) {
|
|
27976
|
+
recent = recent.slice(-boardCachePolicy.recentMax);
|
|
27977
|
+
logFrom = recent[0].seq - 1;
|
|
27978
|
+
}
|
|
27979
|
+
}
|
|
27980
|
+
const delta = envelopes.reduce((sum, e) => sum + JSON.stringify(e.op).length, 0);
|
|
27981
|
+
storeEntry(key, {
|
|
27982
|
+
snap: next,
|
|
27983
|
+
// O ETag cobre o snapshot inteiro: se o seq andou, o guardado não vale mais.
|
|
27984
|
+
etag: next === entry.snap ? entry.etag : null,
|
|
27985
|
+
bytes: entry.bytes + delta,
|
|
27986
|
+
checkedAt: boardCachePolicy.now(),
|
|
27987
|
+
recent,
|
|
27988
|
+
logFrom
|
|
27989
|
+
});
|
|
27990
|
+
return next;
|
|
27991
|
+
}
|
|
27992
|
+
}
|
|
27993
|
+
const res = await this.client.requestMeta("GET", `/boards/${boardId4}`, {
|
|
27994
|
+
base: this.cfg.canvasBase,
|
|
27995
|
+
headers: entry?.etag ? { "If-None-Match": entry.etag } : void 0
|
|
27996
|
+
});
|
|
27997
|
+
if (res.status === 304 && entry) {
|
|
27998
|
+
storeEntry(key, { ...entry, checkedAt: boardCachePolicy.now() });
|
|
27999
|
+
return entry.snap;
|
|
28000
|
+
}
|
|
28001
|
+
if (!res.data) throw new ApiError(502, "O servidor do Canvas respondeu sem o board.");
|
|
28002
|
+
storeEntry(key, {
|
|
28003
|
+
snap: res.data,
|
|
28004
|
+
etag: res.etag,
|
|
28005
|
+
bytes: res.bytes,
|
|
28006
|
+
checkedAt: boardCachePolicy.now(),
|
|
28007
|
+
recent: [],
|
|
28008
|
+
logFrom: res.data.seq
|
|
28009
|
+
});
|
|
28010
|
+
return res.data;
|
|
28011
|
+
}
|
|
28012
|
+
/** Esquece o board deste token (ex.: o servidor recusou por papel e o cache pode estar velho). */
|
|
28013
|
+
forget(boardId4) {
|
|
28014
|
+
boardStore.delete(this.cacheKey(boardId4));
|
|
24617
28015
|
}
|
|
24618
|
-
/**
|
|
28016
|
+
/**
|
|
28017
|
+
* O que mudou depois de `after`. Vem do cache quando a última leitura cobre esse trecho (o
|
|
28018
|
+
* edit() acabou de reler), senão da rede. `null` quando o servidor manda reler a foto (410).
|
|
28019
|
+
*/
|
|
24619
28020
|
async opsAfter(boardId4, after) {
|
|
28021
|
+
const entry = boardStore.get(this.cacheKey(boardId4));
|
|
28022
|
+
if (entry && after >= entry.logFrom && after <= entry.snap.seq) return entry.recent.filter((e) => e.seq > after);
|
|
28023
|
+
return this.fetchOpsAfter(boardId4, after);
|
|
28024
|
+
}
|
|
28025
|
+
/** Replay depois de `after`. `null` quando o servidor manda reler a foto (410). */
|
|
28026
|
+
async fetchOpsAfter(boardId4, after) {
|
|
24620
28027
|
try {
|
|
24621
28028
|
const { envelopes } = await this.req("GET", `/boards/${boardId4}/ops`, {
|
|
24622
28029
|
query: { after }
|
|
@@ -24628,9 +28035,14 @@ var CanvasApi = class {
|
|
|
24628
28035
|
}
|
|
24629
28036
|
}
|
|
24630
28037
|
async commit(boardId4, ops) {
|
|
24631
|
-
const send = () =>
|
|
24632
|
-
|
|
24633
|
-
|
|
28038
|
+
const send = () => (
|
|
28039
|
+
// Reenvio seguro: o servidor ignora operação com id que já entrou.
|
|
28040
|
+
this.client.request("POST", `/boards/${boardId4}/ops`, {
|
|
28041
|
+
base: this.cfg.canvasBase,
|
|
28042
|
+
body: { coreVersion: this.coreVersion, ops },
|
|
28043
|
+
retry: true
|
|
28044
|
+
})
|
|
28045
|
+
);
|
|
24634
28046
|
try {
|
|
24635
28047
|
return await send();
|
|
24636
28048
|
} catch (e) {
|
|
@@ -24810,6 +28222,33 @@ var KINDS = {
|
|
|
24810
28222
|
outputs: ["audio", "approved"],
|
|
24811
28223
|
dynamic: "style conforme o modelo; SeedAudio 1.0 tem reference (audio, at\xE9 3 vozes na ordem @Audio1..3), volume seedLoudnessRate (-50..100), usa voice: seed-auto e seedConsent: true com refer\xEAncia; alternativa seedReferenceGenerationId de gera\xE7\xE3o pr\xF3pria"
|
|
24812
28224
|
},
|
|
28225
|
+
"audio-tools": {
|
|
28226
|
+
title: "Ferramentas de \xE1udio",
|
|
28227
|
+
size: { w: 320, h: 212 },
|
|
28228
|
+
data: {
|
|
28229
|
+
tool: "sfx",
|
|
28230
|
+
model: null,
|
|
28231
|
+
voice: null,
|
|
28232
|
+
durationSec: null,
|
|
28233
|
+
loop: false,
|
|
28234
|
+
instrumental: true,
|
|
28235
|
+
removeNoise: false,
|
|
28236
|
+
language: null,
|
|
28237
|
+
diarize: true,
|
|
28238
|
+
audioEvents: false,
|
|
28239
|
+
targetLang: "en",
|
|
28240
|
+
sourceLang: null,
|
|
28241
|
+
dubMode: "v1",
|
|
28242
|
+
history: [],
|
|
28243
|
+
pinned: null,
|
|
28244
|
+
results: [],
|
|
28245
|
+
pinnedResult: null
|
|
28246
|
+
},
|
|
28247
|
+
inputs: ["prompt", "lyrics", "source"],
|
|
28248
|
+
outputs: ["audio", "approved", "text", "subtitle", "video"],
|
|
28249
|
+
dynamic: "as portas mudam com data.tool (sfx, isolate, voice_change, music, stems, transcribe, dub)",
|
|
28250
|
+
main: "tool"
|
|
28251
|
+
},
|
|
24813
28252
|
music: {
|
|
24814
28253
|
title: "Trilha",
|
|
24815
28254
|
size: { w: 320, h: 212 },
|
|
@@ -24900,6 +28339,7 @@ function ratioOfAspect(aspect) {
|
|
|
24900
28339
|
const height = Number(match[2]);
|
|
24901
28340
|
return width2 > 0 && height > 0 ? width2 / height : null;
|
|
24902
28341
|
}
|
|
28342
|
+
var DUB_NOTE = "Dublagem no Canvas exige clique de pessoa: agente n\xE3o roda. ";
|
|
24903
28343
|
function isGeneratorKind(kind) {
|
|
24904
28344
|
return kind === "image" || kind === "video";
|
|
24905
28345
|
}
|
|
@@ -24922,7 +28362,7 @@ function knownPort(kind, side, port) {
|
|
|
24922
28362
|
}
|
|
24923
28363
|
|
|
24924
28364
|
// src/canvas/core.ts
|
|
24925
|
-
import { randomBytes, randomUUID } from "crypto";
|
|
28365
|
+
import { randomBytes, randomUUID as randomUUID2 } from "crypto";
|
|
24926
28366
|
var SCHEMA_VERSION = 1;
|
|
24927
28367
|
var MAX_ENVELOPES_PER_COMMIT = 200;
|
|
24928
28368
|
var MAX_OP_BYTES = 64 * 1024;
|
|
@@ -25008,7 +28448,7 @@ function checkOp(op) {
|
|
|
25008
28448
|
}
|
|
25009
28449
|
}
|
|
25010
28450
|
function envelope(boardId4, op, actorId) {
|
|
25011
|
-
return { id:
|
|
28451
|
+
return { id: randomUUID2(), boardId: boardId4, clientId: CLIENT_ID, actorId, seq: null, ts: Date.now(), op };
|
|
25012
28452
|
}
|
|
25013
28453
|
function checkEnvelope(env) {
|
|
25014
28454
|
const bad = checkOp(env.op);
|
|
@@ -25020,7 +28460,7 @@ function checkEnvelope(env) {
|
|
|
25020
28460
|
}
|
|
25021
28461
|
function emptyBoard(title, now = Date.now()) {
|
|
25022
28462
|
return {
|
|
25023
|
-
id:
|
|
28463
|
+
id: randomUUID2(),
|
|
25024
28464
|
schemaVersion: SCHEMA_VERSION,
|
|
25025
28465
|
title,
|
|
25026
28466
|
ownerId: "",
|
|
@@ -25037,7 +28477,7 @@ function emptyBoard(title, now = Date.now()) {
|
|
|
25037
28477
|
function makeNode(init) {
|
|
25038
28478
|
const now = init.now ?? Date.now();
|
|
25039
28479
|
return {
|
|
25040
|
-
id: init.id ??
|
|
28480
|
+
id: init.id ?? randomUUID2(),
|
|
25041
28481
|
type: init.type,
|
|
25042
28482
|
position: { x: init.position.x, y: init.position.y },
|
|
25043
28483
|
size: { w: init.size.w, h: init.size.h },
|
|
@@ -25051,7 +28491,7 @@ function makeNode(init) {
|
|
|
25051
28491
|
}
|
|
25052
28492
|
function makeEdge(init) {
|
|
25053
28493
|
return {
|
|
25054
|
-
id:
|
|
28494
|
+
id: randomUUID2(),
|
|
25055
28495
|
source: init.source,
|
|
25056
28496
|
sourcePort: init.sourcePort,
|
|
25057
28497
|
target: init.target,
|
|
@@ -26289,7 +29729,7 @@ ${text}`;
|
|
|
26289
29729
|
}
|
|
26290
29730
|
|
|
26291
29731
|
// src/canvas/upload.ts
|
|
26292
|
-
import { randomUUID as
|
|
29732
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
26293
29733
|
import { basename as basename2, extname as extname3 } from "path";
|
|
26294
29734
|
function kindOfMime(mime) {
|
|
26295
29735
|
if (mime.startsWith("image/")) return "image";
|
|
@@ -26329,7 +29769,7 @@ async function uploadMedia(cfg, source, name) {
|
|
|
26329
29769
|
meta: meta ?? {},
|
|
26330
29770
|
measuredBy,
|
|
26331
29771
|
reused,
|
|
26332
|
-
assetId: `asset_${
|
|
29772
|
+
assetId: `asset_${randomUUID3()}`
|
|
26333
29773
|
};
|
|
26334
29774
|
}
|
|
26335
29775
|
function mediaItem(u) {
|
|
@@ -26511,9 +29951,14 @@ ${payload(u)}`
|
|
|
26511
29951
|
}
|
|
26512
29952
|
|
|
26513
29953
|
// src/tools/canvas-run.ts
|
|
26514
|
-
import { randomUUID as
|
|
29954
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
26515
29955
|
var MAX_REMEMBERED = 50;
|
|
26516
|
-
var acceptedPacing = { repeats:
|
|
29956
|
+
var acceptedPacing = { repeats: 8, pauseMs: 2e3 };
|
|
29957
|
+
var statusPacing = {
|
|
29958
|
+
minIntervalMs: 3e3,
|
|
29959
|
+
now: () => Date.now(),
|
|
29960
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)))
|
|
29961
|
+
};
|
|
26517
29962
|
var sleep3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
26518
29963
|
var seconds = (ms) => `${new Intl.NumberFormat("pt-BR", { maximumFractionDigits: 1 }).format(ms / 1e3)} s`;
|
|
26519
29964
|
function timingsLine(t) {
|
|
@@ -26535,23 +29980,23 @@ function prettyClient(name) {
|
|
|
26535
29980
|
function modeText(mode) {
|
|
26536
29981
|
return mode === "simulated" ? "Simulado (n\xE3o gasta)" : mode === "live" ? "Real" : mode ?? "?";
|
|
26537
29982
|
}
|
|
26538
|
-
function estimateLines(
|
|
26539
|
-
if (!
|
|
29983
|
+
function estimateLines(estimate2, titleOf) {
|
|
29984
|
+
if (!estimate2) return [];
|
|
26540
29985
|
const lines = [];
|
|
26541
|
-
const nodes =
|
|
29986
|
+
const nodes = estimate2.nodes ?? [];
|
|
26542
29987
|
const now = nodes.filter((n) => n.willRun);
|
|
26543
29988
|
for (const n of now) {
|
|
26544
29989
|
const cost = n.error ? `estimativa falhou (${n.error})` : dia(n.diamonds);
|
|
26545
29990
|
lines.push(`- ${n.title ?? titleOf(n.nodeId)} (${n.nodeId}): ${cost}`);
|
|
26546
29991
|
}
|
|
26547
|
-
if (
|
|
26548
|
-
lines.push(`\u2026 e mais ${
|
|
29992
|
+
if (estimate2.omitted) {
|
|
29993
|
+
lines.push(`\u2026 e mais ${estimate2.omitted} n\xF3(s) fora da lista (a resposta da aba foi cortada pelo tamanho; o total vale para todos).`);
|
|
26549
29994
|
}
|
|
26550
|
-
const cached2 =
|
|
29995
|
+
const cached2 = estimate2.cached ?? nodes.filter((n) => !n.willRun && !n.afterApproval).length;
|
|
26551
29996
|
if (cached2) lines.push(`Em cache (n\xE3o rodam): ${cached2}.`);
|
|
26552
|
-
const later =
|
|
26553
|
-
if (later) lines.push(`Esperando aprova\xE7\xE3o no board depois disso: ${later} n\xF3(s), \u2248 ${dia(
|
|
26554
|
-
const unknown2 =
|
|
29997
|
+
const later = estimate2.counts?.later ?? estimate2.later?.nodes?.length ?? 0;
|
|
29998
|
+
if (later) lines.push(`Esperando aprova\xE7\xE3o no board depois disso: ${later} n\xF3(s), \u2248 ${dia(estimate2.later?.total ?? 0)} (fora desta conta).`);
|
|
29999
|
+
const unknown2 = estimate2.counts?.unknown ?? estimate2.unknown?.length ?? 0;
|
|
26555
30000
|
if (unknown2) {
|
|
26556
30001
|
lines.push(`Sem estimativa: ${unknown2} n\xF3(s) (texto cobra por token; o total \xE9 piso).`);
|
|
26557
30002
|
}
|
|
@@ -26568,6 +30013,7 @@ function targetOf(args) {
|
|
|
26568
30013
|
}
|
|
26569
30014
|
function registerCanvasRunTools(server, api, run) {
|
|
26570
30015
|
const remembered = /* @__PURE__ */ new Map();
|
|
30016
|
+
const lastStatusAt = /* @__PURE__ */ new Map();
|
|
26571
30017
|
const remember = (requestId, entry) => {
|
|
26572
30018
|
remembered.delete(requestId);
|
|
26573
30019
|
remembered.set(requestId, entry);
|
|
@@ -26656,7 +30102,7 @@ function registerCanvasRunTools(server, api, run) {
|
|
|
26656
30102
|
},
|
|
26657
30103
|
async (args) => run(async () => {
|
|
26658
30104
|
const target = targetOf(args);
|
|
26659
|
-
const requestId = (args.request_id ??
|
|
30105
|
+
const requestId = (args.request_id ?? randomUUID4()).toLowerCase();
|
|
26660
30106
|
const label = args.label ?? prettyClient(server.server.getClientVersion()?.name);
|
|
26661
30107
|
const ask = async () => {
|
|
26662
30108
|
try {
|
|
@@ -26715,6 +30161,11 @@ function registerCanvasRunTools(server, api, run) {
|
|
|
26715
30161
|
},
|
|
26716
30162
|
async ({ board_id, request_id, node_ids }) => run(async () => {
|
|
26717
30163
|
const requestId = request_id.toLowerCase();
|
|
30164
|
+
const since = statusPacing.now() - (lastStatusAt.get(requestId) ?? -Infinity);
|
|
30165
|
+
if (since < statusPacing.minIntervalMs) await statusPacing.sleep(statusPacing.minIntervalMs - since);
|
|
30166
|
+
lastStatusAt.delete(requestId);
|
|
30167
|
+
lastStatusAt.set(requestId, statusPacing.now());
|
|
30168
|
+
while (lastStatusAt.size > MAX_REMEMBERED) lastStatusAt.delete(lastStatusAt.keys().next().value);
|
|
26718
30169
|
let why = "";
|
|
26719
30170
|
try {
|
|
26720
30171
|
const status = await api.runStatus(board_id, requestId);
|
|
@@ -26731,7 +30182,7 @@ function registerCanvasRunTools(server, api, run) {
|
|
|
26731
30182
|
}
|
|
26732
30183
|
const partial2 = known?.omitted ? ` (parcial: s\xF3 os ${ids.length} n\xF3s que a aba listou; outros ${known.omitted} ficaram fora da resposta. Para eles, chame com node_ids)` : "";
|
|
26733
30184
|
return `${why} Pelo estado de execu\xE7\xE3o do board${partial2}:
|
|
26734
|
-
${fromRuns(await api.snapshot(board_id), ids)}`;
|
|
30185
|
+
${fromRuns(await api.snapshot(board_id, { runs: true }), ids)}`;
|
|
26735
30186
|
})
|
|
26736
30187
|
);
|
|
26737
30188
|
}
|
|
@@ -27153,6 +30604,17 @@ function registerCanvasTools(server, client, cfg) {
|
|
|
27153
30604
|
}
|
|
27154
30605
|
return errorResult(apiErrorToUserMessage(e));
|
|
27155
30606
|
}
|
|
30607
|
+
async function commitOps(id, envs) {
|
|
30608
|
+
try {
|
|
30609
|
+
return await api.commit(id, envs);
|
|
30610
|
+
} catch (e) {
|
|
30611
|
+
if (!(e instanceof ApiError) || e.httpStatus !== 403) throw e;
|
|
30612
|
+
api.forget(id);
|
|
30613
|
+
const again = await api.snapshot(id, { runs: true }).catch(() => null);
|
|
30614
|
+
if (again?.role === "viewer") throw new CanvasToolError("Voc\xEA \xE9 s\xF3 leitor neste board: pe\xE7a ao dono para te dar papel de editor.");
|
|
30615
|
+
throw e;
|
|
30616
|
+
}
|
|
30617
|
+
}
|
|
27156
30618
|
async function run(fn) {
|
|
27157
30619
|
try {
|
|
27158
30620
|
return textResult(await fn());
|
|
@@ -27165,7 +30627,7 @@ function registerCanvasTools(server, client, cfg) {
|
|
|
27165
30627
|
if (last === void 0 && !opts.layoutOnly) {
|
|
27166
30628
|
throw new CanvasToolError("Leia o board com canvas_read_board antes de editar (a leitura vale para a sess\xE3o).");
|
|
27167
30629
|
}
|
|
27168
|
-
const snap = await api.snapshot(id);
|
|
30630
|
+
const snap = await api.snapshot(id, { fresh: true });
|
|
27169
30631
|
if (snap.role === "viewer") throw new CanvasToolError("Voc\xEA \xE9 s\xF3 leitor neste board: pe\xE7a ao dono para te dar papel de editor.");
|
|
27170
30632
|
const doc = snap.doc;
|
|
27171
30633
|
const { ops, done, targets } = await build2(doc, snap);
|
|
@@ -27200,7 +30662,7 @@ Aviso: ${changesSince(theirs, doc)}.`;
|
|
|
27200
30662
|
const env = envelope(id, batchOf(ops), await api.me());
|
|
27201
30663
|
const bad = checkEnvelope(env);
|
|
27202
30664
|
if (bad) throw new CanvasToolError(`Edi\xE7\xE3o recusada antes de enviar: ${bad}.`);
|
|
27203
|
-
const res = await
|
|
30665
|
+
const res = await commitOps(id, [env]);
|
|
27204
30666
|
const outcome = res.outcomes.find((o) => o.opId === env.id);
|
|
27205
30667
|
if (!outcome || "rejected" in outcome) {
|
|
27206
30668
|
if (!opts.layoutOnly) seen.delete(id);
|
|
@@ -27228,7 +30690,7 @@ Aviso: ${changesSince(theirs, doc)}.`;
|
|
|
27228
30690
|
const outcomes = /* @__PURE__ */ new Map();
|
|
27229
30691
|
let last = null;
|
|
27230
30692
|
for (let i = 0; i < envs.length; i += MAX_ENVELOPES_PER_COMMIT) {
|
|
27231
|
-
const res = await
|
|
30693
|
+
const res = await commitOps(id, envs.slice(i, i + MAX_ENVELOPES_PER_COMMIT));
|
|
27232
30694
|
for (const o of res.outcomes) outcomes.set(o.opId, o);
|
|
27233
30695
|
last = res.seq;
|
|
27234
30696
|
}
|
|
@@ -27441,7 +30903,7 @@ ${lines.join("\n")}${note}`;
|
|
|
27441
30903
|
const from = Math.min(offset ?? 0, total);
|
|
27442
30904
|
const size = max_chars ?? 4e4;
|
|
27443
30905
|
const to = Math.min(from + size, total);
|
|
27444
|
-
const hash =
|
|
30906
|
+
const hash = createHash2("sha256").update(json2).digest("hex").slice(0, 12);
|
|
27445
30907
|
const where = `data${segments.length ? `.${segments.join(".")}` : ""}`;
|
|
27446
30908
|
const at = readMeasured(node)?.at;
|
|
27447
30909
|
const head = `${node.id} \xB7 ${nodeKind(node) ?? node.type} \xB7 "${oneLine2(nodeName(node), 60)}" \xB7 board seq ${snap.seq} \xB7 tamanho ${sizeLabel(node)}${at ? ` \xB7 medido em ${at}` : ""} \xB7 ${where}${which}: ${total} caracteres (JSON compacto) \xB7 sha256 ${hash}`;
|
|
@@ -27505,7 +30967,7 @@ N\xF3s: ${Object.entries(ids).map(([k, v]) => `${k}=${v}`).join(" \xB7 ")}` : ""
|
|
|
27505
30967
|
"canvas_add_node",
|
|
27506
30968
|
{
|
|
27507
30969
|
title: "Canvas: adicionar n\xF3",
|
|
27508
|
-
description: `Adiciona um n\xF3 (n\xE3o executa). ${READ}kind: ${kindList()}. data completa o padr\xE3o do tipo; label d\xE1 o nome. Sem position, nasce ao lado do n\xF3 ligado ou \xE0 direita do board (com aba, no fim do conte\xFAdo da aba); aba grava data.abaId. Texto livre (label) sem size {w} nasce na largura do tamanho do texto: titulo 2000, subtitulo 1200, corpo 320. Prompt sem size nasce com 1024 \xD7 516; gerador de imagem ou v\xEDdeo, com altura 516 e a largura do aspect_ratio (16:9 917, 9:16 290, 1:1 516). inputs/outputs j\xE1 ligam o n\xF3 no mesmo passo. ` + MENTION_NOTE + MONTAGE_NOTE,
|
|
30970
|
+
description: `Adiciona um n\xF3 (n\xE3o executa). ${READ}kind: ${kindList()}. data completa o padr\xE3o do tipo; label d\xE1 o nome. Sem position, nasce ao lado do n\xF3 ligado ou \xE0 direita do board (com aba, no fim do conte\xFAdo da aba); aba grava data.abaId. Texto livre (label) sem size {w} nasce na largura do tamanho do texto: titulo 2000, subtitulo 1200, corpo 320. Prompt sem size nasce com 1024 \xD7 516; gerador de imagem ou v\xEDdeo, com altura 516 e a largura do aspect_ratio (16:9 917, 9:16 290, 1:1 516). inputs/outputs j\xE1 ligam o n\xF3 no mesmo passo. ` + DUB_NOTE + MENTION_NOTE + MONTAGE_NOTE,
|
|
27509
30971
|
inputSchema: {
|
|
27510
30972
|
board_id: boardId3,
|
|
27511
30973
|
kind: external_exports.string().min(1).max(40),
|
|
@@ -27570,7 +31032,7 @@ N\xF3s: ${Object.entries(ids).map(([k, v]) => `${k}=${v}`).join(" \xB7 ")}` : ""
|
|
|
27570
31032
|
"canvas_update_node",
|
|
27571
31033
|
{
|
|
27572
31034
|
title: "Canvas: editar n\xF3",
|
|
27573
|
-
description: `Muda campos do data de um n\xF3, chave a chave (null apaga a chave), sem executar. ${READ}label renomeia; position move; size {w, h} muda a caixa (piso: o cart\xE3o cresce com o conte\xFAdo). N\xE3o troca o tipo. Cada chave \xE9 gravada inteira: leia antes com canvas_read_node e mande o valor completo j\xE1 revisado, para n\xE3o apagar o que outra pessoa escreveu. Para mudar partes de uma estrutura grande (clipes da timeline), use canvas_patch_node, por caminho; v\xE1rios n\xF3s de uma vez, canvas_update_nodes. ` + MENTION_NOTE + MONTAGE_NOTE,
|
|
31035
|
+
description: `Muda campos do data de um n\xF3, chave a chave (null apaga a chave), sem executar. ${READ}label renomeia; position move; size {w, h} muda a caixa (piso: o cart\xE3o cresce com o conte\xFAdo). N\xE3o troca o tipo. Cada chave \xE9 gravada inteira: leia antes com canvas_read_node e mande o valor completo j\xE1 revisado, para n\xE3o apagar o que outra pessoa escreveu. Para mudar partes de uma estrutura grande (clipes da timeline), use canvas_patch_node, por caminho; v\xE1rios n\xF3s de uma vez, canvas_update_nodes. ` + DUB_NOTE + MENTION_NOTE + MONTAGE_NOTE,
|
|
27574
31036
|
inputSchema: {
|
|
27575
31037
|
board_id: boardId3,
|
|
27576
31038
|
node_id: nodeIdArg2,
|
|
@@ -27598,7 +31060,7 @@ N\xF3s: ${Object.entries(ids).map(([k, v]) => `${k}=${v}`).join(" \xB7 ")}` : ""
|
|
|
27598
31060
|
"canvas_update_nodes",
|
|
27599
31061
|
{
|
|
27600
31062
|
title: "Canvas: editar v\xE1rios n\xF3s",
|
|
27601
|
-
description: 'Muda v\xE1rios n\xF3s num passo s\xF3, cada um como no canvas_update_node (position, size, label, data com null apagando). layout_only: true aceita s\xF3 position e size {w, h}, n\xE3o exige leitura e n\xE3o recusa por "outra pessoa mexeu" (nesses dois campos vale quem grava por \xFAltimo). Sem layout_only, exige canvas_read_board nesta sess\xE3o e recusa se outra pessoa mexeu em algum desses n\xF3s. Quebra em envelopes de at\xE9 64 KB e relata cada um. Para arrumar linhas inteiras (t\xEDtulo, prompt, refer\xEAncia, gerador), use canvas_arrange_rows.',
|
|
31063
|
+
description: 'Muda v\xE1rios n\xF3s num passo s\xF3, cada um como no canvas_update_node (position, size, label, data com null apagando). layout_only: true aceita s\xF3 position e size {w, h}, n\xE3o exige leitura e n\xE3o recusa por "outra pessoa mexeu" (nesses dois campos vale quem grava por \xFAltimo). Sem layout_only, exige canvas_read_board nesta sess\xE3o e recusa se outra pessoa mexeu em algum desses n\xF3s. Quebra em envelopes de at\xE9 64 KB e relata cada um. Para arrumar linhas inteiras (t\xEDtulo, prompt, refer\xEAncia, gerador), use canvas_arrange_rows. ' + DUB_NOTE,
|
|
27602
31064
|
inputSchema: {
|
|
27603
31065
|
board_id: boardId3,
|
|
27604
31066
|
nodes: external_exports.array(
|
|
@@ -27650,7 +31112,7 @@ N\xF3s: ${Object.entries(ids).map(([k, v]) => `${k}=${v}`).join(" \xB7 ")}` : ""
|
|
|
27650
31112
|
"canvas_patch_node",
|
|
27651
31113
|
{
|
|
27652
31114
|
title: "Canvas: gravar por caminho",
|
|
27653
|
-
description: `Grava v\xE1rios caminhos dentro do data de um n\xF3, sem executar: {path, value} grava, {path, unset: true} apaga. ${READ}O caminho atravessa objetos (o n\xEDvel que falta \xE9 criado) e n\xE3o entra em lista: para mudar um item de lista, grave a lista inteira. Quebra sozinho em envelopes de at\xE9 64 KB, em ordem, e devolve o resultado de cada um; entre envelopes n\xE3o h\xE1 atomicidade (o que entrou fica). Serve para mexer em partes de uma estrutura grande, como clipes da timeline da Montagem, sem reenviar tudo. Leia antes com canvas_read_node. ` + MENTION_NOTE + MONTAGE_NOTE,
|
|
31115
|
+
description: `Grava v\xE1rios caminhos dentro do data de um n\xF3, sem executar: {path, value} grava, {path, unset: true} apaga. ${READ}O caminho atravessa objetos (o n\xEDvel que falta \xE9 criado) e n\xE3o entra em lista: para mudar um item de lista, grave a lista inteira. Quebra sozinho em envelopes de at\xE9 64 KB, em ordem, e devolve o resultado de cada um; entre envelopes n\xE3o h\xE1 atomicidade (o que entrou fica). Serve para mexer em partes de uma estrutura grande, como clipes da timeline da Montagem, sem reenviar tudo. Leia antes com canvas_read_node. ` + DUB_NOTE + MENTION_NOTE + MONTAGE_NOTE,
|
|
27654
31116
|
inputSchema: {
|
|
27655
31117
|
board_id: boardId3,
|
|
27656
31118
|
node_id: nodeIdArg2,
|
|
@@ -27890,7 +31352,7 @@ N\xF3s: ${Object.entries(ids).map(([k, v]) => `${k}=${v}`).join(" \xB7 ")}` : ""
|
|
|
27890
31352
|
import { createRequire } from "module";
|
|
27891
31353
|
var require2 = createRequire(import.meta.url);
|
|
27892
31354
|
function readVersion() {
|
|
27893
|
-
if ("0.
|
|
31355
|
+
if ("0.46.0") return "0.46.0";
|
|
27894
31356
|
try {
|
|
27895
31357
|
const pkg = require2("../package.json");
|
|
27896
31358
|
return pkg.version ?? "0.0.0-unknown";
|
|
@@ -27903,7 +31365,7 @@ var VERSION = readVersion();
|
|
|
27903
31365
|
// src/server.ts
|
|
27904
31366
|
var SERVER_INSTRUCTIONS = [
|
|
27905
31367
|
"BePlus: tudo roda pela conta do usu\xE1rio (diamantes, limites e hist\xF3rico na plataforma).",
|
|
27906
|
-
'M\xEDdia: generate_*
|
|
31368
|
+
'M\xEDdia: generate_* e elevenlabs_* gastam diamantes; confira com estimate_cost antes de lotes grandes. Sem project, a gera\xE7\xE3o cai no projeto ativo; billing:"personal" cobra do usu\xE1rio.',
|
|
27907
31369
|
"Calls: search_calls acha, get_call traz a transcri\xE7\xE3o.",
|
|
27908
31370
|
"Canvas online (canvas_*): leia com canvas_read_board antes de editar e siga o estado lido. Cada edi\xE7\xE3o vai num passo s\xF3; se outra pessoa mexeu nos mesmos n\xF3s, a ferramenta recusa e pede releitura. As canvas_* n\xE3o geram m\xEDdia, exceto canvas_run: roda n\xF3s pela aba do Canvas aberta do usu\xE1rio e gasta diamantes; max_diamonds \xE9 o teto que o usu\xE1rio autorizou (dry_run s\xF3 estima). D\xEA nome (label) aos n\xF3s, n\xE3o invente tipos nem portas, e confirme antes de canvas_delete.",
|
|
27909
31371
|
"Cada aba \xE9 um plano: ao criar, passe aba (id da se\xE7\xE3o) em canvas_add_node e canvas_upload_media, sen\xE3o o cart\xE3o pode cair em Avulsos. canvas_read_board com aba l\xEA uma aba s\xF3.",
|
|
@@ -27918,6 +31380,7 @@ function buildServer(cfg) {
|
|
|
27918
31380
|
registerUpscaleTools(server, client, cfg);
|
|
27919
31381
|
registerAudioTools(server, client, cfg);
|
|
27920
31382
|
registerMusicTools(server, client, cfg);
|
|
31383
|
+
registerElevenLabsTools(server, client, cfg);
|
|
27921
31384
|
registerAccountTools(server, client, cfg);
|
|
27922
31385
|
registerAnalyzeTools(server, client, cfg);
|
|
27923
31386
|
registerProjectTools(server, client, cfg);
|