aicommunicator 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +93 -2
  3. package/bin/aic.js +20427 -0
  4. package/host-ui/host.js +5151 -0
  5. package/host-ui/index.html +483 -0
  6. package/host-ui/lang-en.js +631 -0
  7. package/package.json +30 -4
  8. package/plugin-guide.md +997 -0
  9. package/plugins/plugin-animation/LICENSE +55 -0
  10. package/plugins/plugin-animation/dist/logic.js +2225 -0
  11. package/plugins/plugin-animation/docs/manual.md +217 -0
  12. package/plugins/plugin-animation/manifest.json +31 -0
  13. package/plugins/plugin-animation/ui/icon.svg +6 -0
  14. package/plugins/plugin-animation/ui/index.html +2266 -0
  15. package/plugins/plugin-html-design/LICENSE +55 -0
  16. package/plugins/plugin-html-design/dist/logic.js +972 -0
  17. package/plugins/plugin-html-design/docs/manual.md +100 -0
  18. package/plugins/plugin-html-design/manifest.json +39 -0
  19. package/plugins/plugin-html-design/samples/exhibition-page.json +570 -0
  20. package/plugins/plugin-html-design/ui/icon.svg +5 -0
  21. package/plugins/plugin-html-design/ui/index.html +1241 -0
  22. package/plugins/plugin-html-slides/LICENSE +55 -0
  23. package/plugins/plugin-html-slides/dist/logic.js +1323 -0
  24. package/plugins/plugin-html-slides/docs/manual.md +121 -0
  25. package/plugins/plugin-html-slides/manifest.json +39 -0
  26. package/plugins/plugin-html-slides/samples/first-week-lecture.json +1129 -0
  27. package/plugins/plugin-html-slides/ui/icon.svg +5 -0
  28. package/plugins/plugin-html-slides/ui/index.html +1349 -0
  29. package/plugins/plugin-mindmap/LICENSE +55 -0
  30. package/plugins/plugin-mindmap/dist/logic.js +966 -0
  31. package/plugins/plugin-mindmap/docs/manual.md +145 -0
  32. package/plugins/plugin-mindmap/manifest.json +39 -0
  33. package/plugins/plugin-mindmap/samples/book-club.json +480 -0
  34. package/plugins/plugin-mindmap/ui/icon.svg +5 -0
  35. package/plugins/plugin-mindmap/ui/index.html +1774 -0
  36. package/plugins/plugin-plan/LICENSE +55 -0
  37. package/plugins/plugin-plan/dist/logic.js +1029 -0
  38. package/plugins/plugin-plan/docs/manual.md +261 -0
  39. package/plugins/plugin-plan/manifest.json +51 -0
  40. package/plugins/plugin-plan/samples/kimchi-day.json +1514 -0
  41. package/plugins/plugin-plan/samples/meeting-outline.json +653 -0
  42. package/plugins/plugin-plan/samples/reading-class.json +1577 -0
  43. package/plugins/plugin-plan/ui/icon.svg +7 -0
  44. package/plugins/plugin-plan/ui/index.html +1523 -0
  45. package/plugins/plugin-png/LICENSE +55 -0
  46. package/plugins/plugin-png/dist/logic.js +1758 -0
  47. package/plugins/plugin-png/docs/manual.md +344 -0
  48. package/plugins/plugin-png/manifest.json +35 -0
  49. package/plugins/plugin-png/ui/icon.svg +5 -0
  50. package/plugins/plugin-png/ui/index.html +2885 -0
  51. package/plugins/plugin-process-log/LICENSE +55 -0
  52. package/plugins/plugin-process-log/dist/logic.js +406 -0
  53. package/plugins/plugin-process-log/docs/manual.md +131 -0
  54. package/plugins/plugin-process-log/manifest.json +43 -0
  55. package/plugins/plugin-process-log/samples/design-decisions.json +241 -0
  56. package/plugins/plugin-process-log/ui/icon.svg +7 -0
  57. package/plugins/plugin-process-log/ui/index.html +721 -0
  58. package/plugins/plugin-story/LICENSE +55 -0
  59. package/plugins/plugin-story/dist/logic.js +2201 -0
  60. package/plugins/plugin-story/docs/manual.md +428 -0
  61. package/plugins/plugin-story/manifest.json +49 -0
  62. package/plugins/plugin-story/samples/scene-body.json +758 -0
  63. package/plugins/plugin-story/samples/time-and-groups.json +989 -0
  64. package/plugins/plugin-story/ui/icon.svg +4 -0
  65. package/plugins/plugin-story/ui/index.html +2783 -0
  66. package/plugins/plugin-svg/LICENSE +55 -0
  67. package/plugins/plugin-svg/dist/logic.js +2150 -0
  68. package/plugins/plugin-svg/docs/manual.md +314 -0
  69. package/plugins/plugin-svg/manifest.json +45 -0
  70. package/plugins/plugin-svg/samples/rocket-icon.json +1305 -0
  71. package/plugins/plugin-svg/samples/yard-cat.json +7796 -0
  72. package/plugins/plugin-svg/ui/icon.svg +4 -0
  73. package/plugins/plugin-svg/ui/index.html +2017 -0
  74. package/plugins/plugin-tree/LICENSE +55 -0
  75. package/plugins/plugin-tree/dist/logic.js +505 -0
  76. package/plugins/plugin-tree/docs/manual.md +140 -0
  77. package/plugins/plugin-tree/manifest.json +45 -0
  78. package/plugins/plugin-tree/samples/book-club.json +473 -0
  79. package/plugins/plugin-tree/samples/sort-memos.json +604 -0
  80. package/plugins/plugin-tree/ui/icon.svg +7 -0
  81. package/plugins/plugin-tree/ui/index.html +1305 -0
  82. package/schema/aic_describe.input.json +11 -0
  83. package/schema/aic_describe.output.json +67 -0
  84. package/schema/aic_observe.input.json +14 -0
  85. package/schema/aic_observe.output.json +47 -0
  86. package/schema/aic_send.input.json +15 -0
  87. package/schema/aic_send.output.json +38 -0
  88. package/schema/aic_update.input.json +19 -0
  89. package/schema/aic_update.output.json +39 -0
  90. package/schema/common.json +127 -0
  91. package/template/plugin/LICENSE +55 -0
  92. package/template/plugin/README.md +27 -0
  93. package/template/plugin/docs/manual.md +31 -0
  94. package/template/plugin/logic.js +337 -0
  95. package/template/plugin/manifest.json +27 -0
  96. package/template/plugin/ui/icon.svg +4 -0
  97. package/template/plugin/ui/index.html +269 -0
@@ -0,0 +1,1758 @@
1
+ "use strict";
2
+ (() => {
3
+ // packages/plugin-sdk/src/index.ts
4
+ var SEPARATOR = " ";
5
+ var ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
6
+ function sortKey(order, id) {
7
+ return `${order}${SEPARATOR}${id}`;
8
+ }
9
+ function boundAfterOrder(order) {
10
+ return `${order}!`;
11
+ }
12
+ function between(lo, hi) {
13
+ const out = [];
14
+ for (const c of ALPHABET) {
15
+ if ((lo === void 0 || c > lo) && (hi === void 0 || c < hi)) out.push(c);
16
+ }
17
+ return out;
18
+ }
19
+ function orderBetween(left, right) {
20
+ if (left === void 0 && right === void 0) return "V";
21
+ const L = left ?? "";
22
+ const U = right;
23
+ if (U !== void 0 && !(L < U)) throw new Error(`orderBetween: \uC67C\uCABD ${L} \uC774 \uC624\uB978\uCABD ${U} \uBCF4\uB2E4 \uC55E\uC774\uC5B4\uC57C \uD55C\uB2E4`);
24
+ let i = 0;
25
+ while (U !== void 0 && i < L.length && i < U.length && L[i] === U[i]) i += 1;
26
+ if (U === void 0) i = 0;
27
+ if (i >= L.length && U !== void 0) {
28
+ let prefix = U.slice(0, i);
29
+ for (let k = i; k < U.length; k += 1) {
30
+ const uc2 = U[k];
31
+ const cands2 = between(void 0, uc2);
32
+ if (cands2.length > 0) return prefix + cands2[cands2.length - 1];
33
+ if (prefix !== "" && !prefix.endsWith(SEPARATOR) && uc2 > SEPARATOR) return prefix;
34
+ prefix += uc2;
35
+ }
36
+ throw new Error(`orderBetween: ${L} \uACFC ${U} \uC0AC\uC774\uC5D0 \uAC12\uC744 \uB9CC\uB4E4 \uC218 \uC5C6\uB2E4`);
37
+ }
38
+ const lc = L[i];
39
+ const uc = U === void 0 ? void 0 : U[i];
40
+ const cands = between(lc, uc);
41
+ if (cands.length > 0) {
42
+ if (uc === void 0) return L.slice(0, i) + cands[0];
43
+ return L.slice(0, i) + cands[Math.floor(cands.length / 2)];
44
+ }
45
+ for (let j = i + 1; j < L.length; j += 1) {
46
+ const up = between(L[j], void 0);
47
+ if (up.length > 0) return L.slice(0, j) + up[0];
48
+ }
49
+ return `${L}V`;
50
+ }
51
+
52
+ // packages/image-quad/src/index.ts
53
+ var ROOT = "q";
54
+ var QUADRANTS = [1, 2, 3, 4];
55
+ var PIECE = /^q(\.[1-4])*$/;
56
+ var DEPTH_CAP = 30;
57
+ function maxDepth(width, height, minSide) {
58
+ if (!(width > 0 && height > 0 && minSide > 0)) return 0;
59
+ let d = 0;
60
+ while (d < DEPTH_CAP && Math.min(width, height) / 2 ** (d + 1) >= minSide) d += 1;
61
+ return d;
62
+ }
63
+ function makeGrid(width, height, minSide) {
64
+ return { width, height, depth: maxDepth(width, height, minSide) };
65
+ }
66
+ function piecePath(id) {
67
+ if (typeof id !== "string" || !PIECE.test(id)) return null;
68
+ return id === ROOT ? [] : id.slice(2).split(".").map(Number);
69
+ }
70
+ function pieceId(path) {
71
+ return path.length === 0 ? ROOT : `${ROOT}.${path.join(".")}`;
72
+ }
73
+ function pieceProblem(grid, id) {
74
+ const path = piecePath(id);
75
+ if (!path) {
76
+ return `\uC870\uAC01 id ${JSON.stringify(id)} \uC758 \uBAA8\uC591\uC774 \uD2C0\uB838\uB2E4. \uB8E8\uD2B8\uB294 q \uC774\uACE0, \uC790\uC2DD\uC740 q.1(\uC67C\uCABD \uC704), q.2(\uC624\uB978\uCABD \uC704), q.3(\uC67C\uCABD \uC544\uB798), q.4(\uC624\uB978\uCABD \uC544\uB798)\uCC98\uB7FC \uC810\uC73C\uB85C \uC774\uC5B4 \uC801\uB294\uB2E4`;
77
+ }
78
+ if (path.length > grid.depth) return `\uC870\uAC01 ${id} \uB294 \uB2E8\uACC4 ${path.length} \uC778\uB370 \uC774 \uADF8\uB9BC\uC5D0\uC11C \uAC00\uC7A5 \uAE4A\uC740 \uB2E8\uACC4\uB294 ${grid.depth} \uB2E4`;
79
+ return null;
80
+ }
81
+ var pieceDepth = (id) => (piecePath(id) ?? []).length;
82
+ function rectOfPath(grid, path) {
83
+ let x = 0;
84
+ let y = 0;
85
+ let w = grid.width;
86
+ let h = grid.height;
87
+ for (const k of path) {
88
+ w /= 2;
89
+ h /= 2;
90
+ if (k === 2 || k === 4) x += w;
91
+ if (k === 3 || k === 4) y += h;
92
+ }
93
+ return { x, y, w, h };
94
+ }
95
+ function pieceRect(grid, id) {
96
+ const path = piecePath(id);
97
+ if (!path || path.length > grid.depth) return null;
98
+ return rectOfPath(grid, path);
99
+ }
100
+ function parentPiece(id) {
101
+ const path = piecePath(id);
102
+ if (!path || path.length === 0) return null;
103
+ return pieceId(path.slice(0, -1));
104
+ }
105
+ function quadrantOf(id) {
106
+ const path = piecePath(id);
107
+ return path && path.length > 0 ? path[path.length - 1] : null;
108
+ }
109
+ function childPieces(grid, id) {
110
+ const path = piecePath(id);
111
+ if (!path || path.length >= grid.depth) return [];
112
+ return QUADRANTS.map((k) => pieceId([...path, k]));
113
+ }
114
+ function overlaps(a, b) {
115
+ return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
116
+ }
117
+ function contains(outer, inner) {
118
+ return inner.x >= outer.x && inner.y >= outer.y && inner.x + inner.w <= outer.x + outer.w && inner.y + inner.h <= outer.y + outer.h;
119
+ }
120
+ function smallestPieceContaining(grid, r) {
121
+ const path = [];
122
+ while (path.length < grid.depth) {
123
+ const next = QUADRANTS.find((k) => contains(rectOfPath(grid, [...path, k]), r));
124
+ if (next === void 0) break;
125
+ path.push(next);
126
+ }
127
+ return pieceId(path);
128
+ }
129
+ function deepestPieceAt(grid, x, y) {
130
+ if (!(x >= 0 && y >= 0 && x <= grid.width && y <= grid.height)) return null;
131
+ const path = [];
132
+ let r = rectOfPath(grid, path);
133
+ while (path.length < grid.depth) {
134
+ const right = x >= r.x + r.w / 2;
135
+ const down = y >= r.y + r.h / 2;
136
+ path.push((down ? 2 : 0) + (right ? 1 : 0) + 1);
137
+ r = rectOfPath(grid, path);
138
+ }
139
+ return pieceId(path);
140
+ }
141
+
142
+ // packages/plugin-png/src/draw.js
143
+ function pdNum(v) {
144
+ const r = Math.round(Number(v) * 1e3) / 1e3;
145
+ return Number.isFinite(r) ? String(r === 0 ? 0 : r) : "0";
146
+ }
147
+ function pdMat(m) {
148
+ return "matrix(" + m.map((v) => {
149
+ const r = Math.round(Number(v) * 1e6) / 1e6;
150
+ return Number.isFinite(r) ? String(r === 0 ? 0 : r) : "0";
151
+ }).join(" ") + ")";
152
+ }
153
+ function pdName(s) {
154
+ return String(s).replace(/[^A-Za-z0-9_-]/g, "_");
155
+ }
156
+ function pdColor(s) {
157
+ return /^#[0-9a-f]{6}$/.test(String(s)) ? String(s) : "#000000";
158
+ }
159
+ function pdIsIdentity(m) {
160
+ return !m || m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0;
161
+ }
162
+ function pdShape(s) {
163
+ let body = "";
164
+ if (s.kind === "rect") body = '<rect x="' + pdNum(s.x) + '" y="' + pdNum(s.y) + '" width="' + pdNum(s.w) + '" height="' + pdNum(s.h) + '" fill="#000"/>';
165
+ else if (s.kind === "ellipse") body = '<ellipse cx="' + pdNum(s.cx) + '" cy="' + pdNum(s.cy) + '" rx="' + pdNum(s.rx) + '" ry="' + pdNum(s.ry) + '" fill="#000"/>';
166
+ else if (s.kind === "polygon") body = '<polygon points="' + s.points.map((p) => pdNum(p[0]) + "," + pdNum(p[1])).join(" ") + '" fill="#000"/>';
167
+ else if (s.kind === "mask") body = '<use href="#m-' + pdName(s.key) + '" x="' + pdNum(s.x) + '" y="' + pdNum(s.y) + '"/>';
168
+ return pdIsIdentity(s.m) ? body : '<g transform="' + pdMat(s.m) + '">' + body + "</g>";
169
+ }
170
+ function pdFilterSteps(a) {
171
+ let out = "";
172
+ if (a.hue) out += '<feColorMatrix type="hueRotate" values="' + pdNum(a.hue) + '"/>';
173
+ if (a.saturate !== 1) out += '<feColorMatrix type="saturate" values="' + pdNum(a.saturate) + '"/>';
174
+ if (a.brightness !== 1) {
175
+ const k = pdNum(a.brightness);
176
+ out += '<feComponentTransfer><feFuncR type="linear" slope="' + k + '"/><feFuncG type="linear" slope="' + k + '"/><feFuncB type="linear" slope="' + k + '"/></feComponentTransfer>';
177
+ }
178
+ if (a.tint && a.tint.amount > 0) {
179
+ const c = pdColor(a.tint.color);
180
+ const t = a.tint.amount;
181
+ const keep = pdNum(1 - t);
182
+ const add = (i) => pdNum(parseInt(c.slice(i, i + 2), 16) / 255 * t);
183
+ out += '<feColorMatrix type="matrix" values="' + keep + " 0 0 0 " + add(1) + " 0 " + keep + " 0 0 " + add(3) + " 0 0 " + keep + " 0 " + add(5) + ' 0 0 0 1 0"/>';
184
+ }
185
+ return out;
186
+ }
187
+ function pdTouches(m, w, h, d) {
188
+ const xs = [m[4], m[0] * w + m[4], m[2] * h + m[4], m[0] * w + m[2] * h + m[4]];
189
+ const ys = [m[5], m[1] * w + m[5], m[3] * h + m[5], m[1] * w + m[3] * h + m[5]];
190
+ return Math.max.apply(null, xs) > d.x && Math.min.apply(null, xs) < d.x + d.w && Math.max.apply(null, ys) > d.y && Math.min.apply(null, ys) < d.y + d.h;
191
+ }
192
+ function pdParts(scene, dataOf, cull) {
193
+ const sizeOf = {};
194
+ for (const im of scene.images) sizeOf[im.id] = im;
195
+ const shown = scene.pieces.filter((p) => !p.hidden && sizeOf[p.image]);
196
+ const drawn = scene.area || { x: 0, y: 0, w: scene.width, h: scene.height };
197
+ const usedImages = {};
198
+ const maskSeen = {};
199
+ let imageDefs = "";
200
+ let maskDefs = "";
201
+ let pieceDefs = "";
202
+ let body = "";
203
+ for (const p of shown) {
204
+ const im = sizeOf[p.image];
205
+ if (cull && !pdTouches(p.matrix, im.width, im.height, drawn)) continue;
206
+ const pid = pdName(p.id);
207
+ if (!usedImages[im.id]) {
208
+ usedImages[im.id] = true;
209
+ imageDefs += '<image id="i-' + pdName(im.id) + '" width="' + pdNum(im.width) + '" height="' + pdNum(im.height) + '" href="data:image/png;base64,' + dataOf(im.id) + '"/>';
210
+ }
211
+ for (const s of p.clip.concat(p.holes)) {
212
+ if (s.kind !== "mask" || maskSeen[s.key]) continue;
213
+ maskSeen[s.key] = true;
214
+ maskDefs += '<image id="m-' + pdName(s.key) + '" width="' + pdNum(s.w) + '" height="' + pdNum(s.h) + '" href="data:image/png;base64,' + dataOf(s.key) + '"/>';
215
+ }
216
+ const area = ' maskUnits="userSpaceOnUse" x="0" y="0" width="' + pdNum(im.width) + '" height="' + pdNum(im.height) + '"';
217
+ let inner = '<use href="#i-' + pdName(im.id) + '"/>';
218
+ if (p.holes.length) {
219
+ pieceDefs += '<mask id="h-' + pid + '"' + area + '><rect x="0" y="0" width="' + pdNum(im.width) + '" height="' + pdNum(im.height) + '" fill="#fff"/>' + p.holes.map(pdShape).join("") + "</mask>";
220
+ inner = '<g mask="url(#h-' + pid + ')">' + inner + "</g>";
221
+ }
222
+ for (let i = p.clip.length - 1; i >= 0; i -= 1) {
223
+ pieceDefs += '<mask id="c-' + pid + "-" + i + '"' + area + ' mask-type="alpha" style="mask-type:alpha">' + pdShape(p.clip[i]) + "</mask>";
224
+ inner = '<g mask="url(#c-' + pid + "-" + i + ')">' + inner + "</g>";
225
+ }
226
+ let piece = '<g data-piece="' + pid + '"' + (pdIsIdentity(p.matrix) ? "" : ' transform="' + pdMat(p.matrix) + '"') + (p.adjust.opacity !== 1 ? ' opacity="' + pdNum(p.adjust.opacity) + '"' : "") + ">" + inner + "</g>";
227
+ const steps = pdFilterSteps(p.adjust);
228
+ if (steps) {
229
+ pieceDefs += '<filter id="f-' + pid + '" filterUnits="userSpaceOnUse" x="' + pdNum(drawn.x) + '" y="' + pdNum(drawn.y) + '" width="' + pdNum(drawn.w) + '" height="' + pdNum(drawn.h) + '" color-interpolation-filters="sRGB">' + steps + "</filter>";
230
+ piece = '<g filter="url(#f-' + pid + ')">' + piece + "</g>";
231
+ }
232
+ body += piece;
233
+ }
234
+ return { imageDefs, maskDefs, pieceDefs, body };
235
+ }
236
+ function pdSvg(scene, dataOf) {
237
+ const parts = pdParts(scene, dataOf, true);
238
+ const w = pdNum(scene.width);
239
+ const h = pdNum(scene.height);
240
+ return '<svg xmlns="http://www.w3.org/2000/svg" width="' + w + '" height="' + h + '" viewBox="0 0 ' + w + " " + h + '"><defs>' + parts.imageDefs + parts.maskDefs + parts.pieceDefs + "</defs>" + parts.body + "</svg>";
241
+ }
242
+
243
+ // packages/plugin-png/src/shapes.ts
244
+ var MAX_IMAGE_BYTES = 4194304;
245
+ var MAX_SIDE = 4096;
246
+ var MAX_IMAGES = 20;
247
+ var MAX_PIECES = 200;
248
+ var MAX_REGIONS = 200;
249
+ var MAX_CLIP = 8;
250
+ var MAX_HOLES = 40;
251
+ var MAX_POINTS = 400;
252
+ var MAX_MASK_CHARS = 8e5;
253
+ var MAX_DATA_CHARS = 7e6;
254
+ var MAX_COORD = 1e5;
255
+ var QUAD_MIN_SIDE = 64;
256
+ var MAX_AUTO_REGIONS = 5;
257
+ var Reject = class extends Error {
258
+ constructor(code, message) {
259
+ super(message);
260
+ this.code = code;
261
+ }
262
+ code;
263
+ };
264
+ var roundTo = (v, k) => {
265
+ const r = Math.round(v * k) / k;
266
+ return r === 0 ? 0 : r;
267
+ };
268
+ var r3 = (v) => roundTo(v, 1e3);
269
+ var r4 = (v) => roundTo(v, 1e4);
270
+ var r6 = (v) => roundTo(v, 1e6);
271
+ var fmt = (v) => String(r4(v));
272
+ var fmt1 = (v) => String(roundTo(v, 10));
273
+ function numInput(v, what, opts = {}) {
274
+ if (typeof v !== "number" || !Number.isFinite(v)) throw new Reject("INVALID_INPUT", `${what} must be a number (write it without quotes). Received: ${JSON.stringify(v) ?? "nothing"}`);
275
+ const min = opts.min ?? -MAX_COORD;
276
+ const max = opts.max ?? MAX_COORD;
277
+ if (v < min || v > max) throw new Reject("INVALID_INPUT", `${what} must be from ${min} to ${max}. Received: ${v}`);
278
+ if (opts.positive && !(v > 0)) throw new Reject("INVALID_INPUT", `${what} must be greater than 0. Received: ${v}`);
279
+ return r3(v);
280
+ }
281
+ function vecInput(v, what) {
282
+ let pair = null;
283
+ if (Array.isArray(v) && v.length === 2) pair = v;
284
+ else if (v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).sort().join() === "x,y") pair = [v.x, v.y];
285
+ if (!pair) throw new Reject("INVALID_INPUT", `${what} is two numbers in the form [x, y]. Received: ${JSON.stringify(v) ?? "nothing"}`);
286
+ return [numInput(pair[0], `x of ${what}`), numInput(pair[1], `y of ${what}`)];
287
+ }
288
+ function boolInput(v, what) {
289
+ if (typeof v !== "boolean") throw new Reject("INVALID_INPUT", `${what} must be true or false (write it without quotes). Received: ${JSON.stringify(v) ?? "nothing"}`);
290
+ return v;
291
+ }
292
+ function colorInput(v, what) {
293
+ const t = typeof v === "string" ? v.trim().toLowerCase() : "";
294
+ if (/^#[0-9a-f]{6}$/.test(t)) return t;
295
+ if (/^#[0-9a-f]{3}$/.test(t)) return `#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`;
296
+ throw new Reject("INVALID_INPUT", `${what} is a color in the form #rrggbb or #rgb. Color names (such as red) and colors with transparency are not accepted. Received: ${JSON.stringify(v) ?? "nothing"}`);
297
+ }
298
+ var isColor = (v) => typeof v === "string" && /^#[0-9a-f]{6}$/.test(v);
299
+ var apply = (m, p) => [m[0] * p[0] + m[2] * p[1] + m[4], m[1] * p[0] + m[3] * p[1] + m[5]];
300
+ function invert(m) {
301
+ const det = m[0] * m[3] - m[1] * m[2];
302
+ if (Math.abs(det) < 1e-12) return null;
303
+ const [a, b, c, d, e, f] = m;
304
+ return [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];
305
+ }
306
+ var roundMat = (m) => m.map(r6);
307
+ var isUnit = (m) => !m || m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0;
308
+ var isIdentityTurn = (p) => p.rotate === 0 && p.scale[0] === 1 && p.scale[1] === 1;
309
+ var isIdentity = (p) => isIdentityTurn(p) && p.move[0] === 0 && p.move[1] === 0;
310
+ function placeMatrix(p, pivot) {
311
+ const t = p.rotate * Math.PI / 180;
312
+ const cos = Math.cos(t);
313
+ const sin = Math.sin(t);
314
+ const [sx, sy] = p.scale;
315
+ const a = cos * sx;
316
+ const b = sin * sx;
317
+ const c = -sin * sy;
318
+ const d = cos * sy;
319
+ return [a, b, c, d, pivot[0] + p.move[0] - (a * pivot[0] + c * pivot[1]), pivot[1] + p.move[1] - (b * pivot[0] + d * pivot[1])];
320
+ }
321
+ function boxOf(points) {
322
+ if (points.length === 0) return null;
323
+ let x0 = Infinity;
324
+ let y0 = Infinity;
325
+ let x1 = -Infinity;
326
+ let y1 = -Infinity;
327
+ for (const [x, y] of points) {
328
+ if (x < x0) x0 = x;
329
+ if (y < y0) y0 = y;
330
+ if (x > x1) x1 = x;
331
+ if (y > y1) y1 = y;
332
+ }
333
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
334
+ }
335
+ var corners = (r) => [
336
+ [r.x, r.y],
337
+ [r.x + r.w, r.y],
338
+ [r.x + r.w, r.y + r.h],
339
+ [r.x, r.y + r.h]
340
+ ];
341
+ var mapRect = (m, r) => boxOf(corners(r).map((p) => apply(m, p)));
342
+ function intersect(a, b) {
343
+ const x0 = Math.max(a.x, b.x);
344
+ const y0 = Math.max(a.y, b.y);
345
+ const x1 = Math.min(a.x + a.w, b.x + b.w);
346
+ const y1 = Math.min(a.y + a.h, b.y + b.h);
347
+ return x1 > x0 && y1 > y0 ? { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } : null;
348
+ }
349
+ var center = (r) => [r3(r.x + r.w / 2), r3(r.y + r.h / 2)];
350
+ var roundRect = (r) => ({ x: r3(r.x), y: r3(r.y), w: r3(r.w), h: r3(r.h) });
351
+ function shapeBox(s) {
352
+ if (s.kind === "rect" || s.kind === "mask") return { x: s.x, y: s.y, w: s.w, h: s.h };
353
+ if (s.kind === "ellipse") return { x: s.cx - s.rx, y: s.cy - s.ry, w: 2 * s.rx, h: 2 * s.ry };
354
+ return boxOf(s.points);
355
+ }
356
+ function placedBox(s) {
357
+ if (isUnit(s.m)) return shapeBox(s);
358
+ if (s.kind === "polygon") return boxOf(s.points.map((p) => apply(s.m, p)));
359
+ return mapRect(s.m, shapeBox(s));
360
+ }
361
+ var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
362
+ var SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
363
+ function headBytes(data, n) {
364
+ const out = [];
365
+ for (let i = 0; i + 3 < data.length && out.length < n; i += 4) {
366
+ const v = B64.indexOf(data[i]) << 18 | B64.indexOf(data[i + 1]) << 12 | Math.max(0, B64.indexOf(data[i + 2])) << 6 | Math.max(0, B64.indexOf(data[i + 3]));
367
+ out.push(v >> 16 & 255);
368
+ if (data[i + 2] !== "=") out.push(v >> 8 & 255);
369
+ if (data[i + 3] !== "=") out.push(v & 255);
370
+ }
371
+ return out.slice(0, n);
372
+ }
373
+ function crc32(bytes) {
374
+ let c = 4294967295;
375
+ for (const b of bytes) {
376
+ c ^= b;
377
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? c >>> 1 ^ 3988292384 : c >>> 1;
378
+ }
379
+ return (c ^ 4294967295) >>> 0;
380
+ }
381
+ var u32 = (b, at) => (b[at] << 24 | b[at + 1] << 16 | b[at + 2] << 8 | b[at + 3]) >>> 0;
382
+ function kindOf(b) {
383
+ if (b[0] === 255 && b[1] === 216 && b[2] === 255) return "a JPEG file";
384
+ if (b[0] === 71 && b[1] === 73 && b[2] === 70 && b[3] === 56) return "a GIF file";
385
+ if (b[0] === 82 && b[1] === 73 && b[2] === 70 && b[3] === 70 && b[8] === 87 && b[9] === 69 && b[10] === 66 && b[11] === 80) return "a WebP file";
386
+ if (b[0] === 66 && b[1] === 77) return "a BMP file";
387
+ if (b[0] === 60) return "an SVG or text file";
388
+ return null;
389
+ }
390
+ function pngHead(data, what, maxChars) {
391
+ if (typeof data !== "string" || data === "") throw new Reject("INVALID_INPUT", `${what} must be the base64 text of a PNG file`);
392
+ if (/^data:/i.test(data)) throw new Reject("INVALID_INPUT", `Remove the data: prefix at the start of ${what} and send only the base64 text`);
393
+ if (data.length > maxChars) throw new Reject("INVALID_INPUT", `${what} is longer than ${maxChars} characters (${data.length} characters)`);
394
+ if (data.length % 4 !== 0 || /[^A-Za-z0-9+/=]/.test(data)) {
395
+ throw new Reject("INVALID_INPUT", `${what} must contain only base64 characters (A-Z, a-z, 0-9, +, / and = at the end), and its length must be a multiple of 4. Do not put in line breaks or spaces`);
396
+ }
397
+ const eq = data.indexOf("=");
398
+ if (eq !== -1 && (eq < data.length - 2 || eq === data.length - 2 && data[data.length - 1] !== "=")) throw new Reject("INVALID_INPUT", `= in ${what} may appear only at the end`);
399
+ const bytes = data.length / 4 * 3 - (eq === -1 ? 0 : data.length - eq);
400
+ if (bytes > MAX_IMAGE_BYTES) throw new Reject("INVALID_INPUT", `An image file can be up to 4MB, ${MAX_IMAGE_BYTES} bytes. The file received is ${bytes} bytes`);
401
+ const b = headBytes(data, 33);
402
+ if (!SIGNATURE.every((v, i) => b[i] === v)) {
403
+ const kind = kindOf(b);
404
+ throw new Reject("INVALID_INPUT", `Only PNG files are accepted (${what}${kind ? ` is ${kind}` : " does not start with the PNG signature"})`);
405
+ }
406
+ if (b.length < 33) throw new Reject("INVALID_INPUT", `The PNG file in ${what} is too short (${bytes} bytes)`);
407
+ const type = String.fromCharCode(b[12], b[13], b[14], b[15]);
408
+ if (u32(b, 8) !== 13 || type !== "IHDR" || crc32(b.slice(12, 29)) !== u32(b, 29)) throw new Reject("INVALID_INPUT", `Could not read the PNG header (IHDR) of ${what}. Check whether the file is damaged`);
409
+ const width = u32(b, 16);
410
+ const height = u32(b, 20);
411
+ if (width < 1 || height < 1 || width > MAX_SIDE || height > MAX_SIDE) throw new Reject("INVALID_INPUT", `The width and height of a picture must be 1 to ${MAX_SIDE} pixels (${what} is ${width}\xD7${height})`);
412
+ return { width, height, bytes };
413
+ }
414
+ function bytesOf(data) {
415
+ const pad = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
416
+ return data.length / 4 * 3 - pad;
417
+ }
418
+ function maskKey(data) {
419
+ let h = 2166136261;
420
+ for (let i = 0; i < data.length; i += 1) {
421
+ h ^= data.charCodeAt(i);
422
+ h = Math.imul(h, 16777619);
423
+ }
424
+ return `mk${(h >>> 0).toString(16).padStart(8, "0")}-${data.length.toString(36)}`;
425
+ }
426
+ var MASK_KEY = /^mk[0-9a-f]{8}-[0-9a-z]+$/;
427
+ var finite = (v) => typeof v === "number" && Number.isFinite(v) && Math.abs(v) <= MAX_COORD;
428
+ var vec = (v) => Array.isArray(v) && v.length === 2 && finite(v[0]) && finite(v[1]);
429
+ function shapeProblem(s, withData = true) {
430
+ const x = s;
431
+ if (!x || typeof x !== "object") return "The shape is missing";
432
+ if (x.kind === "rect") return finite(x.x) && finite(x.y) && finite(x.w) && finite(x.h) && x.w > 0 && x.h > 0 ? null : "The values of the rectangle are wrong";
433
+ if (x.kind === "ellipse") return finite(x.cx) && finite(x.cy) && finite(x.rx) && finite(x.ry) && x.rx > 0 && x.ry > 0 ? null : "The values of the ellipse are wrong";
434
+ if (x.kind === "polygon") return Array.isArray(x.points) && x.points.length >= 3 && x.points.length <= MAX_POINTS && x.points.every(vec) ? null : `A polygon has 3 to ${MAX_POINTS} points, each [x, y]`;
435
+ if (x.kind === "mask") {
436
+ if (!finite(x.x) || !finite(x.y) || !Number.isInteger(x.w) || !Number.isInteger(x.h) || x.w < 1 || x.h < 1 || x.w > MAX_SIDE || x.h > MAX_SIDE) return "The position or size of the selection shape is wrong";
437
+ if (typeof x.key !== "string" || !MASK_KEY.test(x.key)) return "The name (key) of the selection shape is wrong";
438
+ if (!withData) return null;
439
+ if (typeof x.data !== "string" || x.data.length.toString(36) !== x.key.split("-")[1]) return "The data of the selection shape does not match its name (key)";
440
+ return null;
441
+ }
442
+ return "The kind of a shape is one of rect, ellipse, polygon, mask";
443
+ }
444
+ function matProblem(m) {
445
+ if (m === null) return null;
446
+ return Array.isArray(m) && m.length === 6 && m.every((v) => typeof v === "number" && Number.isFinite(v)) ? null : "The matrix (m) of a shape is null or six numbers";
447
+ }
448
+ function placeProblem(p) {
449
+ const x = p;
450
+ if (!x || typeof x !== "object") return "The placement (place) is missing";
451
+ if (!vec(x.move) || !finite(x.rotate) || !vec(x.scale) || !(x.pivot === null || vec(x.pivot))) return "A number in the placement (place) is wrong";
452
+ if (x.scale[0] === 0 || x.scale[1] === 0) return "The scale of a placement must not be 0";
453
+ if (x.pivot === null && !isIdentityTurn(x)) return "A placement that rotates or scales needs a pivot (pivot)";
454
+ return null;
455
+ }
456
+
457
+ // packages/plugin-png/src/model.ts
458
+ var NO_ADJUST = { hue: 0, saturate: 1, brightness: 1, tint: null, opacity: 1 };
459
+ var idNumber = (id) => Number(id.replace(/\D/g, ""));
460
+ var byIdNumber = (a, b) => {
461
+ const ta = a.id.startsWith("$") ? 1 : 0;
462
+ const tb = b.id.startsWith("$") ? 1 : 0;
463
+ if (ta !== tb) return ta - tb;
464
+ if (ta === 1) return 0;
465
+ return idNumber(a.id) - idNumber(b.id) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
466
+ };
467
+ var all = (s, type) => Object.values(s.records).filter((r) => r.type === type);
468
+ var keyOf = (r) => sortKey(r.content.order, r.id);
469
+ var byKey = (a, b) => keyOf(a) < keyOf(b) ? -1 : keyOf(a) > keyOf(b) ? 1 : 0;
470
+ function canvasRecord(s) {
471
+ return all(s, "canvas").sort(byIdNumber)[0];
472
+ }
473
+ function gridOf(c) {
474
+ return c ? makeGrid(c.width, c.height, QUAD_MIN_SIDE) : makeGrid(1, 1, QUAD_MIN_SIDE);
475
+ }
476
+ function innerOf(c, image) {
477
+ if (!image) return null;
478
+ let r = { x: 0, y: 0, w: image.width, h: image.height };
479
+ for (const s of c.clip) {
480
+ if (!r) break;
481
+ r = intersect(r, placedBox(s));
482
+ }
483
+ return r;
484
+ }
485
+ function defaultPivot(c, image) {
486
+ const inner = innerOf(c, image);
487
+ if (inner) return center(inner);
488
+ return image ? center({ x: 0, y: 0, w: image.width, h: image.height }) : [0, 0];
489
+ }
490
+ function pieceMatrix(c, image) {
491
+ const p = c.place;
492
+ if (isIdentityTurn(p)) return [1, 0, 0, 1, p.move[0], p.move[1]];
493
+ return placeMatrix(p, p.pivot ?? defaultPivot(c, image));
494
+ }
495
+ function buildModel(s) {
496
+ const cv = canvasRecord(s);
497
+ const canvas = cv ? { id: cv.id, c: cv.content } : null;
498
+ const images = all(s, "image").sort(byIdNumber).map((r) => ({ id: r.id, c: r.content }));
499
+ const imageOf2 = new Map(images.map((x) => [x.id, x]));
500
+ const pieces = all(s, "piece").sort(byKey).map((r, z) => {
501
+ const c = r.content;
502
+ const image = imageOf2.get(c.image) ?? null;
503
+ const matrix = pieceMatrix(c, image?.c);
504
+ const inner = innerOf(c, image?.c);
505
+ return { id: r.id, c, z, image, matrix, inner, box: inner ? mapRect(matrix, inner) : null };
506
+ });
507
+ const regions = all(s, "region").sort(byIdNumber).map((r) => ({ id: r.id, c: r.content, box: shapeBox(r.content.shape) }));
508
+ return { canvas, images, pieces, byId: new Map(pieces.map((p) => [p.id, p])), regions, grid: gridOf(canvas?.c ?? null) };
509
+ }
510
+ var SIDE_WORD = { 1: "top left", 2: "top right", 3: "bottom left", 4: "bottom right" };
511
+ function sectionProblem(grid, id) {
512
+ if (!pieceProblem(grid, id)) return null;
513
+ const path = piecePath(id);
514
+ if (!path) {
515
+ return {
516
+ depth: false,
517
+ message: `Section id ${JSON.stringify(id)} has the wrong form. The root is q, and its children are joined with dots, like q.1 (top left), q.2 (top right), q.3 (bottom left), q.4 (bottom right)`
518
+ };
519
+ }
520
+ return { depth: true, message: `Section ${id} is at level ${path.length}, but the deepest level in this picture is ${grid.depth}` };
521
+ }
522
+ function quadOfBox(m, box) {
523
+ if (!box || !m.canvas) return null;
524
+ const inside = box.x >= 0 && box.y >= 0 && box.x + box.w <= m.canvas.c.width && box.y + box.h <= m.canvas.c.height;
525
+ return inside ? smallestPieceContaining(m.grid, box) : null;
526
+ }
527
+
528
+ // packages/plugin-png/src/view.ts
529
+ var VIEWS = [
530
+ {
531
+ summary: "See one section larger. Sections are rectangles made by splitting the canvas into four, again and again. See the overall shape in an upper section, and go down to lower sections for detail",
532
+ input: {
533
+ piece: "Section id. q is the whole picture, and q.1 is the top left, q.2 the top right, q.3 the bottom left, q.4 the bottom right. Chain them like q.2.3",
534
+ margin: "Extra pixels to show around it (0 to 512). If left out, 0"
535
+ },
536
+ example: { piece: "q.2" }
537
+ },
538
+ {
539
+ summary: "See the area one piece covers, larger",
540
+ input: {
541
+ piece: "Piece id (pc and a number)",
542
+ alone: "If true, draws only that piece (other pieces are left out, and it shows even if hidden). If left out, shows the picture as it is seen there",
543
+ margin: "Extra pixels to show around it (0 to 512). If left out, 0"
544
+ },
545
+ example: { piece: "pc2", alone: true }
546
+ },
547
+ {
548
+ summary: "See a rectangle or a saved region larger",
549
+ input: {
550
+ region: 'A rectangle { "x": , "y": , "w": , "h": } (canvas positions) or a region id (rg and a number)',
551
+ mark: "If true, paints the shape of the region given by id in pink on top. Use it to see where the person selected",
552
+ margin: "Extra pixels to show around it (0 to 512). If left out, 0"
553
+ },
554
+ example: { region: "rg1", mark: true, margin: 24 }
555
+ }
556
+ ];
557
+ var MARK_COLOR = "#ff2bd6";
558
+ var MAX_MARGIN = 512;
559
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
560
+ function viewSvg(m, scene, dataOf, view) {
561
+ if (!isObject(view)) throw new Reject("INVALID_INPUT", 'view must be an object. For example: { "piece": "q.2" }');
562
+ const canvas = m.canvas.c;
563
+ const hasPiece = view.piece !== void 0;
564
+ const hasRegion = view.region !== void 0;
565
+ if (hasPiece === hasRegion) {
566
+ throw new Reject("INVALID_INPUT", "Give view only one of piece (a section id or piece id) and region (a rectangle or region id). Read the whole picture without view");
567
+ }
568
+ let margin = 0;
569
+ if (view.margin !== void 0) {
570
+ if (typeof view.margin !== "number" || !Number.isFinite(view.margin) || view.margin < 0 || view.margin > MAX_MARGIN) {
571
+ throw new Reject("INVALID_INPUT", `margin must be a number from 0 to ${MAX_MARGIN}. Received: ${JSON.stringify(view.margin)}`);
572
+ }
573
+ margin = view.margin;
574
+ }
575
+ for (const k of ["alone", "mark"]) {
576
+ if (view[k] !== void 0 && typeof view[k] !== "boolean") throw new Reject("INVALID_INPUT", `${k} must be true or false. Received: ${JSON.stringify(view[k])}`);
577
+ }
578
+ let rect;
579
+ let label2;
580
+ let shown = scene;
581
+ let mark = "";
582
+ let extraDefs = "";
583
+ if (hasPiece) {
584
+ if (typeof view.piece !== "string") throw new Reject("INVALID_INPUT", `piece must be text: a section id (q, q.2.3) or a piece id (pc and a number). Received: ${JSON.stringify(view.piece)}`);
585
+ if (view.mark !== void 0) throw new Reject("INVALID_INPUT", "mark is used only when region is a region id");
586
+ const id = view.piece;
587
+ if (id === "q" || id.startsWith("q.")) {
588
+ if (view.alone !== void 0) throw new Reject("INVALID_INPUT", "alone is used only when piece is a piece id (pc and a number)");
589
+ const problem = sectionProblem(m.grid, id);
590
+ if (problem) throw new Reject(problem.depth ? "TARGET_NOT_FOUND" : "INVALID_INPUT", problem.message);
591
+ rect = pieceRect(m.grid, id);
592
+ label2 = `section ${id}`;
593
+ } else {
594
+ const node = m.byId.get(id);
595
+ if (!node) {
596
+ throw new Reject("TARGET_NOT_FOUND", `There is no piece ${id}. Existing pieces: ${m.pieces.map((p) => p.id).join(", ") || "none"}. Write sections like q, q.2.3`);
597
+ }
598
+ if (!node.box) throw new Reject("INVALID_STATE", `Piece ${id} covers no area, so there is nothing to see`);
599
+ rect = node.box;
600
+ label2 = `piece ${id}${view.alone ? " (that piece only)" : ""}`;
601
+ if (view.alone) shown = { ...scene, pieces: scene.pieces.filter((p) => p.id === id).map((p) => ({ ...p, hidden: false })) };
602
+ }
603
+ } else {
604
+ if (view.alone !== void 0) throw new Reject("INVALID_INPUT", "alone is used only when piece is a piece id (pc and a number)");
605
+ if (typeof view.region === "string") {
606
+ const id = view.region;
607
+ const region = m.regions.find((r) => r.id === id);
608
+ if (!region) throw new Reject("TARGET_NOT_FOUND", `There is no region ${id}. Existing regions: ${m.regions.map((r) => r.id).join(", ") || "none"}`);
609
+ rect = region.box;
610
+ label2 = `region ${id}${view.mark ? " (shape painted over in pink)" : ""}`;
611
+ if (view.mark) {
612
+ const shape = region.c.shape;
613
+ if (shape.kind === "mask") extraDefs = `<image id="m-${pdName(shape.key)}" width="${pdNum(shape.w)}" height="${pdNum(shape.h)}" href="data:image/png;base64,${dataOf(shape.key)}"/>`;
614
+ const area = ` maskUnits="userSpaceOnUse" x="0" y="0" width="${pdNum(canvas.width)}" height="${pdNum(canvas.height)}"`;
615
+ extraDefs += `<mask id="v-mark"${area} mask-type="alpha" style="mask-type:alpha">${pdShape({ ...shape, m: null })}</mask>`;
616
+ mark = `<rect x="0" y="0" width="${pdNum(canvas.width)}" height="${pdNum(canvas.height)}" fill="${MARK_COLOR}" opacity="0.5" mask="url(#v-mark)"/>`;
617
+ }
618
+ } else if (isObject(view.region)) {
619
+ const r = view.region;
620
+ for (const k of ["x", "y", "w", "h"]) {
621
+ if (typeof r[k] !== "number" || !Number.isFinite(r[k])) throw new Reject("INVALID_INPUT", `${k} of region must be a number. region has the form { "x": , "y": , "w": , "h": }. Received: ${JSON.stringify(view.region)}`);
622
+ }
623
+ if (!(r.w > 0 && r.h > 0)) throw new Reject("INVALID_INPUT", `w and h of region must be greater than 0. Received: ${JSON.stringify(view.region)}`);
624
+ if (view.mark !== void 0) throw new Reject("INVALID_INPUT", "mark is used only when region is a region id");
625
+ rect = { x: r.x, y: r.y, w: r.w, h: r.h };
626
+ label2 = `rectangle x ${pdNum(rect.x)} y ${pdNum(rect.y)} ${pdNum(rect.w)}\xD7${pdNum(rect.h)}`;
627
+ } else {
628
+ throw new Reject("INVALID_INPUT", `region is a rectangle { "x": , "y": , "w": , "h": } or region id text (rg and a number). Received: ${JSON.stringify(view.region)}`);
629
+ }
630
+ }
631
+ const grown = { x: rect.x - margin, y: rect.y - margin, w: rect.w + margin * 2, h: rect.h + margin * 2 };
632
+ const inside = intersect(grown, { x: 0, y: 0, w: canvas.width, h: canvas.height });
633
+ if (!inside || !(inside.w > 0 && inside.h > 0)) {
634
+ throw new Reject("INVALID_INPUT", `Nothing to see: ${label2} is outside the canvas (${canvas.width}\xD7${canvas.height})`);
635
+ }
636
+ const x0 = Math.floor(inside.x);
637
+ const y0 = Math.floor(inside.y);
638
+ const x1 = Math.min(canvas.width, Math.ceil(inside.x + inside.w));
639
+ const y1 = Math.min(canvas.height, Math.ceil(inside.y + inside.h));
640
+ const out = { x: x0, y: y0, w: Math.max(1, x1 - x0), h: Math.max(1, y1 - y0) };
641
+ const seen = shown.pieces.filter((p) => {
642
+ const box = m.byId.get(p.id)?.box;
643
+ return !!box && !!intersect(box, out);
644
+ });
645
+ const parts = pdParts({ ...shown, pieces: seen, area: out }, dataOf, true);
646
+ if (extraDefs.startsWith("<image") && parts.maskDefs.includes(extraDefs.slice(0, extraDefs.indexOf(" width=")))) extraDefs = extraDefs.slice(extraDefs.indexOf("/>") + 2);
647
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${pdNum(out.w)}" height="${pdNum(out.h)}" viewBox="${pdNum(out.x)} ${pdNum(out.y)} ${pdNum(out.w)} ${pdNum(out.h)}"><defs>${parts.imageDefs}${parts.maskDefs}${parts.pieceDefs}${extraDefs}</defs>${parts.body}${mark}</svg>`;
648
+ return { svg, label: `${label2}, canvas x ${out.x}~${out.x + out.w} y ${out.y}~${out.y + out.h}(${out.w}\xD7${out.h})`, rect: out };
649
+ }
650
+
651
+ // packages/plugin-png/src/read.ts
652
+ var MAX_TARGETS = 20;
653
+ var DATA_SCOPE = "data:";
654
+ var q = (t) => JSON.stringify(t);
655
+ var pt = (x, y) => `(${fmt(x)}, ${fmt(y)})`;
656
+ var boxText = (r) => `x ${fmt1(r.x)}~${fmt1(r.x + r.w)} y ${fmt1(r.y)}~${fmt1(r.y + r.h)}(${fmt1(r.w)}\xD7${fmt1(r.h)})`;
657
+ var many = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
658
+ var SHAPE_WORD = { rect: "rectangle", ellipse: "ellipse", polygon: "polygon", mask: "selection shape" };
659
+ function shapeText(s, full = false) {
660
+ if (s.kind === "rect") return `rectangle ${boxText(s)}`;
661
+ if (s.kind === "ellipse") return `ellipse center ${pt(s.cx, s.cy)} horizontal radius ${fmt(s.rx)} vertical radius ${fmt(s.ry)}`;
662
+ if (s.kind === "polygon") {
663
+ const box = { x: Math.min(...s.points.map((p) => p[0])), y: Math.min(...s.points.map((p) => p[1])), w: 0, h: 0 };
664
+ box.w = Math.max(...s.points.map((p) => p[0])) - box.x;
665
+ box.h = Math.max(...s.points.map((p) => p[1])) - box.y;
666
+ return full ? `polygon with ${many(s.points.length, "point")} ${s.points.map((p) => pt(p[0], p[1])).join(" ")}` : `polygon with ${many(s.points.length, "point")}, bounding rectangle ${boxText(box)}`;
667
+ }
668
+ return `selection shape (selected by pixels on the screen, name ${s.key}) ${boxText(s)}`;
669
+ }
670
+ function placeText(p) {
671
+ if (isIdentity(p)) return "none";
672
+ const out = [];
673
+ if (p.move[0] !== 0 || p.move[1] !== 0) out.push(`move ${pt(p.move[0], p.move[1])}`);
674
+ if (p.rotate !== 0) out.push(`rotate ${fmt(p.rotate)}\xB0`);
675
+ if (p.scale[0] !== 1 || p.scale[1] !== 1) out.push(p.scale[0] === p.scale[1] ? `scale ${fmt(p.scale[0])}` : `scale horizontal ${fmt(p.scale[0])} vertical ${fmt(p.scale[1])}`);
676
+ if (!isIdentityTurn(p) && p.pivot) out.push(`pivot ${pt(p.pivot[0], p.pivot[1])}`);
677
+ return out.join(", ");
678
+ }
679
+ function adjustText(a) {
680
+ const out = [];
681
+ if (a.hue !== 0) out.push(`hue ${fmt(a.hue)}\xB0`);
682
+ if (a.saturate !== 1) out.push(`saturation ${fmt(a.saturate)}`);
683
+ if (a.brightness !== 1) out.push(`brightness ${fmt(a.brightness)}`);
684
+ if (a.tint) out.push(`tint ${a.tint.color} ${fmt(a.tint.amount)}`);
685
+ if (a.opacity !== 1) out.push(`opacity ${fmt(a.opacity)}`);
686
+ return out.length ? out.join(", ") : "none";
687
+ }
688
+ var nameText = (name) => name ? q(name) : "(no name)";
689
+ var pieceLabel = (n) => `(${n.id}) ${nameText(n.c.name)}`;
690
+ var regionLabel = (r) => `(${r.id}) ${r.c.name ? q(r.c.name) : r.c.auto ? "(unnamed automatic region)" : "(no name)"}`;
691
+ function pieceLine(n, star = "") {
692
+ const c = n.c;
693
+ const parts = [
694
+ `(${n.id})${star} ${nameText(c.name)}`,
695
+ `image file ${c.image}`,
696
+ n.box ? `covered area (estimate) ${boxText(n.box)}` : "no covered area (its visible areas do not overlap the image file)",
697
+ `placement ${placeText(c.place)}`,
698
+ `color adjustment ${adjustText(c.adjust)}`,
699
+ `${many(c.clip.length, "visible area")}, ${many(c.holes.length, "erased area")}`
700
+ ];
701
+ if (c.hidden) parts.push("hidden");
702
+ if (c.from) parts.push(`lifted from ${c.from}`);
703
+ return parts.join(", ");
704
+ }
705
+ function regionLine(r, star = "") {
706
+ const head = `(${r.id})${star} ${r.c.name ? q(r.c.name) : "(no name)"}`;
707
+ const auto = r.c.auto ? ", automatic region (saved by the screen to send to the AI)" : "";
708
+ return `${head} ${shapeText(r.c.shape)}${auto}${r.c.note ? `. Note: ${r.c.note}` : ""}`;
709
+ }
710
+ var placedNow = (n, s) => mapRect(n.matrix, placedBox(s));
711
+ var placedLine = (n, s) => `- ${SHAPE_WORD[s.kind]}${s.kind === "mask" ? ` (name ${s.key})` : ""}, now on the canvas at ${boxText(placedNow(n, s))}`;
712
+ var visibleOver = (m, box) => m.pieces.filter((n) => !n.c.hidden && n.box && overlaps(n.box, box)).reverse();
713
+ function quadWords(m, box) {
714
+ const quad = quadOfBox(m, box);
715
+ return quad ? `Smallest section that holds all of it: ${quad}` : "It goes outside the canvas, so no section holds all of it";
716
+ }
717
+ function overviewRead(m, star) {
718
+ const cv = m.canvas;
719
+ const src = cv.c.source ? ` Started from sample ${cv.c.source.sample} (${cv.c.source.title}).` : "";
720
+ const lines = [
721
+ `Canvas (${cv.id})${star(cv.id)}: ${fmt(cv.c.width)}\xD7${fmt(cv.c.height)} pixels.${src}${cv.c.reason ? ` Reason for starting: ${cv.c.reason}` : ""}`,
722
+ "Positions are canvas pixels. x grows to the right and y grows downward, and (0, 0) is the top left. Rotation is in degrees clockwise.",
723
+ "The logic cannot see pixels. A covered area is an estimate that includes transparent pixels. See the picture with read_image.",
724
+ "",
725
+ m.images.length ? `${many(m.images.length, "image file")}:` : "Image files: none. Only the person adds image files, on the screen.",
726
+ ...m.images.map((x) => `- (${x.id})${star(x.id)} ${q(x.c.name)} ${x.c.width}\xD7${x.c.height}, ${x.c.bytes} bytes`),
727
+ "",
728
+ m.pieces.length ? `${many(m.pieces.length, "piece")} (stacking order, bottom to top):` : "Pieces: none. The person adds image files as pieces on the screen.",
729
+ ...m.pieces.map((n) => `- ${pieceLine(n, star(n.id))}`),
730
+ "",
731
+ m.regions.length ? `${many(m.regions.length, "region")}:` : "Regions: none",
732
+ ...m.regions.map((r) => `- ${regionLine(r, star(r.id))}`),
733
+ "",
734
+ `Sections: rectangles made by splitting the canvas into four, again and again. They go from the root q down to the deepest level ${m.grid.depth} (each side at least ${QUAD_MIN_SIDE} pixels). q.1 is the top left, q.2 the top right, q.3 the bottom left and q.4 the bottom right. Give a section id as the scope to read only the pieces and regions that overlap that section. Give a piece id or region id as the scope to read it in detail, including its shape.`
735
+ ];
736
+ return { text: lines.join("\n"), records: [cv.id, ...m.images.map((x) => x.id), ...m.pieces.map((n) => n.id), ...m.regions.map((r) => r.id)] };
737
+ }
738
+ function pieceRead(m, id, star) {
739
+ const n = m.byId.get(id);
740
+ const c = n.c;
741
+ const img = n.image;
742
+ const lifted = m.pieces.filter((k) => k.c.from === id);
743
+ const lines = [
744
+ `Piece (${id})${star(id)} ${nameText(c.name)}: image file ${c.image}${img ? ` (${q(img.c.name)}, ${img.c.width}\xD7${img.c.height})` : " (missing)"}. It is number ${n.z + 1} from the bottom in the stacking order of ${many(m.pieces.length, "piece")}.${c.hidden ? " It is a hidden piece, so it does not show in the picture." : ""}`,
745
+ c.from ? `Lifted from ${c.from}${m.byId.has(c.from) ? "" : " (now removed)"}.` : "A piece that has shown one image file from the start.",
746
+ `Placement: ${placeText(c.place)}`,
747
+ `Color adjustment: ${adjustText(c.adjust)}`,
748
+ n.inner ? `Area covered inside the piece (pixel positions in the image file): ${boxText(n.inner)}` : "Area covered inside the piece: none",
749
+ n.box ? `Area covered on the canvas (estimate): ${boxText(n.box)}. ${quadWords(m, n.box)}` : "Area covered on the canvas: none",
750
+ c.clip.length ? `${many(c.clip.length, "visible area")} (only the part inside all of them shows):` : "Visible area: the whole image file",
751
+ ...c.clip.map((s) => placedLine(n, s)),
752
+ c.holes.length ? `${many(c.holes.length, "erased area")} (piece.unerase restores all of them):` : "Erased areas: none",
753
+ ...c.holes.map((s) => placedLine(n, s))
754
+ ];
755
+ if (lifted.length) lines.push(`Pieces lifted from this piece: ${lifted.map(pieceLabel).join(", ")}`);
756
+ const regions = n.box ? m.regions.filter((r) => overlaps(r.box, n.box)) : [];
757
+ if (regions.length) lines.push(`Overlapping regions: ${regions.map(regionLabel).join(", ")}`);
758
+ return { text: lines.join("\n"), records: [id, c.image, ...lifted.map((k) => k.id)] };
759
+ }
760
+ function regionRead(m, id, star) {
761
+ const r = m.regions.find((x) => x.id === id);
762
+ const over = visibleOver(m, r.box);
763
+ const lines = [
764
+ `Region ${regionLine(r, star(id))}`,
765
+ r.c.shape.kind === "polygon" ? shapeText(r.c.shape, true) : "",
766
+ `Bounding rectangle: ${boxText(r.box)}. ${quadWords(m, r.box)}`,
767
+ `Give "${id}" as where to lift or erase exactly this shape.`,
768
+ over.length ? `Visible pieces overlapping it (by estimated covered area, top to bottom): ${over.map(pieceLabel).join(", ")}` : "Visible pieces overlapping it: none"
769
+ ].filter(Boolean);
770
+ return { text: lines.join("\n"), records: [id, ...over.map((n) => n.id)] };
771
+ }
772
+ function quadRead(m, quad, star) {
773
+ const area = pieceRect(m.grid, quad);
774
+ const d = pieceDepth(quad);
775
+ const head = d === 0 ? `Section q (the root, the whole canvas). Level 0, deepest level ${m.grid.depth}. ${boxText(area)}.` : `Section ${quad} (level ${d}, deepest level ${m.grid.depth}). ${boxText(area)}. It is the ${SIDE_WORD[quadrantOf(quad)]} of the parent section ${parentPiece(quad)}.`;
776
+ const pieces = m.pieces.filter((n) => n.box && overlaps(n.box, area));
777
+ const regions = m.regions.filter((r) => overlaps(r.box, area));
778
+ const lines = [
779
+ head,
780
+ "",
781
+ pieces.length ? `Pieces overlapping here (${pieces.length}, by estimated covered area, bottom to top):` : "Pieces overlapping here: none",
782
+ ...pieces.map((n) => `- ${pieceLine(n, star(n.id))}`),
783
+ "",
784
+ regions.length ? `Regions overlapping here (${regions.length}):` : "Regions overlapping here: none",
785
+ ...regions.map((r) => `- ${regionLine(r, star(r.id))}`)
786
+ ];
787
+ const kids = childPieces(m.grid, quad);
788
+ lines.push("", kids.length ? `Lower sections: ${kids.map((k) => `${k} (${SIDE_WORD[quadrantOf(k)]}, ${boxText(pieceRect(m.grid, k))})`).join(", ")}` : "This is the deepest level, so there are no lower sections.");
789
+ return { text: lines.join("\n"), records: [...pieces.map((n) => n.id), ...regions.map((r) => r.id)] };
790
+ }
791
+ function readScope(m, ids, star) {
792
+ if (!m.canvas) {
793
+ if (ids && ids.length) throw new Reject("TARGET_NOT_FOUND", `There is no canvas yet, so ${ids.join(", ")} cannot be read`);
794
+ return { text: "", records: [], scopeLabel: "Read everything" };
795
+ }
796
+ if (ids === null || ids.length === 0) return { ...overviewRead(m, star), scopeLabel: "Read everything" };
797
+ if (ids.length > MAX_TARGETS) throw new Reject("INVALID_INPUT", `Up to ${MAX_TARGETS} scopes can be read at once (got ${ids.length})`);
798
+ const parts = [];
799
+ const records = /* @__PURE__ */ new Set();
800
+ for (const id of ids) {
801
+ let r;
802
+ if (typeof id === "string" && /^q(\.|$)/.test(id)) {
803
+ const problem = sectionProblem(m.grid, id);
804
+ if (problem) throw new Reject("TARGET_NOT_FOUND", problem.message);
805
+ r = quadRead(m, id, star);
806
+ } else if (m.byId.has(id)) r = pieceRead(m, id, star);
807
+ else if (m.regions.some((x) => x.id === id)) r = regionRead(m, id, star);
808
+ else if (id === m.canvas.id) r = overviewRead(m, star);
809
+ else throw new Reject("TARGET_NOT_FOUND", `Cannot find scope ${id}. Use a piece id (pc3), region id (rg2) or section id (q, q.2.3) as the scope`);
810
+ parts.push(r.text);
811
+ for (const x of r.records) records.add(x);
812
+ }
813
+ return { text: parts.join("\n\n---\n\n"), records: [...records], scopeLabel: `Read ${ids.join(", ")}` };
814
+ }
815
+
816
+ // packages/plugin-png/src/samples.ts
817
+ var APPLE_PNG = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAABC0lEQVR42u2awQ3CMAxFuwscOgNLMBKT0LFYJ5wqRYiSOKSK8/2e5GPU/pdDXKfLAgAAAABzcHte0l5TB3ncr2kvS+hvJSugFFxWQG1wSQEhwh8JsIaXEhAqfA8B05/nuYBw4VsFSHV0FgGSLW3pFJDv6S2t8HS81jX9qiMBNeumDf1ZuQDrWncyWgL8K8CFhNYX712hww+RUHqZtG26EkrB85KUUBteUoBl90cJOFWCJbycAOvujxRwigQERBZQc+57Ct9dAgKMAuTa45qHeQo+RIDHQgACELCElSA/AUKAty/CEPPB8AJmkBBuHO5uMszdALdDQcJ7EDH9DbFM+JYfJHquAwAAAGjhDZxbgdKPQ5rTAAAAAElFTkSuQmCC";
818
+ var SAMPLES = [
819
+ {
820
+ id: "apple",
821
+ version: "1",
822
+ title: "Apple",
823
+ about: "A 64\xD764 picture of an apple. On a transparent background, the red body, pink highlight, brown stem and green leaf each have one flat color. Use it for a quick try of lifting, moving and color adjustment",
824
+ data: APPLE_PNG
825
+ }
826
+ ];
827
+ var sampleById = (id) => SAMPLES.find((s) => s.id === id);
828
+
829
+ // packages/plugin-png/src/logic.ts
830
+ var PACKAGE_ID = "aic.png";
831
+ var VERSION = "0.1.3";
832
+ var TITLE = "PNG Image";
833
+ var SELECTION_FORMAT = "aic.png/selection-1";
834
+ var OUTPUT_MEDIA_TYPE = "image/svg+xml; charset=utf-8";
835
+ var pc = (r) => r.content;
836
+ var MAX_NAME = 80;
837
+ var MAX_FILE_NAME = 120;
838
+ var MAX_NOTE = 1e3;
839
+ var MAX_REASON = 1e3;
840
+ var MAX_IMAGE_CHARS = Math.ceil(MAX_IMAGE_BYTES / 3) * 4;
841
+ var TYPE_WORD = { canvas: "a canvas", image: "an image file", piece: "a piece", region: "a region" };
842
+ function need(s, id, type, field) {
843
+ if (typeof id !== "string" || id === "") throw new Reject("INVALID_INPUT", `${field} needs the id of ${TYPE_WORD[type] ?? type}`);
844
+ const r = s.records[id];
845
+ if (!r) throw new Reject("TARGET_NOT_FOUND", `Cannot find ${type} ${id} given in ${field}. Check the id with read_concept`);
846
+ if (r.type !== type) throw new Reject("INVALID_INPUT", `${id} given in ${field} is ${TYPE_WORD[r.type] ?? r.type}, not ${TYPE_WORD[type] ?? type}`);
847
+ return r;
848
+ }
849
+ function needCanvas(s) {
850
+ const r = canvasRecord(s);
851
+ if (!r) throw new Reject("INVALID_STATE", "There is no canvas yet. Only the person adds image files, on the screen. Start a sample or an empty canvas with canvas.start");
852
+ return { r, c: r.content };
853
+ }
854
+ function onlyKeys(input, allowed, op) {
855
+ const extra = Object.keys(input).filter((k) => !allowed.includes(k));
856
+ if (extra.length) throw new Reject("INVALID_INPUT", `Unknown fields for ${op}: ${extra.join(", ")}. Accepted fields: ${allowed.join(", ")}`);
857
+ }
858
+ function textInput(v, what, ctx, max) {
859
+ if (v === void 0 || v === null) return "";
860
+ if (typeof v !== "string") throw new Reject("INVALID_INPUT", `${what} must be text`);
861
+ const t = v.replace(/\r\n?/g, "\n").trim();
862
+ if (t.length > max) throw new Reject("INVALID_INPUT", `${what} is longer than ${max} characters (${t.length} characters)`);
863
+ if (ctx.tempNames.includes(t)) throw new Reject("INVALID_INPUT", `"${t}" is the same as a temporary name in this request, so it cannot be used as text`);
864
+ return t;
865
+ }
866
+ function nameInput(v, what, ctx, max) {
867
+ const t = textInput(v, what, ctx, max);
868
+ if (/[\u0000-\u001f\u007f]/.test(t)) throw new Reject("INVALID_INPUT", `${what} must not contain line breaks or control characters`);
869
+ return t;
870
+ }
871
+ var baseName = (name) => name.replace(/\.[A-Za-z0-9]{1,5}$/, "").slice(0, MAX_NAME);
872
+ function imageInput(v, ctx) {
873
+ if (!v || typeof v !== "object" || Array.isArray(v)) throw new Reject("INVALID_INPUT", 'image is { "name": file name, "data": base64 of the PNG file }. Only the person adds image files, on the screen');
874
+ onlyKeys(v, ["name", "data"], "image");
875
+ const o = v;
876
+ const head = pngHead(o.data, "image.data", MAX_IMAGE_CHARS);
877
+ const name = nameInput(o.name, "image.name (file name)", ctx, MAX_FILE_NAME) || "picture.png";
878
+ return { name, mime: "image/png", width: head.width, height: head.height, bytes: head.bytes, data: o.data };
879
+ }
880
+ var WHERE_HELP = 'The area (where) is one of: a region id ("rg3"), { "rect": [x, y, w, h] }, { "ellipse": [cx, cy, rx, ry] }, { "polygon": [[x, y], ...] }, { "mask": { "x", "y", "w", "h", "data" } } (a shape the screen selected by pixels). All are canvas positions';
881
+ function fourInput(v, names, what, positive) {
882
+ let list = null;
883
+ if (Array.isArray(v) && v.length === 4) list = v;
884
+ else if (v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).sort().join() === [...names].sort().join()) list = names.map((k) => v[k]);
885
+ if (!list) throw new Reject("INVALID_INPUT", `${what} is four numbers in the form [${names.join(", ")}]. Received: ${JSON.stringify(v) ?? "nothing"}`);
886
+ return list.map((x, i) => numInput(x, `${names[i]} of ${what}`, { positive: positive.includes(names[i]) }));
887
+ }
888
+ var copyShape = (s) => s.kind === "polygon" ? { kind: "polygon", points: s.points.map((p) => [p[0], p[1]]) } : { ...s };
889
+ function whereInput(s, v) {
890
+ if (v === void 0 || v === null) throw new Reject("INVALID_INPUT", `where is required. ${WHERE_HELP}`);
891
+ if (typeof v === "string") {
892
+ if (/^q(\.[1-4])*$/.test(v)) throw new Reject("INVALID_INPUT", `A section (${v}) cannot be used as where. Give the rectangle of the section as { "rect": [x, y, w, h] } (read_concept shows the rectangle when you give the section id as the scope)`);
893
+ const r = s.records[v];
894
+ if (!r) throw new Reject("TARGET_NOT_FOUND", `Cannot find region ${v}. ${WHERE_HELP}`);
895
+ if (r.type !== "region") throw new Reject("INVALID_INPUT", `${v} is ${TYPE_WORD[r.type] ?? r.type}, not a region. Text in where is a region id`);
896
+ return { shape: copyShape(r.content.shape), region: v };
897
+ }
898
+ if (typeof v !== "object" || Array.isArray(v) || Object.keys(v).length !== 1) throw new Reject("INVALID_INPUT", `where has the wrong form. An object has exactly one key. ${WHERE_HELP}`);
899
+ const kind = Object.keys(v)[0];
900
+ const val = v[kind];
901
+ if (kind === "rect") {
902
+ const [x, y, w, h] = fourInput(val, ["x", "y", "w", "h"], "rect", ["w", "h"]);
903
+ return { shape: { kind: "rect", x, y, w, h }, region: null };
904
+ }
905
+ if (kind === "ellipse") {
906
+ const [cx, cy, rx, ry] = fourInput(val, ["cx", "cy", "rx", "ry"], "ellipse", ["rx", "ry"]);
907
+ return { shape: { kind: "ellipse", cx, cy, rx, ry }, region: null };
908
+ }
909
+ if (kind === "polygon") {
910
+ if (!Array.isArray(val)) throw new Reject("INVALID_INPUT", "polygon is a list of points in the form [[x, y], ...]");
911
+ if (val.length < 3 || val.length > MAX_POINTS) throw new Reject("INVALID_INPUT", `A polygon has 3 to ${MAX_POINTS} points (got ${val.length})`);
912
+ const points = val.map((p, i) => vecInput(p, `polygon[${i}]`));
913
+ let area = 0;
914
+ for (let i = 0; i < points.length; i += 1) {
915
+ const [x0, y0] = points[i];
916
+ const [x1, y1] = points[(i + 1) % points.length];
917
+ area += x0 * y1 - x1 * y0;
918
+ }
919
+ if (Math.abs(area) < 1e-6) throw new Reject("INVALID_INPUT", "The polygon points are all on one line, so it has no area");
920
+ return { shape: { kind: "polygon", points }, region: null };
921
+ }
922
+ if (kind === "mask") {
923
+ if (!val || typeof val !== "object" || Array.isArray(val)) throw new Reject("INVALID_INPUT", 'mask is { "x", "y", "w", "h", "data" }. The screen uses it to send a shape selected by pixels');
924
+ onlyKeys(val, ["x", "y", "w", "h", "data"], "mask");
925
+ const o = val;
926
+ const side = (n, what) => {
927
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_SIDE) throw new Reject("INVALID_INPUT", `${what} of mask must be a whole number from 1 to ${MAX_SIDE}. Received: ${JSON.stringify(n) ?? "nothing"}`);
928
+ return n;
929
+ };
930
+ const x = numInput(o.x, "x of mask");
931
+ const y = numInput(o.y, "y of mask");
932
+ const w = side(o.w, "w");
933
+ const h = side(o.h, "h");
934
+ const head = pngHead(o.data, "mask.data", MAX_MASK_CHARS);
935
+ if (head.width !== w || head.height !== h) throw new Reject("INVALID_INPUT", `The mask PNG is ${head.width}\xD7${head.height}, but w, h is ${w}\xD7${h}. Make the selection shape PNG the same size as the area (w, h)`);
936
+ const data = o.data;
937
+ return { shape: { kind: "mask", x, y, w, h, key: maskKey(data), data }, region: null };
938
+ }
939
+ throw new Reject("INVALID_INPUT", `${kind} in where is an unknown shape. ${WHERE_HELP}`);
940
+ }
941
+ var whereWords = (w) => w.region ? `region ${w.region} (${shapeText(w.shape)})` : shapeText(w.shape);
942
+ function placeOn(shape, matrix) {
943
+ return { ...shape, m: isUnit(matrix) ? null : roundMat(invert(matrix)) };
944
+ }
945
+ function scaleInput(v) {
946
+ const one = (x, what) => {
947
+ if (typeof x !== "number" || !Number.isFinite(x) || Math.abs(x) > 100 || Math.abs(x) < 0.01) {
948
+ throw new Reject("INVALID_INPUT", `${what} must be a number whose size is from 0.01 to 100. A negative number flips. Received: ${JSON.stringify(x) ?? "nothing"}`);
949
+ }
950
+ return r4(x);
951
+ };
952
+ if (typeof v === "number") return [one(v, "scale"), one(v, "scale")];
953
+ if (Array.isArray(v) && v.length === 2) return [one(v[0], "horizontal scale"), one(v[1], "vertical scale")];
954
+ if (v && typeof v === "object" && Object.keys(v).sort().join() === "x,y") return [one(v.x, "horizontal scale"), one(v.y, "vertical scale")];
955
+ throw new Reject("INVALID_INPUT", "scale is one number (the same for width and height) or [horizontal, vertical]");
956
+ }
957
+ var PLACE_KEYS = ["move", "rotate", "scale", "pivot"];
958
+ var ADJUST_KEYS = ["hue", "saturate", "brightness", "tint", "opacity"];
959
+ function placeInput(input, base, pivotFor) {
960
+ const move = input.move !== void 0 ? vecInput(input.move, "move") : base.move;
961
+ const rotate = input.rotate !== void 0 ? numInput(input.rotate, "rotate (degrees)", { min: -360, max: 360 }) : base.rotate;
962
+ const scale = input.scale !== void 0 ? scaleInput(input.scale) : base.scale;
963
+ let pivot = input.pivot === void 0 ? base.pivot : input.pivot === null ? null : vecInput(input.pivot, "pivot");
964
+ if (pivot === null && !isIdentityTurn({ move, rotate, scale, pivot })) pivot = pivotFor();
965
+ return { move, rotate, scale, pivot };
966
+ }
967
+ function tintInput(v) {
968
+ if (v === null) return null;
969
+ if (!v || typeof v !== "object" || Array.isArray(v)) throw new Reject("INVALID_INPUT", 'tint is { "color": "#rrggbb", "amount": 0~1 } or null (no tint)');
970
+ onlyKeys(v, ["color", "amount"], "tint");
971
+ const o = v;
972
+ return { color: colorInput(o.color, "tint.color"), amount: numInput(o.amount, "tint.amount (how much tint)", { min: 0, max: 1 }) };
973
+ }
974
+ var leftKey = (r) => r ? r.id.startsWith("$") ? boundAfterOrder(pc(r).order) : keyOf(r) : void 0;
975
+ var rightKey = (r) => r ? r.id.startsWith("$") ? pc(r).order : keyOf(r) : void 0;
976
+ var inOrder = (s, except) => all(s, "piece").filter((r) => r.id !== except).sort(byKey);
977
+ var topOrder = (s, except) => {
978
+ const list = inOrder(s, except);
979
+ return orderBetween(leftKey(list[list.length - 1]), void 0);
980
+ };
981
+ function nextTo(s, anchor, above, except) {
982
+ const list = inOrder(s, except);
983
+ const at = list.findIndex((r) => r.id === anchor);
984
+ const [left, right] = above ? [list[at], list[at + 1]] : [list[at - 1], list[at]];
985
+ return orderBetween(leftKey(left), rightKey(right));
986
+ }
987
+ var imageOf = (s, id) => s.records[id]?.type === "image" ? s.records[id].content : void 0;
988
+ function newPiece(name, image, order, extra = {}) {
989
+ return { name, image, order, hidden: false, place: { move: [0, 0], rotate: 0, scale: [1, 1], pivot: null }, clip: [], holes: [], adjust: { ...NO_ADJUST }, from: null, ...extra };
990
+ }
991
+ var label = (s, id) => {
992
+ const r = s.records[id];
993
+ const name = r ? r.content.name : "";
994
+ return name ? `${id}("${name}")` : id;
995
+ };
996
+ function overPieces(m, box) {
997
+ return visibleOver(m, box);
998
+ }
999
+ function nodeOf(m, id) {
1000
+ return m.byId.get(id);
1001
+ }
1002
+ function mustOverlap(n, box, op) {
1003
+ if (!n.box || !overlaps(n.box, box)) {
1004
+ throw new Reject("INVALID_INPUT", `${op}: the area (${boxText(box)}) does not overlap the area piece ${n.id} covers (${n.box ? boxText(n.box) : "none"}). Check the covered area of the piece with read_concept and give the area again`);
1005
+ }
1006
+ }
1007
+ var OPERATIONS = {
1008
+ "canvas.start": (s, input, id, ctx) => {
1009
+ onlyKeys(input, ["image", "sample", "width", "height", "reason"], "canvas.start");
1010
+ const existing = canvasRecord(s);
1011
+ if (existing) {
1012
+ const c = existing.content;
1013
+ throw new Reject("INVALID_STATE", `There is only one canvas. ${existing.id} already exists at ${c.width}\xD7${c.height}. The person adds other image files as pieces on the screen`);
1014
+ }
1015
+ const catalog = SAMPLES.map((x) => x.id).join(", ");
1016
+ const ways = [input.image !== void 0, input.sample !== void 0, input.width !== void 0 || input.height !== void 0].filter(Boolean).length;
1017
+ if (ways !== 1) throw new Reject("INVALID_INPUT", `Give only one of image (an image file), sample (built-in sample: ${catalog}), or width and height (an empty canvas)`);
1018
+ const reason = textInput(input.reason, "reason", ctx, MAX_REASON);
1019
+ const tail = reason ? `. Reason: ${reason}` : "";
1020
+ if (input.image === void 0 && input.sample === void 0) {
1021
+ const side = (v, what2) => {
1022
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > MAX_SIDE) throw new Reject("INVALID_INPUT", `For an empty canvas, give ${what2} as a whole number from 1 to ${MAX_SIDE}`);
1023
+ return v;
1024
+ };
1025
+ const width = side(input.width, "width");
1026
+ const height = side(input.height, "height");
1027
+ return {
1028
+ changes: [{ id: id(0), type: "canvas", prefix: "cv", after: { width, height, source: null, reason } }],
1029
+ summary: `Started canvas (${id(0)}): empty canvas ${width}\xD7${height}${tail}`
1030
+ };
1031
+ }
1032
+ let image;
1033
+ let source = null;
1034
+ let what;
1035
+ let first;
1036
+ if (input.sample !== void 0) {
1037
+ const sample = typeof input.sample === "string" ? sampleById(input.sample) : void 0;
1038
+ if (!sample) throw new Reject("TARGET_NOT_FOUND", `There is no built-in sample ${JSON.stringify(input.sample)}. Available samples: ${catalog}`);
1039
+ image = imageInput({ name: `${sample.id}.png`, data: sample.data }, ctx);
1040
+ source = { sample: sample.id, title: sample.title };
1041
+ what = `sample ${sample.id} (${sample.title})`;
1042
+ first = sample.title;
1043
+ } else {
1044
+ image = imageInput(input.image, ctx);
1045
+ what = `image file "${image.name}"`;
1046
+ first = baseName(image.name);
1047
+ }
1048
+ return {
1049
+ changes: [
1050
+ { id: id(0), type: "canvas", prefix: "cv", after: { width: image.width, height: image.height, source, reason } },
1051
+ { id: id(1), type: "image", prefix: "im", after: image },
1052
+ { id: id(2), type: "piece", prefix: "pc", after: newPiece(first, id(1), orderBetween(void 0, void 0)) }
1053
+ ],
1054
+ summary: `Started canvas (${id(0)}): ${what}, ${image.width}\xD7${image.height}, ${image.bytes} bytes. Made image file ${id(1)} and the first piece ${id(2)}, which shows the whole picture${tail}`
1055
+ };
1056
+ },
1057
+ "canvas.crop": (s, input) => {
1058
+ onlyKeys(input, ["where", "x", "y", "width", "height"], "canvas.crop");
1059
+ const cv = needCanvas(s);
1060
+ const plain = ["x", "y", "width", "height"].filter((k) => input[k] !== void 0);
1061
+ let box;
1062
+ let words;
1063
+ if (input.where !== void 0) {
1064
+ if (plain.length) throw new Reject("INVALID_INPUT", `Do not give where together with ${plain.join(", ")}. Give the area to crop in one way`);
1065
+ const w = whereInput(s, input.where);
1066
+ box = shapeBox(w.shape);
1067
+ words = whereWords(w);
1068
+ } else {
1069
+ if (plain.length !== 4) throw new Reject("INVALID_INPUT", `Give the area to crop with where, or with all four of x, y, width, height. ${WHERE_HELP}`);
1070
+ box = { x: numInput(input.x, "x"), y: numInput(input.y, "y"), w: numInput(input.width, "width", { positive: true }), h: numInput(input.height, "height", { positive: true }) };
1071
+ words = `rectangle ${boxText(box)}`;
1072
+ }
1073
+ const x0 = Math.floor(r3(box.x));
1074
+ const y0 = Math.floor(r3(box.y));
1075
+ const width = Math.ceil(r3(box.x + box.w)) - x0;
1076
+ const height = Math.ceil(r3(box.y + box.h)) - y0;
1077
+ if (width < 1 || height < 1 || width > MAX_SIDE || height > MAX_SIDE) throw new Reject("INVALID_INPUT", `The cropped canvas must be 1 to ${MAX_SIDE} pixels wide and high (${width}\xD7${height})`);
1078
+ const shift = (x, y) => [r3(x - x0), r3(y - y0)];
1079
+ const changes = [{ id: cv.r.id, type: "canvas", after: { ...cv.c, width, height } }];
1080
+ const pieces = all(s, "piece").sort(byKey);
1081
+ for (const r of pieces) {
1082
+ const c = pc(r);
1083
+ changes.push({ id: r.id, type: "piece", after: { ...c, place: { ...c.place, move: shift(c.place.move[0], c.place.move[1]) } } });
1084
+ }
1085
+ const regions = all(s, "region").sort(byIdNumber);
1086
+ for (const r of regions) {
1087
+ const c = r.content;
1088
+ const sh = c.shape;
1089
+ const moved = sh.kind === "ellipse" ? { ...sh, cx: shift(sh.cx, sh.cy)[0], cy: shift(sh.cx, sh.cy)[1] } : sh.kind === "polygon" ? { kind: "polygon", points: sh.points.map((p) => shift(p[0], p[1])) } : { ...sh, x: shift(sh.x, sh.y)[0], y: shift(sh.x, sh.y)[1] };
1090
+ changes.push({ id: r.id, type: "region", after: { ...c, shape: moved } });
1091
+ }
1092
+ return {
1093
+ changes,
1094
+ summary: `Cropped canvas (${cv.r.id}) from ${cv.c.width}\xD7${cv.c.height} to ${width}\xD7${height}. It was cut to the whole-pixel rectangle around ${words}. The new top left is (${x0}, ${y0}) on the old canvas. Shifted the positions of ${many(pieces.length, "piece")} and ${many(regions.length, "region")} by the same amount, so the picture looks the same except for the cropped part`
1095
+ };
1096
+ },
1097
+ "piece.add": (s, input, id, ctx) => {
1098
+ onlyKeys(input, ["image", "name", "move"], "piece.add");
1099
+ const cv = needCanvas(s);
1100
+ const image = imageInput(input.image, ctx);
1101
+ const name = input.name !== void 0 ? nameInput(input.name, "name", ctx, MAX_NAME) : baseName(image.name);
1102
+ const move = input.move !== void 0 ? vecInput(input.move, "move") : [Math.round((cv.c.width - image.width) / 2), Math.round((cv.c.height - image.height) / 2)];
1103
+ const piece = newPiece(name, id(1), topOrder(s), { place: { move, rotate: 0, scale: [1, 1], pivot: null } });
1104
+ return {
1105
+ changes: [
1106
+ { id: id(1), type: "image", prefix: "im", after: image },
1107
+ { id: id(0), type: "piece", prefix: "pc", after: piece }
1108
+ ],
1109
+ summary: `Added piece (${id(0)}${name ? ` "${name}"` : ""}): put image file "${image.name}" (${image.width}\xD7${image.height}, ${image.bytes} bytes) in as image file ${id(1)} and placed it on top. Move (${fmt(move[0])}, ${fmt(move[1])})`
1110
+ };
1111
+ },
1112
+ "piece.lift": (s, input, id, ctx) => {
1113
+ onlyKeys(input, ["where", "from", "cut", "name"], "piece.lift");
1114
+ needCanvas(s);
1115
+ const w = whereInput(s, input.where);
1116
+ const box = shapeBox(w.shape);
1117
+ const m = buildModel(s);
1118
+ let from;
1119
+ if (input.from !== void 0) {
1120
+ from = nodeOf(m, need(s, input.from, "piece", "from").id);
1121
+ mustOverlap(from, box, "piece.lift");
1122
+ } else {
1123
+ const over = overPieces(m, box);
1124
+ if (over.length === 0) throw new Reject("INVALID_INPUT", `No visible piece overlaps the area (${boxText(box)}). Check the areas the pieces cover with read_concept`);
1125
+ if (over.length > 1) throw new Reject("INVALID_INPUT", `Several visible pieces overlap the area (top to bottom: ${over.map((n) => label(s, n.id)).join(", ")}). Give the id of the piece to lift from in from`);
1126
+ from = over[0];
1127
+ }
1128
+ const cut = input.cut === void 0 ? true : boolInput(input.cut, "cut");
1129
+ const name = nameInput(input.name, "name", ctx, MAX_NAME);
1130
+ const fc = from.c;
1131
+ if (fc.clip.length >= MAX_CLIP) throw new Reject("INVALID_STATE", `Cannot lift from this piece any more. ${from.id} is already the result of ${MAX_CLIP} lifts (${many(fc.clip.length, "visible area")}). Lift from a larger piece`);
1132
+ if (cut && fc.holes.length >= MAX_HOLES) throw new Reject("INVALID_STATE", `${from.id} already has ${MAX_HOLES} erased areas, so nothing more can be cut out of it. Lift a copy with cut: false, or restore the erased areas with piece.unerase`);
1133
+ const placed = placeOn(w.shape, from.matrix);
1134
+ const inner = placedBox(placed);
1135
+ const holes = fc.holes.filter((h) => overlaps(placedBox(h), inner));
1136
+ const piece = { ...fc, name, order: nextTo(s, from.id, true), clip: [...fc.clip, placed], holes, from: from.id };
1137
+ const changes = [{ id: id(0), type: "piece", prefix: "pc", after: piece }];
1138
+ if (cut) changes.push({ id: from.id, type: "piece", after: { ...fc, holes: [...fc.holes, placed] } });
1139
+ return {
1140
+ changes,
1141
+ summary: `Lifted piece (${id(0)}${name ? ` "${name}"` : ""}): ${cut ? "cut out" : "copied"} ${whereWords(w)} from ${label(s, from.id)} (${cut ? `erased that area of ${from.id}` : `${from.id} is unchanged`}). The new piece sits right above ${from.id} with the same placement and color adjustment`
1142
+ };
1143
+ },
1144
+ "piece.erase": (s, input) => {
1145
+ onlyKeys(input, ["where", "piece"], "piece.erase");
1146
+ needCanvas(s);
1147
+ const w = whereInput(s, input.where);
1148
+ const box = shapeBox(w.shape);
1149
+ const m = buildModel(s);
1150
+ let targets;
1151
+ if (input.piece !== void 0) {
1152
+ const n = nodeOf(m, need(s, input.piece, "piece", "piece").id);
1153
+ mustOverlap(n, box, "piece.erase");
1154
+ targets = [n];
1155
+ } else {
1156
+ targets = overPieces(m, box);
1157
+ if (targets.length === 0) throw new Reject("INVALID_INPUT", `No visible piece overlaps the area (${boxText(box)}). Check the areas the pieces cover with read_concept`);
1158
+ }
1159
+ const full = targets.filter((n) => n.c.holes.length >= MAX_HOLES);
1160
+ if (full.length) throw new Reject("INVALID_STATE", `${full.map((n) => n.id).join(", ")}: the limit of ${MAX_HOLES} erased areas is reached, so nothing more can be erased. Restore the erased areas with piece.unerase, or lift the piece again`);
1161
+ return {
1162
+ changes: targets.map((n) => ({ id: n.id, type: "piece", after: { ...n.c, holes: [...n.c.holes, placeOn(w.shape, n.matrix)] } })),
1163
+ summary: `Erased: made ${whereWords(w)} transparent in ${targets.map((n) => label(s, n.id)).join(", ")}`
1164
+ };
1165
+ },
1166
+ "piece.unerase": (s, input) => {
1167
+ onlyKeys(input, ["piece"], "piece.unerase");
1168
+ const r = need(s, input.piece, "piece", "piece");
1169
+ const c = pc(r);
1170
+ return { changes: [{ id: r.id, type: "piece", after: { ...c, holes: [] } }], summary: `Restored ${many(c.holes.length, "erased area")} of ${label(s, r.id)}` };
1171
+ },
1172
+ "piece.place": (s, input) => {
1173
+ onlyKeys(input, ["piece", ...PLACE_KEYS], "piece.place");
1174
+ const r = need(s, input.piece, "piece", "piece");
1175
+ if (!PLACE_KEYS.some((k) => input[k] !== void 0)) throw new Reject("INVALID_INPUT", "Give at least one of move, rotate, scale, pivot");
1176
+ const c = pc(r);
1177
+ const place = placeInput(input, c.place, () => defaultPivot(c, imageOf(s, c.image)));
1178
+ const words = [];
1179
+ if (input.move !== void 0) words.push(`move (${fmt(place.move[0])}, ${fmt(place.move[1])})`);
1180
+ if (input.rotate !== void 0) words.push(`rotate ${fmt(place.rotate)}\xB0`);
1181
+ if (input.scale !== void 0) words.push(place.scale[0] === place.scale[1] ? `scale ${fmt(place.scale[0])}` : `scale horizontal ${fmt(place.scale[0])} vertical ${fmt(place.scale[1])}`);
1182
+ if (place.pivot && (input.pivot !== void 0 || c.place.pivot === null) && !isIdentityTurn(place)) words.push(`pivot (${fmt(place.pivot[0])}, ${fmt(place.pivot[1])})`);
1183
+ return { changes: [{ id: r.id, type: "piece", after: { ...c, place } }], summary: `${label(s, r.id)} placement: ${words.join(", ") || "nothing changed"}` };
1184
+ },
1185
+ "piece.adjust": (s, input) => {
1186
+ onlyKeys(input, ["piece", ...ADJUST_KEYS], "piece.adjust");
1187
+ const r = need(s, input.piece, "piece", "piece");
1188
+ if (!ADJUST_KEYS.some((k) => input[k] !== void 0)) throw new Reject("INVALID_INPUT", "Give at least one of hue, saturate, brightness, tint, opacity");
1189
+ const c = pc(r);
1190
+ const a = c.adjust;
1191
+ const adjust = {
1192
+ hue: input.hue !== void 0 ? numInput(input.hue, "hue (degrees)", { min: -180, max: 180 }) : a.hue,
1193
+ saturate: input.saturate !== void 0 ? numInput(input.saturate, "saturate (saturation)", { min: 0, max: 2 }) : a.saturate,
1194
+ brightness: input.brightness !== void 0 ? numInput(input.brightness, "brightness", { min: 0, max: 2 }) : a.brightness,
1195
+ tint: input.tint !== void 0 ? tintInput(input.tint) : a.tint,
1196
+ opacity: input.opacity !== void 0 ? numInput(input.opacity, "opacity", { min: 0, max: 1 }) : a.opacity
1197
+ };
1198
+ return { changes: [{ id: r.id, type: "piece", after: { ...c, adjust } }], summary: `${label(s, r.id)} color adjustment: ${adjustText(adjust)}` };
1199
+ },
1200
+ "piece.set": (s, input, _id, ctx) => {
1201
+ onlyKeys(input, ["piece", "name", "hidden"], "piece.set");
1202
+ const r = need(s, input.piece, "piece", "piece");
1203
+ if (input.name === void 0 && input.hidden === void 0) throw new Reject("INVALID_INPUT", "Give at least one of name or hidden");
1204
+ const c = pc(r);
1205
+ const name = input.name !== void 0 ? nameInput(input.name, "name", ctx, MAX_NAME) : c.name;
1206
+ const hidden = input.hidden !== void 0 ? boolInput(input.hidden, "hidden") : c.hidden;
1207
+ const words = [];
1208
+ if (name !== c.name) words.push(`name "${c.name}" to "${name}"`);
1209
+ if (hidden !== c.hidden) words.push(hidden ? "hidden" : "shown");
1210
+ return { changes: [{ id: r.id, type: "piece", after: { ...c, name, hidden } }], summary: `Changed piece ${r.id}: ${words.join(", ") || "nothing changed"}` };
1211
+ },
1212
+ "piece.order": (s, input) => {
1213
+ onlyKeys(input, ["piece", "above", "below", "to"], "piece.order");
1214
+ const r = need(s, input.piece, "piece", "piece");
1215
+ const given = ["above", "below", "to"].filter((k) => input[k] !== void 0);
1216
+ if (given.length !== 1) throw new Reject("INVALID_INPUT", 'Give only one of above (right above this piece), below (right below this piece), to ("top" for the top, "bottom" for the bottom)');
1217
+ let order;
1218
+ let words;
1219
+ if (given[0] === "to") {
1220
+ if (input.to !== "top" && input.to !== "bottom") throw new Reject("INVALID_INPUT", `to is "top" (the top) or "bottom" (the bottom). Received: ${JSON.stringify(input.to)}`);
1221
+ const list = inOrder(s, r.id);
1222
+ order = input.to === "top" ? orderBetween(leftKey(list[list.length - 1]), void 0) : orderBetween(void 0, rightKey(list[0]));
1223
+ words = input.to === "top" ? "to the top" : "to the bottom";
1224
+ } else {
1225
+ const a = need(s, input[given[0]], "piece", given[0]);
1226
+ if (a.id === r.id) throw new Reject("INVALID_INPUT", `Cannot move ${a.id} above or below itself`);
1227
+ order = nextTo(s, a.id, given[0] === "above", r.id);
1228
+ words = `right ${given[0] === "above" ? "above" : "below"} ${a.id}`;
1229
+ }
1230
+ return { changes: [{ id: r.id, type: "piece", after: { ...pc(r), order }, moved: true }], summary: `Changed the stacking order of ${label(s, r.id)}: ${words}` };
1231
+ },
1232
+ "piece.remove": (s, input) => {
1233
+ onlyKeys(input, ["piece"], "piece.remove");
1234
+ const r = need(s, input.piece, "piece", "piece");
1235
+ const image = pc(r).image;
1236
+ const used = all(s, "piece").some((x) => x.id !== r.id && pc(x).image === image);
1237
+ const changes = [{ id: r.id, type: "piece", after: null }];
1238
+ if (!used && s.records[image]?.type === "image") changes.push({ id: image, type: "image", after: null });
1239
+ return { changes, summary: `Removed piece (${label(s, r.id)})${changes.length > 1 ? `. Also removed image file ${image}, which no piece uses any more` : ""}` };
1240
+ },
1241
+ "region.add": (s, input, id, ctx) => {
1242
+ onlyKeys(input, ["where", "name", "note", "auto"], "region.add");
1243
+ needCanvas(s);
1244
+ const w = whereInput(s, input.where);
1245
+ const auto = input.auto === void 0 ? false : boolInput(input.auto, "auto");
1246
+ const name = nameInput(input.name, "name", ctx, MAX_NAME);
1247
+ if (name === "" && !auto) throw new Reject("INVALID_INPUT", "Give the region a name (name). The person and the AI refer to this area by that name");
1248
+ const note = textInput(input.note, "note", ctx, MAX_NOTE);
1249
+ const changes = [{ id: id(0), type: "region", prefix: "rg", after: { name, shape: w.shape, note, auto } }];
1250
+ let dropped = [];
1251
+ if (auto) {
1252
+ const autos = all(s, "region").filter((r) => r.content.auto).sort(byIdNumber);
1253
+ dropped = autos.slice(0, Math.max(0, autos.length + 1 - MAX_AUTO_REGIONS)).map((r) => r.id);
1254
+ for (const x of dropped) changes.push({ id: x, type: "region", after: null });
1255
+ }
1256
+ return {
1257
+ changes,
1258
+ summary: `Saved region (${id(0)}${name ? ` "${name}"` : ""}${auto ? ", automatic" : ""}): ${whereWords(w)}${dropped.length ? `. Removed old automatic ${dropped.length === 1 ? "region" : "regions"} ${dropped.join(", ")}` : ""}`
1259
+ };
1260
+ },
1261
+ "region.set": (s, input, _id, ctx) => {
1262
+ onlyKeys(input, ["region", "name", "note"], "region.set");
1263
+ const r = need(s, input.region, "region", "region");
1264
+ if (input.name === void 0 && input.note === void 0) throw new Reject("INVALID_INPUT", "Give at least one of name or note");
1265
+ const c = r.content;
1266
+ const name = input.name !== void 0 ? nameInput(input.name, "name", ctx, MAX_NAME) : c.name;
1267
+ if (name === "" && !c.auto) throw new Reject("INVALID_INPUT", "The name of a region cannot be empty");
1268
+ const note = input.note !== void 0 ? textInput(input.note, "note", ctx, MAX_NOTE) : c.note;
1269
+ const auto = c.auto && !(input.name !== void 0 && name !== "");
1270
+ const words = [];
1271
+ if (name !== c.name) words.push(`name "${c.name}" to "${name}"`);
1272
+ if (note !== c.note) words.push("note changed");
1273
+ if (auto !== c.auto) words.push("no longer an automatic region");
1274
+ return { changes: [{ id: r.id, type: "region", after: { ...c, name, note, auto } }], summary: `Changed region ${r.id}: ${words.join(", ") || "nothing changed"}` };
1275
+ },
1276
+ "region.remove": (s, input) => {
1277
+ onlyKeys(input, ["region"], "region.remove");
1278
+ const r = need(s, input.region, "region", "region");
1279
+ return { changes: [{ id: r.id, type: "region", after: null }], summary: `Removed region (${label(s, r.id)})` };
1280
+ }
1281
+ };
1282
+ function refsOf(r) {
1283
+ if (r.type !== "piece") return [];
1284
+ const c = pc(r);
1285
+ const out = [{ from: r.id, to: c.image, kind: "image" }];
1286
+ if (c.from) out.push({ from: r.id, to: c.from, kind: "from", soft: true });
1287
+ return out;
1288
+ }
1289
+ var num = (v, min, max) => typeof v === "number" && Number.isFinite(v) && v >= min && v <= max;
1290
+ function adjustProblem(a) {
1291
+ const x = a;
1292
+ if (!x || typeof x !== "object") return "The color adjustment (adjust) is missing";
1293
+ if (!num(x.hue, -180, 180) || !num(x.saturate, 0, 2) || !num(x.brightness, 0, 2) || !num(x.opacity, 0, 1)) return "A number in the color adjustment is wrong";
1294
+ if (x.tint !== null && !(x.tint && isColor(x.tint.color) && num(x.tint.amount, 0, 1))) return "The tint (tint) is null or { color: #rrggbb, amount: 0~1 }";
1295
+ return null;
1296
+ }
1297
+ function pieceProblem2(c) {
1298
+ const p = c;
1299
+ if (!p || typeof p !== "object") return "The piece has no content";
1300
+ if (typeof p.name !== "string" || p.name.length > MAX_NAME || typeof p.image !== "string" || typeof p.order !== "string" || p.order === "" || typeof p.hidden !== "boolean") return "The name, image file, order value or hidden value of the piece is wrong";
1301
+ if (!(p.from === null || typeof p.from === "string")) return "The from of the piece is wrong";
1302
+ const pp = placeProblem(p.place);
1303
+ if (pp) return pp;
1304
+ if (!Array.isArray(p.clip) || p.clip.length > MAX_CLIP) return `A piece can have up to ${MAX_CLIP} visible areas (clip)`;
1305
+ if (!Array.isArray(p.holes) || p.holes.length > MAX_HOLES) return `A piece can have up to ${MAX_HOLES} erased areas (holes)`;
1306
+ for (const s of [...p.clip, ...p.holes]) {
1307
+ const problem = shapeProblem(s) ?? matProblem(s?.m);
1308
+ if (problem) return problem;
1309
+ }
1310
+ return adjustProblem(p.adjust);
1311
+ }
1312
+ function imageProblem(c) {
1313
+ const x = c;
1314
+ if (!x || typeof x !== "object") return "The image file has no content";
1315
+ if (typeof x.name !== "string" || x.name === "" || x.name.length > MAX_FILE_NAME || x.mime !== "image/png") return "The name or type of the image file is wrong";
1316
+ if (!Number.isInteger(x.width) || !Number.isInteger(x.height) || x.width < 1 || x.height < 1 || x.width > MAX_SIDE || x.height > MAX_SIDE) return `The width and height of an image file are whole numbers from 1 to ${MAX_SIDE}`;
1317
+ if (typeof x.data !== "string" || x.data.length % 4 !== 0 || x.bytes !== bytesOf(x.data) || x.bytes > MAX_IMAGE_BYTES) return `The data or size of the image file is wrong (up to 4MB)`;
1318
+ return null;
1319
+ }
1320
+ function regionProblem(c) {
1321
+ const x = c;
1322
+ if (!x || typeof x !== "object") return "The region has no content";
1323
+ if (typeof x.name !== "string" || x.name.length > MAX_NAME || typeof x.note !== "string" || x.note.length > MAX_NOTE || typeof x.auto !== "boolean") return "The name, note or auto of the region is wrong";
1324
+ return shapeProblem(x.shape);
1325
+ }
1326
+ function masksOf(r) {
1327
+ const list = (v) => Array.isArray(v) ? v : [];
1328
+ const shapes = r.type === "piece" ? [...list(pc(r)?.clip), ...list(pc(r)?.holes)] : r.type === "region" ? [r.content?.shape] : [];
1329
+ return shapes.filter((x) => !!x && x.kind === "mask");
1330
+ }
1331
+ function validate(candidate, changed) {
1332
+ const out = [];
1333
+ const err = (record, code, message) => out.push({ level: "error", code, record, message });
1334
+ const changedSet = new Set(changed);
1335
+ const live = (list) => list.map((x) => x.id).find((x) => changedSet.has(x));
1336
+ const canvases = all(candidate, "canvas").sort(byIdNumber);
1337
+ if (canvases.length > 1) err(live(canvases.slice(1)) ?? canvases[1].id, "second_canvas", `There is only one canvas: ${canvases.map((x) => x.id).join(", ")}`);
1338
+ const images = all(candidate, "image");
1339
+ const pieces = all(candidate, "piece");
1340
+ const regions = all(candidate, "region");
1341
+ const rest = [...images, ...pieces, ...regions];
1342
+ if (!canvases.length && rest.length && live(rest)) err(live(rest), "no_canvas", "There are image files, pieces or regions but no canvas (canvas). Start with canvas.start first");
1343
+ const limit = (list, max, code, message) => {
1344
+ if (list.length > max && live(list)) err(live(list), code, message);
1345
+ };
1346
+ limit(images, MAX_IMAGES, "too_many_images", `Up to ${MAX_IMAGES} image files are allowed (there are ${images.length}). Removing unused pieces also removes their image files`);
1347
+ limit(pieces, MAX_PIECES, "too_many_pieces", `Up to ${MAX_PIECES} pieces are allowed (there are ${pieces.length}). Remove unused pieces`);
1348
+ limit(regions, MAX_REGIONS, "too_many_regions", `Up to ${MAX_REGIONS} regions are allowed (there are ${regions.length}). Remove unused regions`);
1349
+ let total = 0;
1350
+ const dataOf = /* @__PURE__ */ new Map();
1351
+ for (const r of images) total += typeof r.content?.data === "string" ? r.content.data.length : 0;
1352
+ for (const r of [...pieces, ...regions]) {
1353
+ for (const k of masksOf(r)) {
1354
+ if (typeof k.data !== "string") continue;
1355
+ total += k.data.length;
1356
+ const seen = dataOf.get(k.key);
1357
+ if (seen === void 0) dataOf.set(k.key, k.data);
1358
+ else if (seen !== k.data && changedSet.has(r.id)) err(r.id, "mask_key_clash", `The selection shape name ${k.key} clashes with a different shape. Change the selection slightly and send it again`);
1359
+ }
1360
+ }
1361
+ const heavy = rest.filter((r) => changedSet.has(r.id) && (r.type === "image" || masksOf(r).length > 0));
1362
+ if (total > MAX_DATA_CHARS && heavy.length) err(heavy[0].id, "too_much_data", `The data of image files and selection shapes totals ${total} characters, over the limit of ${MAX_DATA_CHARS}. Remove unused pieces, image files and automatic regions`);
1363
+ for (const id of changed) {
1364
+ const r = candidate.records[id];
1365
+ if (!r) continue;
1366
+ if (r.type === "canvas") {
1367
+ const c = r.content;
1368
+ if (!Number.isInteger(c.width) || !Number.isInteger(c.height) || c.width < 1 || c.height < 1 || c.width > MAX_SIDE || c.height > MAX_SIDE) err(id, "bad_canvas", `The canvas width and height are whole numbers from 1 to ${MAX_SIDE}`);
1369
+ } else if (r.type === "image") {
1370
+ const problem = imageProblem(r.content);
1371
+ if (problem) err(id, "bad_image", `${id}: ${problem}`);
1372
+ } else if (r.type === "piece") {
1373
+ const problem = pieceProblem2(r.content);
1374
+ if (problem) err(id, "bad_piece", `${id}: ${problem}`);
1375
+ else if (candidate.records[pc(r).image]?.type !== "image") err(id, "dangling_image", `Image file ${pc(r).image}, which ${id} draws, does not exist`);
1376
+ } else if (r.type === "region") {
1377
+ const problem = regionProblem(r.content);
1378
+ if (problem) err(id, "bad_region", `${id}: ${problem}`);
1379
+ }
1380
+ }
1381
+ const gone = new Set(changed.filter((x) => !candidate.records[x]));
1382
+ if (gone.size) {
1383
+ for (const r of pieces) if (!changedSet.has(r.id) && gone.has(pc(r).image)) err(r.id, "dangling_image", `Image file ${pc(r).image}, which ${r.id} draws, was removed`);
1384
+ }
1385
+ return out;
1386
+ }
1387
+ var noCanvasText = () => [
1388
+ "There is no picture yet. Only the person adds image files, on the screen. You can start a sample or an empty canvas with canvas.start.",
1389
+ "If this response lists changes by another participant that are not yet in the shared history, the person has already added a picture on the screen. In that case do not start a new one. Merge those changes with a request that has no operations, then read again.",
1390
+ "If there are no such changes, ask the person to add an image file, or, if the person wants, start with one of these.",
1391
+ ...SAMPLES.map((x) => `- sample ${x.id} (${x.title}): ${x.about}`),
1392
+ `- empty canvas: give width and height (whole numbers from 1 to ${MAX_SIDE}).`
1393
+ ].join("\n");
1394
+ function bare(s) {
1395
+ if (s.kind !== "mask") return s;
1396
+ const { data: _data, ...rest } = s;
1397
+ return rest;
1398
+ }
1399
+ function screenData(m) {
1400
+ return {
1401
+ version: VERSION,
1402
+ canvas: m.canvas ? { id: m.canvas.id, width: m.canvas.c.width, height: m.canvas.c.height, source: m.canvas.c.source } : null,
1403
+ images: m.images.map((x) => ({ id: x.id, name: x.c.name, width: x.c.width, height: x.c.height, bytes: x.c.bytes })),
1404
+ pieces: m.pieces.map((n) => ({
1405
+ id: n.id,
1406
+ name: n.c.name,
1407
+ image: n.c.image,
1408
+ hidden: n.c.hidden,
1409
+ place: n.c.place,
1410
+ matrix: roundMat(n.matrix),
1411
+ clip: n.c.clip.map(bare),
1412
+ holes: n.c.holes.map(bare),
1413
+ adjust: n.c.adjust,
1414
+ from: n.c.from,
1415
+ inner: n.inner ? roundRect(n.inner) : null,
1416
+ box: n.box ? roundRect(n.box) : null
1417
+ })),
1418
+ regions: m.regions.map((r) => ({ id: r.id, name: r.c.name, note: r.c.note, auto: r.c.auto, shape: bare(r.c.shape), box: roundRect(r.box) })),
1419
+ samples: SAMPLES.map((x) => ({ id: x.id, title: x.title })),
1420
+ limits: { imageBytes: MAX_IMAGE_BYTES, side: MAX_SIDE, maskChars: MAX_MASK_CHARS, pieces: MAX_PIECES, regions: MAX_REGIONS, clip: MAX_CLIP, holes: MAX_HOLES, points: MAX_POINTS }
1421
+ };
1422
+ }
1423
+ function dataIndex(s) {
1424
+ const out = /* @__PURE__ */ new Map();
1425
+ for (const r of all(s, "image")) out.set(r.id, r.content.data);
1426
+ for (const r of [...all(s, "piece"), ...all(s, "region")]) for (const k of masksOf(r)) if (!out.has(k.key)) out.set(k.key, k.data);
1427
+ return out;
1428
+ }
1429
+ function dataRead(s, ids) {
1430
+ const bad = ids.filter((x) => typeof x !== "string" || !x.startsWith(DATA_SCOPE));
1431
+ if (bad.length) throw new Reject("INVALID_INPUT", `A data: scope cannot be read together with other scopes (${bad.join(", ")})`);
1432
+ const index = dataIndex(s);
1433
+ const names = ids.map((x) => x.slice(DATA_SCOPE.length));
1434
+ const missing = names.filter((x) => !index.has(x));
1435
+ if (missing.length) throw new Reject("TARGET_NOT_FOUND", `There is no picture data for ${missing.join(", ")}. A name is an image file id or a selection shape name (starting with mk)`);
1436
+ const data = {};
1437
+ for (const x of names) data[x] = index.get(x);
1438
+ return {
1439
+ text: `Gave the screen the picture data of ${many(names.length, "item")} (${names.join(", ")}). This scope is for the screen. The AI sees the picture with read_image.`,
1440
+ json: { data },
1441
+ scopeLabel: `Read ${ids.join(", ")}`,
1442
+ records: []
1443
+ };
1444
+ }
1445
+ function project(s, scope, mine) {
1446
+ const ids = scope?.targets ?? (scope?.target !== void 0 ? [scope.target] : null);
1447
+ if (ids && ids.some((x) => typeof x === "string" && x.startsWith(DATA_SCOPE))) return dataRead(s, ids);
1448
+ const starred = new Set(mine.flatMap((p) => p.changes.filter((c) => c.after !== null).map((c) => c.record)));
1449
+ const m = buildModel(s);
1450
+ const read = readScope(m, ids, (id) => starred.has(id) ? " *" : "");
1451
+ return {
1452
+ text: m.canvas ? read.text : noCanvasText(),
1453
+ scopeLabel: read.scopeLabel,
1454
+ json: screenData(m),
1455
+ ...ids && ids.length ? { records: read.records } : {}
1456
+ };
1457
+ }
1458
+ var HOW_WORD = { rect: "with a rectangle", ellipse: "with an ellipse", lasso: "with a freehand outline", wand: "by similar colors", mixed: "by adding and subtracting with several tools" };
1459
+ var finiteNum = (v) => typeof v === "number" && Number.isFinite(v);
1460
+ var idList = (v, max = 2e3) => v === void 0 || Array.isArray(v) && v.length <= max && v.every((x) => typeof x === "string");
1461
+ function selectionProblem(v) {
1462
+ const x = v;
1463
+ if (typeof x !== "object" || x === null || x.format !== SELECTION_FORMAT) return `The selection format is not ${SELECTION_FORMAT}`;
1464
+ if (x.rev !== void 0 && typeof x.rev !== "string") return "rev of a selection must be text";
1465
+ if (x.kind === "pieces") {
1466
+ if (!Array.isArray(x.pieces) || x.pieces.length === 0 || !idList(x.pieces) || x.pieces.some((id) => id === "")) return "A pieces selection needs pieces (a list of piece ids)";
1467
+ return idList(x.labels) ? null : "labels of a pieces selection must be a list of text";
1468
+ }
1469
+ if (x.kind === "area") {
1470
+ const b = x.box;
1471
+ if (!Array.isArray(b) || b.length !== 4 || !b.every(finiteNum) || b[2] < 0 || b[3] < 0) return "An area selection needs box [x, y, w, h]";
1472
+ if (x.region !== void 0 && x.region !== null && typeof x.region !== "string") return "region of an area selection is a region id or null";
1473
+ if (x.pixels !== void 0 && !finiteNum(x.pixels)) return "pixels of an area selection must be a number";
1474
+ if (x.colors !== void 0 && !(Array.isArray(x.colors) && x.colors.length <= 20 && x.colors.every((c) => c && typeof c === "object" && typeof c.color === "string" && finiteNum(c.share)))) return "colors of an area selection is a list of { color, share }";
1475
+ if (!idList(x.under)) return "under of an area selection is a list of piece ids";
1476
+ if (x.how !== void 0 && !(typeof x.how === "string" && x.how in HOW_WORD)) return `how of an area selection is one of ${Object.keys(HOW_WORD).join(", ")}`;
1477
+ return null;
1478
+ }
1479
+ if (x.kind === "point") {
1480
+ if (!finiteNum(x.x) || !finiteNum(x.y)) return "A point selection needs x, y";
1481
+ if (x.piece !== void 0 && x.piece !== null && typeof x.piece !== "string") return "piece of a point selection is a piece id or null";
1482
+ return null;
1483
+ }
1484
+ return "kind of a selection is one of pieces, area, point";
1485
+ }
1486
+ var MAX_SELECTION_LINES = 60;
1487
+ var percent = (v) => `${fmt(r3(v * 100))}%`;
1488
+ function describeSelection(s, input) {
1489
+ const problem = selectionProblem(input?.selection);
1490
+ if (problem) return { error: "INVALID_INPUT", summary: problem };
1491
+ const sel = input.selection;
1492
+ const m = buildModel(s);
1493
+ if (!m.canvas) return { error: "INVALID_STATE", summary: "There is no canvas, so the selection cannot be described" };
1494
+ const cv = m.canvas.c;
1495
+ const targets = [];
1496
+ const gone = [];
1497
+ const add = (id) => {
1498
+ if (!targets.includes(id)) targets.push(id);
1499
+ };
1500
+ const lost = (id) => {
1501
+ if (!gone.includes(id)) gone.push(id);
1502
+ };
1503
+ const lines = [];
1504
+ const now = sel.rev && typeof input.current === "string" && input.current !== sel.rev ? ` Things have changed since then (now ${input.current}). The values of pieces and regions are the current ones.` : "";
1505
+ lines.push(`${sel.rev ? `Selected at ${sel.rev}.${now} ` : ""}Positions are canvas pixels (canvas ${cv.width}\xD7${cv.height}).`);
1506
+ if (sel.kind === "pieces") {
1507
+ const ids = [...new Set(sel.pieces)];
1508
+ lines.push(`The person clicked ${many(ids.length, "piece")} (in the order selected):`);
1509
+ ids.forEach((id, i) => {
1510
+ const n = m.byId.get(id);
1511
+ if (n) {
1512
+ add(id);
1513
+ if (i < MAX_SELECTION_LINES) lines.push(`- ${pieceLine(n)}`);
1514
+ } else {
1515
+ lost(id);
1516
+ if (i < MAX_SELECTION_LINES) lines.push(`- (${id}) ${sel.labels?.[sel.pieces.indexOf(id)] ? `"${sel.labels[sel.pieces.indexOf(id)]}"` : "name unknown"} (now removed)`);
1517
+ }
1518
+ });
1519
+ if (ids.length > MAX_SELECTION_LINES) lines.push(`- and ${ids.length - MAX_SELECTION_LINES} more. Read them by piece id`);
1520
+ lines.push(targets.length ? `When the person says "this" or "these", send operations only to ${targets.length === 1 ? "this piece" : `these ${targets.length} pieces`} (give the id in piece).` : "None of the pieces selected exist now.");
1521
+ return { text: lines.join("\n"), targets, gone };
1522
+ }
1523
+ if (sel.kind === "point") {
1524
+ lines.push(`Selected point: (${fmt(sel.x)}, ${fmt(sel.y)}). Color there: ${sel.color ?? "transparent (no visible pixel)"}. Deepest section containing the point: ${deepestPieceAt(m.grid, sel.x, sel.y) ?? "none (outside the canvas)"}`);
1525
+ if (sel.piece) {
1526
+ const n = m.byId.get(sel.piece);
1527
+ if (n) {
1528
+ add(n.id);
1529
+ lines.push(`Top visible piece there: ${pieceLine(n)}`);
1530
+ } else {
1531
+ lost(sel.piece);
1532
+ lines.push(`The top piece that was visible there, ${sel.piece}, has been removed.`);
1533
+ }
1534
+ } else lines.push("No piece is visible there (empty area).");
1535
+ const inside = m.regions.filter((r) => sel.x >= r.box.x && sel.x <= r.box.x + r.box.w && sel.y >= r.box.y && sel.y <= r.box.y + r.box.h);
1536
+ if (inside.length) lines.push(`Regions containing the point (by bounding rectangle): ${inside.map(regionLabel).join(", ")}`);
1537
+ return { text: lines.join("\n"), targets, gone };
1538
+ }
1539
+ const [bx, by, bw, bh] = sel.box;
1540
+ const box = { x: bx, y: by, w: bw, h: bh };
1541
+ const how = sel.how ? HOW_WORD[sel.how] : null;
1542
+ const pixels = sel.pixels !== void 0 ? `, ${many(Math.round(sel.pixels), "selected pixel")}` : "";
1543
+ lines.push(`Selected area${how ? ` (selected ${how})` : ""}: bounding rectangle ${boxText(box)}, ${percent(bw * bh / (cv.width * cv.height))} of the canvas${pixels}.`);
1544
+ if (sel.how === "wand" && sel.wand && typeof sel.wand === "object") {
1545
+ const wd = sel.wand;
1546
+ lines.push(`Similar colors: clicked at (${fmt(Number(wd.x))}, ${fmt(Number(wd.y))}), tolerance ${fmt(Number(wd.tolerance))}, ${wd.contiguous ? "connected area only" : "across the whole picture"}.`);
1547
+ }
1548
+ if (sel.colors?.length) lines.push(`Main colors (most first): ${sel.colors.slice(0, 5).map((c) => `${c.color} ${percent(c.share)}`).join(", ")}`);
1549
+ const under = [...new Set(sel.under ?? [])];
1550
+ if (under.length) {
1551
+ const words = under.map((id) => {
1552
+ const n = m.byId.get(id);
1553
+ if (n) {
1554
+ add(id);
1555
+ return pieceLabel(n);
1556
+ }
1557
+ lost(id);
1558
+ return `(${id}) (now removed)`;
1559
+ });
1560
+ lines.push(`Pieces actually visible in the selected area (checked by pixels on the screen, top to bottom): ${words.join(", ")}`);
1561
+ } else {
1562
+ const over = visibleOver(m, box);
1563
+ lines.push(over.length ? `Visible pieces overlapping it (by estimated covered area, top to bottom): ${over.map(pieceLabel).join(", ")}` : "No visible piece overlaps it (empty area).");
1564
+ for (const n of over) add(n.id);
1565
+ }
1566
+ const named = m.regions.filter((r) => r.id !== sel.region && r.c.name && overlaps(r.box, box));
1567
+ if (named.length) lines.push(`Named regions overlapping it: ${named.map(regionLabel).join(", ")}`);
1568
+ const quad = quadOfBox(m, box);
1569
+ lines.push(quad ? `Smallest section that holds all of this area: ${quad}` : "This area goes outside the canvas, so no section holds all of it.");
1570
+ const rect = `{ "rect": [${[bx, by, bw, bh].map((v) => fmt(v)).join(", ")}] }`;
1571
+ if (sel.region) {
1572
+ if (m.regions.some((r) => r.id === sel.region)) {
1573
+ targets.unshift(sel.region);
1574
+ lines.push(`This shape is saved in region ${sel.region}. Give "${sel.region}" as where to lift (piece.lift) or erase (piece.erase) exactly this shape.`);
1575
+ } else {
1576
+ lost(sel.region);
1577
+ lines.push(`Region ${sel.region}, which saved this shape, has been removed. To edit exactly this shape, ask the person to select it and send it again. You can also edit an estimate using the bounding rectangle (where: ${rect}).`);
1578
+ }
1579
+ } else if (sel.where !== void 0 && sel.where !== null && !sel.unsaved) {
1580
+ lines.push(`Write ${JSON.stringify(sel.where)} as where, as it is, to lift or erase this area.`);
1581
+ } else {
1582
+ lines.push(`This shape is not saved yet. To edit exactly this shape, the person has to send the selection to you from the screen. You can also edit an estimate using the bounding rectangle (where: ${rect}).`);
1583
+ }
1584
+ if (targets.length > 1) lines.push("If several pieces overlap, give the id of the piece to lift from in the from field of piece.lift.");
1585
+ return { text: lines.join("\n"), targets, gone };
1586
+ }
1587
+ function sceneOf(m) {
1588
+ return {
1589
+ width: m.canvas.c.width,
1590
+ height: m.canvas.c.height,
1591
+ images: m.images.map((x) => ({ id: x.id, width: x.c.width, height: x.c.height })),
1592
+ pieces: m.pieces.map((n) => ({ id: n.id, image: n.c.image, hidden: n.c.hidden, matrix: roundMat(n.matrix), clip: n.c.clip, holes: n.c.holes, adjust: n.c.adjust }))
1593
+ };
1594
+ }
1595
+ function renderOutput(s, req) {
1596
+ if ((req?.format ?? "svg") !== "svg") return { error: "UNSUPPORTED_CAPABILITY", summary: `The only output of ${TITLE} is svg (it does not make ${String(req?.format)}). The core draws this svg to make the PNG file` };
1597
+ const m = buildModel(s);
1598
+ if (!m.canvas) return { error: "INVALID_STATE", summary: "There is no canvas. Start with canvas.start first" };
1599
+ const index = dataIndex(s);
1600
+ const first = m.images[0];
1601
+ const name = first && baseName(first.c.name) || "picture";
1602
+ const basis = { canvas: m.canvas.id, revision: req?.revision ?? null, pieces: m.pieces.length, shown: m.pieces.filter((n) => !n.c.hidden).length };
1603
+ const dataOf = (key) => index.get(key) ?? "";
1604
+ if (req?.view !== void 0 && req.view !== null) {
1605
+ return run(() => {
1606
+ const part = viewSvg(m, sceneOf(m), dataOf, req.view);
1607
+ return { ok: true, mediaType: OUTPUT_MEDIA_TYPE, fileName: `${name}-part.svg`, content: part.svg, basis: { ...basis, view: part.label, rect: part.rect } };
1608
+ });
1609
+ }
1610
+ return { ok: true, mediaType: OUTPUT_MEDIA_TYPE, fileName: `${name}.svg`, content: pdSvg(sceneOf(m), dataOf), basis };
1611
+ }
1612
+ var AI_GUIDE = [
1613
+ "On this screen you and the person edit one PNG picture together. There is one canvas (cv and a number) with image files (im and a number), and pieces (pc and a number) that each show an image file are drawn stacked from bottom to top. The original pixels never change. Each piece only records its visible areas, erased areas, placement and color adjustment. An area saved with a name is a region (rg and a number).",
1614
+ "You cannot read pixels as text. Look at the picture with read_image before you edit, and look at the result with read_image again after you edit. Use read_concept to read the canvas size, the ids of pieces and regions, and the area each piece covers (an estimate that includes transparent pixels).",
1615
+ 'Give view to read_image to see one part larger. See the overall shape without view (section q), and go down to lower sections for detail, as in { "piece": "q.2.3" }. A section always comes as one picture of the same size, so even a large picture shows detail once you go down enough levels. When editing, get the overall shape from an upper section, check details in a lower section, and after editing look again from an upper section. See one piece with { "piece": "pc2", "alone": true }, and an area the person selected with { "region": "rg1", "mark": true }.',
1616
+ "Only the person adds image files (choosing a file, dragging and dropping, or pasting). If there is no picture, ask the person to add one, and if the person wants, start the built-in sample or an empty canvas with canvas.start.",
1617
+ 'Read what the person selected on the screen with read_selection. When the person says "this" or "the selected area", call read_selection first. When the person sends an area selected by pixels, it arrives saved as an automatic region, so give that region id as where to lift or erase exactly that shape. A selected area that was not sent can be estimated with its bounding rectangle, but if it must be exact, ask the person to send it to you from the screen.',
1618
+ "To move, rotate or recolor one object on its own, first lift it into a piece with piece.lift. For areas that must be selected precisely by color (fur, hair, objects with complex edges), ask the person to select them by similar colors on the screen and send them to you. The areas you give are estimates made with rectangles, ellipses and polygons, so check with read_image after lifting.",
1619
+ "To change the color of only one area, lift a copy of that area with cut: false and send piece.adjust to the new piece. If you cut it out (cut: true), a gap may show at the edges. The empty area left by lifting stays transparent and cannot be painted in.",
1620
+ 'Give areas (where) in canvas positions: a region id ("rg3"), { "rect": [x, y, w, h] }, { "ellipse": [cx, cy, rx, ry] }, { "polygon": [[x, y], ...] }. Even if a piece is moved or rotated, give the position where it is seen on the canvas now. { "mask": ... } is only for the screen, to send a shape selected by pixels. x grows to the right and y grows downward, and rotation is in degrees clockwise.',
1621
+ "The values of piece.place and piece.adjust are set as given, not added. If you do not give a pivot (pivot), the first rotation or scaling sets it to the center of the area the piece covers.",
1622
+ "Give a piece id or region id as the scope of read_concept to read it in detail, including its shape. Give a section id (q, q.2.3) to read only the pieces and regions that overlap that section. Sections are rectangles made by splitting the canvas into four, again and again (q.1 top left, q.2 top right, q.3 bottom left, q.4 bottom right). The scope data:<name> is for the screen to receive picture data, so do not use it."
1623
+ ].join(" ");
1624
+ var WHERE_INPUT = 'The area. One of a region id ("rg3"), { "rect": [x, y, w, h] }, { "ellipse": [cx, cy, rx, ry] }, { "polygon": [[x, y], ...] }. In canvas positions';
1625
+ var DESCRIPTION = {
1626
+ id: PACKAGE_ID,
1627
+ version: VERSION,
1628
+ title: TITLE,
1629
+ aiGuide: AI_GUIDE,
1630
+ views: VIEWS,
1631
+ markGuide: `Names and notes are plain text in the person's language. Do not put marks inside the text. For pieces and regions made earlier in the same request, give a $name with "as" and point to it from the input of other operations (piece, from, where, above, below, region).`,
1632
+ operations: [
1633
+ {
1634
+ op: "canvas.start",
1635
+ input: {
1636
+ sample: `Built-in sample id (${SAMPLES.map((x) => x.id).join(", ")})`,
1637
+ width: `Width of an empty canvas (whole number 1~${MAX_SIDE}). Give it together with height`,
1638
+ height: `Height of an empty canvas (whole number 1~${MAX_SIDE})`,
1639
+ image: "{ name, data }. A PNG file the person added on the screen. The AI does not use this",
1640
+ reason: "Why you start with this picture. Can be left out"
1641
+ },
1642
+ summary: "Creates the canvas. Do this only once. Give one of sample, image, or width and height. Starting from an image file makes a canvas of that size and a first piece that shows the whole picture",
1643
+ example: [{ op: "canvas.start", input: { sample: "apple", reason: "to try lifting and color adjustment" } }]
1644
+ },
1645
+ {
1646
+ op: "canvas.crop",
1647
+ input: { where: `${WHERE_INPUT}. Crops to the whole-pixel rectangle around that area`, "x, y, width, height": "Give the rectangle to crop as numbers, instead of where" },
1648
+ summary: "Crops the canvas. The positions of pieces and regions shift by the same amount, so the picture looks the same except for the cropped part. The canvas can also be made larger than before",
1649
+ example: [{ op: "canvas.crop", input: { where: { rect: [6, 4, 52, 56] } } }]
1650
+ },
1651
+ {
1652
+ op: "piece.add",
1653
+ input: { image: "{ name, data }. A PNG file the person added on the screen. The AI does not use this", name: "Piece name. If left out, the file name", move: "Where to put it [x, y] (top left of the image file). If left out, the center of the canvas" },
1654
+ summary: "Adds another image file as a new piece on top. The person's screen sends this"
1655
+ },
1656
+ {
1657
+ op: "piece.lift",
1658
+ input: {
1659
+ where: WHERE_INPUT,
1660
+ from: "Id of the piece to lift from. If left out, used only when exactly one visible piece overlaps the area",
1661
+ cut: "If true (the default), erases that area from the original piece (cut out). If false, leaves the original piece as it is (copy)",
1662
+ name: "Name of the new piece. Can be left out"
1663
+ },
1664
+ summary: "Lifts the area out of a piece into a new piece. The new piece sits right above the original piece with the same image file, placement and color adjustment",
1665
+ example: [
1666
+ { op: "piece.lift", as: "$leaf", input: { where: { ellipse: [41, 15, 11, 7] }, name: "leaf" } },
1667
+ { op: "piece.place", input: { piece: "$leaf", rotate: -20 } }
1668
+ ]
1669
+ },
1670
+ {
1671
+ op: "piece.erase",
1672
+ input: { where: WHERE_INPUT, piece: "Id of the piece to erase from. If left out, erases from every visible piece that overlaps the area" },
1673
+ summary: "Erases the area to transparent",
1674
+ example: [{ op: "piece.erase", input: { where: { rect: [28, 6, 8, 6] } } }]
1675
+ },
1676
+ { op: "piece.unerase", input: { piece: "Piece id" }, summary: "Restores all erased areas of the piece" },
1677
+ {
1678
+ op: "piece.place",
1679
+ input: { piece: "Piece id", move: "Move [x, y]", rotate: "Rotation (degrees, clockwise, -360~360)", scale: "Scale. One number or [horizontal, vertical]. A negative number flips", pivot: "Pivot [x, y] (a position inside the piece). If left out, the one already set, or the first time, the center of the area the piece covers. null sets it to the center again" },
1680
+ summary: "Sets the placement. Only the given fields change, and the values are set as given, not added",
1681
+ example: [{ op: "piece.place", input: { piece: "pc2", move: [6, -4], rotate: 15 } }]
1682
+ },
1683
+ {
1684
+ op: "piece.adjust",
1685
+ input: {
1686
+ piece: "Piece id",
1687
+ hue: "Degrees to turn the hue (-180~180, 0 keeps it)",
1688
+ saturate: "Saturation (0~2, 1 keeps it, 0 is gray)",
1689
+ brightness: "Brightness (0~2, 1 keeps it)",
1690
+ tint: 'Tints with one color, as { color: "#rrggbb", amount: 0~1 }. null removes the tint',
1691
+ opacity: "Opacity (0~1)"
1692
+ },
1693
+ summary: "Sets the color adjustment of the whole piece. Only the given fields change, and the values are set as given. To change only one area, lift it with cut: false and change that piece",
1694
+ example: [
1695
+ { op: "piece.lift", as: "$body", input: { where: { ellipse: [32, 39, 24, 18] }, cut: false, name: "body" } },
1696
+ { op: "piece.adjust", input: { piece: "$body", hue: 100 } }
1697
+ ]
1698
+ },
1699
+ { op: "piece.set", input: { piece: "Piece id", name: "New name", hidden: "true hides it and false shows it" }, summary: "Names or hides a piece", example: [{ op: "piece.set", input: { piece: "pc2", name: "leaf" } }] },
1700
+ {
1701
+ op: "piece.order",
1702
+ input: { piece: "Piece id", above: "Right above this piece", below: "Right below this piece", to: '"top" (the top) or "bottom" (the bottom)' },
1703
+ summary: "Changes the stacking order. Give one of above, below, to",
1704
+ example: [{ op: "piece.order", input: { piece: "pc2", to: "top" } }]
1705
+ },
1706
+ { op: "piece.remove", input: { piece: "Piece id" }, summary: "Removes the piece. If no other piece uses its image file, the image file is removed too" },
1707
+ {
1708
+ op: "region.add",
1709
+ input: { where: WHERE_INPUT, name: "Name. Required", note: "Note. Can be left out", auto: "true only when the screen saves a selected area to send it. Up to five automatic regions are kept" },
1710
+ summary: "Saves an area with a name. The picture does not change. In later conversations too, give the region id as where to point to the same area",
1711
+ example: [{ op: "region.add", input: { where: { rect: [26, 4, 26, 20] }, name: "stem and leaf" } }]
1712
+ },
1713
+ { op: "region.set", input: { region: "Region id", name: "New name. Giving one makes it no longer an automatic region", note: "Note" }, summary: "Changes the name or note of a region" },
1714
+ { op: "region.remove", input: { region: "Region id" }, summary: "Removes the region" }
1715
+ ]
1716
+ };
1717
+ var run = (f) => {
1718
+ try {
1719
+ return f();
1720
+ } catch (e) {
1721
+ if (e instanceof Reject) return { error: e.code, summary: e.message };
1722
+ throw e;
1723
+ }
1724
+ };
1725
+ var logic = {
1726
+ describe: () => DESCRIPTION,
1727
+ initialize: () => [],
1728
+ plan(state, op, ctx) {
1729
+ const handler = OPERATIONS[op.op];
1730
+ if (!handler) return { error: "INVALID_INPUT", summary: `Unknown operation ${op.op}. See the list of operations in describe_document` };
1731
+ const id = (k) => k === 0 && op.as ? op.as : `$~${ctx.stepIndex}.${k}`;
1732
+ return run(() => {
1733
+ const input = op.input ?? {};
1734
+ if (typeof input !== "object" || Array.isArray(input)) throw new Reject("INVALID_INPUT", "input must be an object");
1735
+ const out = handler(state, input, id, ctx);
1736
+ return { ...out, summary: /[.?!]$/.test(out.summary) ? out.summary : `${out.summary}.` };
1737
+ });
1738
+ },
1739
+ validate,
1740
+ project: (state, scope, mine) => run(() => project(state, scope, mine)),
1741
+ extractRefs: refsOf,
1742
+ prepareGeneration: () => ({ error: "UNSUPPORTED_CAPABILITY", summary: `${TITLE} does not make an output for the AI to rewrite. The picture becomes SVG through renderOutput, and the core saves it as PNG` }),
1743
+ interpretSelection: () => ({ candidates: [] }),
1744
+ resolveTarget(state, target) {
1745
+ const r = state.records[target.id];
1746
+ if (!r) return { found: false };
1747
+ const name = r.content.name;
1748
+ if (r.type === "piece") return { found: true, label: `piece ${r.id}${name ? ` "${name}"` : ""}` };
1749
+ if (r.type === "region") return { found: true, label: `region ${r.id}${name ? ` "${name}"` : ""}` };
1750
+ if (r.type === "image") return { found: true, label: `image file ${r.id}${name ? ` "${name}"` : ""}` };
1751
+ if (r.type === "canvas") return { found: true, label: `canvas ${r.id}` };
1752
+ return { found: true, label: r.id };
1753
+ },
1754
+ describeSelection,
1755
+ renderOutput
1756
+ };
1757
+ globalThis.__aicPlugin = logic;
1758
+ })();