dopesheet 0.0.0-stage → 0.1.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +78 -2
- package/bin/dopesheet.mjs +50 -0
- package/dist/browser/client.js +9 -0
- package/dist/browser/client.js.map +1 -0
- package/dist/browser/runtime.js +1 -0
- package/dist/browser/src-C-7lxf9e.js +2735 -0
- package/dist/browser/src-C-7lxf9e.js.map +1 -0
- package/dist/browser/src-D2ttZ_j7.js +7089 -0
- package/dist/browser/src-D2ttZ_j7.js.map +1 -0
- package/dist/browser/ui.js +1 -0
- package/dist/index.js +11 -0
- package/dist/loader.cjs +24 -0
- package/dist/next.js +81 -0
- package/dist/shared-CdhNdlQj.js +47 -0
- package/dist/shared-DpUIelWp.js +1454 -0
- package/dist/shared-E9l6ZbF6.js +102 -0
- package/dist/transform.js +2 -0
- package/dist/vite.js +16 -0
- package/docs/agents.md +38 -0
- package/package.json +90 -3
- package/types/next.d.ts +10 -0
- package/types/vite.d.ts +11 -0
- package/types/webpack.d.ts +14 -0
|
@@ -0,0 +1,1454 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, promises, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { parseSync } from "oxc-parser";
|
|
5
|
+
import MagicString from "magic-string";
|
|
6
|
+
/** Argument index of the position parameter, per method. */
|
|
7
|
+
var POSITION_INDEX = {
|
|
8
|
+
to: 2,
|
|
9
|
+
from: 2,
|
|
10
|
+
set: 2,
|
|
11
|
+
fromTo: 3,
|
|
12
|
+
add: 1,
|
|
13
|
+
addLabel: 1,
|
|
14
|
+
call: 2,
|
|
15
|
+
addPause: 0
|
|
16
|
+
};
|
|
17
|
+
var SAVE_ENDPOINT = "/__dopesheet/save";
|
|
18
|
+
var RELOCATE_ENDPOINT = "/__dopesheet/relocate";
|
|
19
|
+
var DOCK_PATH = "/__dopesheet/dock";
|
|
20
|
+
/** FNV-1a, 32-bit, as 8 hex chars. Identifies a file version; not a security hash. */
|
|
21
|
+
function hashText(text) {
|
|
22
|
+
let h = 0x811c9dc5;
|
|
23
|
+
for (let i = 0; i < text.length; i++) {
|
|
24
|
+
h ^= text.charCodeAt(i);
|
|
25
|
+
h = Math.imul(h, 16777619);
|
|
26
|
+
}
|
|
27
|
+
return (h >>> 0).toString(16).padStart(8, "0");
|
|
28
|
+
}
|
|
29
|
+
function parseSiteId(id) {
|
|
30
|
+
const i = id.lastIndexOf("#");
|
|
31
|
+
if (i < 0) return null;
|
|
32
|
+
const ordinal = Number(id.slice(i + 1));
|
|
33
|
+
if (!Number.isInteger(ordinal) || ordinal < 0) return null;
|
|
34
|
+
return {
|
|
35
|
+
file: id.slice(0, i),
|
|
36
|
+
ordinal
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
// ../codemod/src/index.ts
|
|
40
|
+
var TWEEN_METHODS = /* @__PURE__ */ new Set([
|
|
41
|
+
"to",
|
|
42
|
+
"from",
|
|
43
|
+
"fromTo",
|
|
44
|
+
"set"
|
|
45
|
+
]);
|
|
46
|
+
var OP_METHODS = /* @__PURE__ */ new Set([
|
|
47
|
+
"add",
|
|
48
|
+
"addLabel",
|
|
49
|
+
"call",
|
|
50
|
+
"addPause"
|
|
51
|
+
]);
|
|
52
|
+
/** Fewest arguments that make an op call meaningful (addPause() alone is valid). */
|
|
53
|
+
var OP_MIN_ARGS = {
|
|
54
|
+
add: 1,
|
|
55
|
+
addLabel: 1,
|
|
56
|
+
call: 1,
|
|
57
|
+
addPause: 0
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Timeline methods that are not effects. A call on a timeline with any other name and a config
|
|
61
|
+
* object, like `tl.fade(".box", { duration: 1 })`, is a registered effect that extends timelines.
|
|
62
|
+
*/
|
|
63
|
+
var TIMELINE_API = /* @__PURE__ */ new Set([
|
|
64
|
+
"add",
|
|
65
|
+
"addLabel",
|
|
66
|
+
"addPause",
|
|
67
|
+
"call",
|
|
68
|
+
"clear",
|
|
69
|
+
"currentLabel",
|
|
70
|
+
"delay",
|
|
71
|
+
"duration",
|
|
72
|
+
"endTime",
|
|
73
|
+
"eventCallback",
|
|
74
|
+
"from",
|
|
75
|
+
"fromTo",
|
|
76
|
+
"getById",
|
|
77
|
+
"getChildren",
|
|
78
|
+
"getTweensOf",
|
|
79
|
+
"invalidate",
|
|
80
|
+
"isActive",
|
|
81
|
+
"iteration",
|
|
82
|
+
"kill",
|
|
83
|
+
"killTweensOf",
|
|
84
|
+
"nextLabel",
|
|
85
|
+
"pause",
|
|
86
|
+
"paused",
|
|
87
|
+
"play",
|
|
88
|
+
"previousLabel",
|
|
89
|
+
"progress",
|
|
90
|
+
"recent",
|
|
91
|
+
"remove",
|
|
92
|
+
"removeLabel",
|
|
93
|
+
"removePause",
|
|
94
|
+
"repeat",
|
|
95
|
+
"repeatDelay",
|
|
96
|
+
"restart",
|
|
97
|
+
"resume",
|
|
98
|
+
"reverse",
|
|
99
|
+
"reversed",
|
|
100
|
+
"revert",
|
|
101
|
+
"seek",
|
|
102
|
+
"set",
|
|
103
|
+
"shiftChildren",
|
|
104
|
+
"startTime",
|
|
105
|
+
"then",
|
|
106
|
+
"time",
|
|
107
|
+
"timeScale",
|
|
108
|
+
"to",
|
|
109
|
+
"totalDuration",
|
|
110
|
+
"totalProgress",
|
|
111
|
+
"totalTime",
|
|
112
|
+
"tweenFromTo",
|
|
113
|
+
"tweenTo",
|
|
114
|
+
"yoyo",
|
|
115
|
+
"timeline",
|
|
116
|
+
"labels",
|
|
117
|
+
"vars"
|
|
118
|
+
]);
|
|
119
|
+
var ParseError = class extends Error {};
|
|
120
|
+
function parse(code, filename) {
|
|
121
|
+
const result = parseSync(filename, code);
|
|
122
|
+
if (result.errors.length) throw new ParseError(result.errors[0]?.message ?? "Parse error");
|
|
123
|
+
return result.program;
|
|
124
|
+
}
|
|
125
|
+
var EMPTY_SCOPE = {
|
|
126
|
+
consts: /* @__PURE__ */ new Map(),
|
|
127
|
+
imports: /* @__PURE__ */ new Map()
|
|
128
|
+
};
|
|
129
|
+
/** Walk with the parent node and the key the child sits under. */
|
|
130
|
+
function walkWithParent(node, parent, key, visit) {
|
|
131
|
+
if (Array.isArray(node)) {
|
|
132
|
+
for (const child of node) walkWithParent(child, parent, key, visit);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (!node || typeof node !== "object") return;
|
|
136
|
+
const n = node;
|
|
137
|
+
if (typeof n.type !== "string") return;
|
|
138
|
+
visit(n, parent, key);
|
|
139
|
+
for (const k in n) {
|
|
140
|
+
if (k === "parent") continue;
|
|
141
|
+
const value = n[k];
|
|
142
|
+
if (value && typeof value === "object") walkWithParent(value, n, k, visit);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Finds `const NAME = <literal | object literal>` declarations whose name is declared exactly once in
|
|
147
|
+
* the file (so references can't be shadowed), and counts the references to each.
|
|
148
|
+
*/
|
|
149
|
+
function analyzeScope(program, starts) {
|
|
150
|
+
const declared = /* @__PURE__ */ new Map();
|
|
151
|
+
const candidates = /* @__PURE__ */ new Map();
|
|
152
|
+
const imports = /* @__PURE__ */ new Map();
|
|
153
|
+
const refs = /* @__PURE__ */ new Map();
|
|
154
|
+
const declare = (name) => declared.set(name, (declared.get(name) ?? 0) + 1);
|
|
155
|
+
walkWithParent(program, null, "", (n, parent, key) => {
|
|
156
|
+
if (n.type === "VariableDeclaration") {
|
|
157
|
+
for (const d of n.declarations) {
|
|
158
|
+
if (d.id?.type !== "Identifier") continue;
|
|
159
|
+
if (n.kind === "const" && d.init) candidates.set(d.id.name, {
|
|
160
|
+
init: unwrap(d.init),
|
|
161
|
+
start: d.start
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (n.type === "ImportDeclaration") {
|
|
167
|
+
for (const sp of n.specifiers) imports.set(sp.local.name, String(n.source.value));
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (n.type !== "Identifier") return;
|
|
171
|
+
const p = parent;
|
|
172
|
+
if (p?.type === "VariableDeclarator" && key === "id") return declare(n.name);
|
|
173
|
+
if ((p?.type === "FunctionDeclaration" || p?.type === "FunctionExpression" || p?.type === "ClassDeclaration") && key === "id") return declare(n.name);
|
|
174
|
+
if ((p?.type === "FunctionDeclaration" || p?.type === "FunctionExpression" || p?.type === "ArrowFunctionExpression") && key === "params") return declare(n.name);
|
|
175
|
+
if (p?.type === "ImportSpecifier" || p?.type === "ImportDefaultSpecifier" || p?.type === "ImportNamespaceSpecifier") return declare(n.name);
|
|
176
|
+
if (p?.type === "MemberExpression" && key === "property" && !p.computed) return;
|
|
177
|
+
if ((p?.type === "Property" || p?.type === "MethodDefinition" || p?.type === "PropertyDefinition") && key === "key" && !p.computed) return;
|
|
178
|
+
if (p?.type === "LabeledStatement" || p?.type === "BreakStatement" || p?.type === "ContinueStatement") return;
|
|
179
|
+
refs.set(n.name, (refs.get(n.name) ?? 0) + 1);
|
|
180
|
+
});
|
|
181
|
+
const consts = /* @__PURE__ */ new Map();
|
|
182
|
+
for (const [name, c] of candidates) {
|
|
183
|
+
if (declared.get(name) !== 1) continue;
|
|
184
|
+
consts.set(name, {
|
|
185
|
+
name,
|
|
186
|
+
init: c.init,
|
|
187
|
+
line: position(starts, c.start).line,
|
|
188
|
+
uses: refs.get(name) ?? 0
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
return {
|
|
192
|
+
consts,
|
|
193
|
+
imports
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
function walk(node, visit) {
|
|
197
|
+
if (Array.isArray(node)) {
|
|
198
|
+
for (const child of node) walk(child, visit);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (!node || typeof node !== "object") return;
|
|
202
|
+
const n = node;
|
|
203
|
+
if (typeof n.type === "string") visit(n);
|
|
204
|
+
for (const key in n) {
|
|
205
|
+
if (key === "parent") continue;
|
|
206
|
+
const value = n[key];
|
|
207
|
+
if (value && typeof value === "object") walk(value, visit);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
function lineIndex(code) {
|
|
211
|
+
const starts = [0];
|
|
212
|
+
for (let i = 0; i < code.length; i++) if (code.charCodeAt(i) === 10) starts.push(i + 1);
|
|
213
|
+
return starts;
|
|
214
|
+
}
|
|
215
|
+
function position(starts, offset) {
|
|
216
|
+
let lo = 0;
|
|
217
|
+
let hi = starts.length - 1;
|
|
218
|
+
while (lo < hi) {
|
|
219
|
+
const mid = lo + hi + 1 >> 1;
|
|
220
|
+
if (starts[mid] <= offset) lo = mid;
|
|
221
|
+
else hi = mid - 1;
|
|
222
|
+
}
|
|
223
|
+
return {
|
|
224
|
+
line: lo + 1,
|
|
225
|
+
column: offset - starts[lo] + 1
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
function unwrap(node) {
|
|
229
|
+
while (node && (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "ParenthesizedExpression")) node = node.expression;
|
|
230
|
+
return node;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Every call Dopesheet understands, in pre-order: tweens (`.to/.from/.fromTo/.set` with 2+ args),
|
|
234
|
+
* `.timeline()`, and timeline ops (`.add/.addLabel/.call/.addPause`). The ordinal is the call's
|
|
235
|
+
* identity, shared by the build transform and the save path.
|
|
236
|
+
*/
|
|
237
|
+
function findCalls(code, filename) {
|
|
238
|
+
return scan(code, filename).calls;
|
|
239
|
+
}
|
|
240
|
+
/** findCalls plus the file's const scope. */
|
|
241
|
+
function scan(code, filename) {
|
|
242
|
+
const program = parse(code, filename);
|
|
243
|
+
const starts = lineIndex(code);
|
|
244
|
+
const calls = [];
|
|
245
|
+
const names = /* @__PURE__ */ new Map();
|
|
246
|
+
/** Variables holding a timeline (`const tl = gsap.timeline()`), so `tl.fade(...)` reads as an effect. */
|
|
247
|
+
const timelineVars = /* @__PURE__ */ new Set();
|
|
248
|
+
const isTimeline = (e) => {
|
|
249
|
+
const x = unwrap(e);
|
|
250
|
+
if (!x) return false;
|
|
251
|
+
if (x.type === "Identifier") return timelineVars.has(x.name);
|
|
252
|
+
if (x.type !== "CallExpression" || x.callee?.type !== "MemberExpression" || x.callee.computed) return false;
|
|
253
|
+
return x.callee.property?.name === "timeline" || isTimeline(x.callee.object);
|
|
254
|
+
};
|
|
255
|
+
walk(program, (n) => {
|
|
256
|
+
if (n.type === "VariableDeclarator" && n.id?.type === "Identifier" && n.init) {
|
|
257
|
+
names.set(unwrap(n.init).start, n.id.name);
|
|
258
|
+
if (isTimeline(n.init)) timelineVars.add(n.id.name);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
if (n.type !== "CallExpression") return;
|
|
262
|
+
const callee = n.callee;
|
|
263
|
+
if (callee?.type !== "MemberExpression" || callee.computed) return;
|
|
264
|
+
const prop = callee.property;
|
|
265
|
+
if (prop?.type !== "Identifier") return;
|
|
266
|
+
const args = n.arguments;
|
|
267
|
+
const name = prop.name;
|
|
268
|
+
let kind;
|
|
269
|
+
let effect;
|
|
270
|
+
let effectPosition;
|
|
271
|
+
const obj = callee.object;
|
|
272
|
+
if (obj?.type === "MemberExpression" && !obj.computed && obj.property?.name === "effects" && args.length >= 1) {
|
|
273
|
+
kind = "effect";
|
|
274
|
+
effect = name;
|
|
275
|
+
} else if (!TIMELINE_API.has(name) && args.length >= 2 && unwrap(args[1])?.type === "ObjectExpression" && isTimeline(obj)) {
|
|
276
|
+
kind = "effect";
|
|
277
|
+
effect = name;
|
|
278
|
+
effectPosition = 2;
|
|
279
|
+
} else if (TWEEN_METHODS.has(name)) {
|
|
280
|
+
if (args.length < 2) return;
|
|
281
|
+
kind = "tween";
|
|
282
|
+
} else if (name === "timeline") kind = "timeline";
|
|
283
|
+
else if (OP_METHODS.has(name)) {
|
|
284
|
+
if (args.length < OP_MIN_ARGS[name]) return;
|
|
285
|
+
kind = "op";
|
|
286
|
+
} else return;
|
|
287
|
+
if (args.some((a) => a.type === "SpreadElement")) return;
|
|
288
|
+
const method = effect ? "effect" : name;
|
|
289
|
+
const vars = [];
|
|
290
|
+
const objectAt = (i) => {
|
|
291
|
+
const a = unwrap(args[i]);
|
|
292
|
+
return a?.type === "ObjectExpression" ? a : void 0;
|
|
293
|
+
};
|
|
294
|
+
if (method === "fromTo") {
|
|
295
|
+
const from = objectAt(1);
|
|
296
|
+
const to = objectAt(2);
|
|
297
|
+
if (from) vars.push({
|
|
298
|
+
role: "fromVars",
|
|
299
|
+
node: from
|
|
300
|
+
});
|
|
301
|
+
if (to) vars.push({
|
|
302
|
+
role: "vars",
|
|
303
|
+
node: to
|
|
304
|
+
});
|
|
305
|
+
} else if (kind === "tween" || kind === "effect") {
|
|
306
|
+
const v = objectAt(1);
|
|
307
|
+
if (v) vars.push({
|
|
308
|
+
role: "vars",
|
|
309
|
+
node: v
|
|
310
|
+
});
|
|
311
|
+
} else if (kind === "timeline") {
|
|
312
|
+
const v = objectAt(0);
|
|
313
|
+
if (v) vars.push({
|
|
314
|
+
role: "vars",
|
|
315
|
+
node: v
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
const { line, column } = position(starts, n.start);
|
|
319
|
+
calls.push({
|
|
320
|
+
ordinal: calls.length,
|
|
321
|
+
kind,
|
|
322
|
+
method,
|
|
323
|
+
callee: code.slice(callee.object.start, callee.object.end),
|
|
324
|
+
calleeEnd: callee.end,
|
|
325
|
+
args,
|
|
326
|
+
positionIndex: effect ? effectPosition : POSITION_INDEX[method],
|
|
327
|
+
...effect ? { effect } : {},
|
|
328
|
+
start: n.start,
|
|
329
|
+
end: n.end,
|
|
330
|
+
line,
|
|
331
|
+
column,
|
|
332
|
+
target: kind === "timeline" || !args[0] ? "" : code.slice(args[0].start, args[0].end),
|
|
333
|
+
vars
|
|
334
|
+
});
|
|
335
|
+
});
|
|
336
|
+
for (const c of calls) if (c.kind === "timeline") c.name = names.get(c.start);
|
|
337
|
+
return {
|
|
338
|
+
calls,
|
|
339
|
+
scope: analyzeScope(program, starts)
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
function keyName(prop) {
|
|
343
|
+
if (prop.computed) return void 0;
|
|
344
|
+
const k = prop.key;
|
|
345
|
+
if (k.type === "Identifier") return k.name;
|
|
346
|
+
if (k.type === "Literal" && (typeof k.value === "string" || typeof k.value === "number")) return String(k.value);
|
|
347
|
+
}
|
|
348
|
+
/** The literal a const binding resolves to (`path` reaches into a const object literal). */
|
|
349
|
+
function bindingOf(scope, name, code, path) {
|
|
350
|
+
const c = scope.consts.get(name);
|
|
351
|
+
if (!c) return void 0;
|
|
352
|
+
let node = c.init;
|
|
353
|
+
if (path !== void 0) {
|
|
354
|
+
if (node.type !== "ObjectExpression") return void 0;
|
|
355
|
+
node = unwrap(findProp(node, path)?.value);
|
|
356
|
+
if (!node) return void 0;
|
|
357
|
+
}
|
|
358
|
+
const lit = classify(node, code);
|
|
359
|
+
if (!lit.editable || lit.value === void 0) return void 0;
|
|
360
|
+
return {
|
|
361
|
+
node,
|
|
362
|
+
binding: {
|
|
363
|
+
name,
|
|
364
|
+
...path !== void 0 ? { path } : {},
|
|
365
|
+
value: lit.value,
|
|
366
|
+
raw: lit.raw,
|
|
367
|
+
uses: c.uses,
|
|
368
|
+
line: c.line
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
function identifierValue(name, raw, code, scope) {
|
|
373
|
+
const b = bindingOf(scope, name, code);
|
|
374
|
+
if (b) return {
|
|
375
|
+
kind: typeof b.binding.value,
|
|
376
|
+
value: b.binding.value,
|
|
377
|
+
raw,
|
|
378
|
+
editable: false,
|
|
379
|
+
reason: `Bound to ${name}`,
|
|
380
|
+
binding: b.binding
|
|
381
|
+
};
|
|
382
|
+
const from = scope.imports.get(name);
|
|
383
|
+
return {
|
|
384
|
+
kind: "expression",
|
|
385
|
+
raw,
|
|
386
|
+
editable: false,
|
|
387
|
+
reason: from ? `Imported from "${from}"` : `Bound to ${name}`
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
function classify(node, code, scope = EMPTY_SCOPE) {
|
|
391
|
+
const raw = code.slice(node.start, node.end);
|
|
392
|
+
const n = unwrap(node);
|
|
393
|
+
if (n.type === "Literal") {
|
|
394
|
+
if (typeof n.value === "number") return {
|
|
395
|
+
kind: "number",
|
|
396
|
+
value: n.value,
|
|
397
|
+
raw,
|
|
398
|
+
editable: true
|
|
399
|
+
};
|
|
400
|
+
if (typeof n.value === "string") return {
|
|
401
|
+
kind: "string",
|
|
402
|
+
value: n.value,
|
|
403
|
+
raw,
|
|
404
|
+
editable: true
|
|
405
|
+
};
|
|
406
|
+
if (typeof n.value === "boolean") return {
|
|
407
|
+
kind: "boolean",
|
|
408
|
+
value: n.value,
|
|
409
|
+
raw,
|
|
410
|
+
editable: true
|
|
411
|
+
};
|
|
412
|
+
return {
|
|
413
|
+
kind: "expression",
|
|
414
|
+
raw,
|
|
415
|
+
editable: false,
|
|
416
|
+
reason: "Not a number, string or boolean"
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
if (n.type === "UnaryExpression" && (n.operator === "-" || n.operator === "+")) {
|
|
420
|
+
const arg = unwrap(n.argument);
|
|
421
|
+
if (arg?.type === "Literal" && typeof arg.value === "number") return {
|
|
422
|
+
kind: "number",
|
|
423
|
+
value: n.operator === "-" ? -arg.value : arg.value,
|
|
424
|
+
raw,
|
|
425
|
+
editable: true
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
if (n.type === "TemplateLiteral" && n.expressions.length === 0) return {
|
|
429
|
+
kind: "string",
|
|
430
|
+
value: n.quasis[0].value.cooked,
|
|
431
|
+
raw,
|
|
432
|
+
editable: true
|
|
433
|
+
};
|
|
434
|
+
if (n.type === "ObjectExpression") {
|
|
435
|
+
const json = literalJson(n);
|
|
436
|
+
return {
|
|
437
|
+
kind: "object",
|
|
438
|
+
raw,
|
|
439
|
+
editable: false,
|
|
440
|
+
reason: "Nested object",
|
|
441
|
+
children: analyzeVars(n, code, scope),
|
|
442
|
+
...json !== void 0 ? { json: JSON.stringify(json) } : {}
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
if (n.type === "ArrayExpression") {
|
|
446
|
+
const json = literalJson(n);
|
|
447
|
+
return {
|
|
448
|
+
kind: "array",
|
|
449
|
+
raw,
|
|
450
|
+
editable: false,
|
|
451
|
+
reason: "Array value",
|
|
452
|
+
...json !== void 0 ? { json: JSON.stringify(json) } : {}
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
if (n.type === "Identifier") return identifierValue(n.name, raw, code, scope);
|
|
456
|
+
if (n.type === "ArrowFunctionExpression" || n.type === "FunctionExpression") return {
|
|
457
|
+
kind: "expression",
|
|
458
|
+
raw,
|
|
459
|
+
editable: false,
|
|
460
|
+
reason: "Function in code"
|
|
461
|
+
};
|
|
462
|
+
return {
|
|
463
|
+
kind: "expression",
|
|
464
|
+
raw,
|
|
465
|
+
editable: false,
|
|
466
|
+
reason: "Computed in code"
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
/** The value of a literal (or an object/array made only of literals), else undefined. */
|
|
470
|
+
function literalJson(node) {
|
|
471
|
+
const n = unwrap(node);
|
|
472
|
+
if (!n) return void 0;
|
|
473
|
+
if (n.type === "Literal") return typeof n.value === "number" || typeof n.value === "string" || typeof n.value === "boolean" ? n.value : void 0;
|
|
474
|
+
if (n.type === "UnaryExpression" && (n.operator === "-" || n.operator === "+")) {
|
|
475
|
+
const arg = unwrap(n.argument);
|
|
476
|
+
if (arg?.type === "Literal" && typeof arg.value === "number") return n.operator === "-" ? -arg.value : arg.value;
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
if (n.type === "TemplateLiteral") return n.expressions.length === 0 ? n.quasis[0].value.cooked : void 0;
|
|
480
|
+
if (n.type === "ArrayExpression") {
|
|
481
|
+
const out = [];
|
|
482
|
+
for (const el of n.elements) {
|
|
483
|
+
if (!el || el.type === "SpreadElement") return void 0;
|
|
484
|
+
const v = literalJson(el);
|
|
485
|
+
if (v === void 0) return void 0;
|
|
486
|
+
out.push(v);
|
|
487
|
+
}
|
|
488
|
+
return out;
|
|
489
|
+
}
|
|
490
|
+
if (n.type === "ObjectExpression") {
|
|
491
|
+
const out = {};
|
|
492
|
+
for (const p of n.properties) {
|
|
493
|
+
if (p.type === "SpreadElement" || p.method || p.shorthand) return void 0;
|
|
494
|
+
const k = keyName(p);
|
|
495
|
+
if (k === void 0 || k in out) return void 0;
|
|
496
|
+
const v = literalJson(p.value);
|
|
497
|
+
if (v === void 0) return void 0;
|
|
498
|
+
out[k] = v;
|
|
499
|
+
}
|
|
500
|
+
return out;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
/** The last property with this key (last one wins in JS). */
|
|
504
|
+
function findProp(obj, key) {
|
|
505
|
+
let found;
|
|
506
|
+
for (const p of obj.properties) if (p.type !== "SpreadElement" && keyName(p) === key) found = p;
|
|
507
|
+
return found;
|
|
508
|
+
}
|
|
509
|
+
/** Keys a `...name` spread supplies, when name is a same-file const object literal (else null). */
|
|
510
|
+
function spreadKeys(spread, code, scope) {
|
|
511
|
+
const arg = unwrap(spread.argument);
|
|
512
|
+
if (arg?.type !== "Identifier") return null;
|
|
513
|
+
const c = scope.consts.get(arg.name);
|
|
514
|
+
if (!c || c.init.type !== "ObjectExpression") return null;
|
|
515
|
+
const out = {};
|
|
516
|
+
for (const p of c.init.properties) {
|
|
517
|
+
if (p.type === "SpreadElement") return null;
|
|
518
|
+
const k = keyName(p);
|
|
519
|
+
if (k === void 0) return null;
|
|
520
|
+
const b = bindingOf(scope, arg.name, code, k);
|
|
521
|
+
const raw = code.slice(p.value.start, p.value.end);
|
|
522
|
+
out[k] = b ? {
|
|
523
|
+
kind: typeof b.binding.value,
|
|
524
|
+
value: b.binding.value,
|
|
525
|
+
raw,
|
|
526
|
+
editable: false,
|
|
527
|
+
reason: `From ...${arg.name}`,
|
|
528
|
+
binding: b.binding
|
|
529
|
+
} : {
|
|
530
|
+
...classify(p.value, code, scope),
|
|
531
|
+
editable: false,
|
|
532
|
+
reason: `From ...${arg.name}`
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
return out;
|
|
536
|
+
}
|
|
537
|
+
function analyzeVars(node, code, scope = EMPTY_SCOPE) {
|
|
538
|
+
const keys = {};
|
|
539
|
+
const order = [];
|
|
540
|
+
const fromSpread = {};
|
|
541
|
+
let hasSpread = false;
|
|
542
|
+
node.properties.forEach((prop) => {
|
|
543
|
+
if (prop.type === "SpreadElement") {
|
|
544
|
+
hasSpread = true;
|
|
545
|
+
const supplied = spreadKeys(prop, code, scope);
|
|
546
|
+
if (supplied) for (const [k, v] of Object.entries(supplied)) {
|
|
547
|
+
fromSpread[k] = v;
|
|
548
|
+
if (k in keys) {
|
|
549
|
+
delete keys[k];
|
|
550
|
+
order.splice(order.indexOf(k), 1);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
else for (const k of order) keys[k] = {
|
|
554
|
+
...keys[k],
|
|
555
|
+
editable: false,
|
|
556
|
+
reason: "A ...spread after this key may override it"
|
|
557
|
+
};
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
const name = keyName(prop);
|
|
561
|
+
if (name === void 0) return;
|
|
562
|
+
let value;
|
|
563
|
+
if (prop.method) value = {
|
|
564
|
+
kind: "expression",
|
|
565
|
+
raw: code.slice(prop.value.start, prop.value.end),
|
|
566
|
+
editable: false,
|
|
567
|
+
reason: "Function in code"
|
|
568
|
+
};
|
|
569
|
+
else if (prop.shorthand) value = identifierValue(name, name, code, scope);
|
|
570
|
+
else value = classify(prop.value, code, scope);
|
|
571
|
+
delete fromSpread[name];
|
|
572
|
+
if (!(name in keys)) order.push(name);
|
|
573
|
+
keys[name] = value;
|
|
574
|
+
});
|
|
575
|
+
return {
|
|
576
|
+
keys,
|
|
577
|
+
order,
|
|
578
|
+
hasSpread,
|
|
579
|
+
...Object.keys(fromSpread).length ? { fromSpread } : {}
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
/** Build-time instrumentation: wraps each vars object with `__dopesheet(vars, meta)`. */
|
|
583
|
+
function instrument(code, filename, fileId) {
|
|
584
|
+
let calls;
|
|
585
|
+
let scope;
|
|
586
|
+
try {
|
|
587
|
+
({calls, scope} = scan(code, filename));
|
|
588
|
+
} catch {
|
|
589
|
+
return null;
|
|
590
|
+
}
|
|
591
|
+
if (!calls.some((c) => c.vars.length || c.kind !== "tween")) return null;
|
|
592
|
+
const hash = hashText(code);
|
|
593
|
+
const s = new MagicString(code);
|
|
594
|
+
for (const call of calls) {
|
|
595
|
+
const base = {
|
|
596
|
+
id: `${fileId}#${call.ordinal}`,
|
|
597
|
+
file: fileId,
|
|
598
|
+
line: call.line,
|
|
599
|
+
column: call.column,
|
|
600
|
+
method: call.method,
|
|
601
|
+
callee: call.callee,
|
|
602
|
+
target: call.target.length > 120 ? call.target.slice(0, 117) + "..." : call.target,
|
|
603
|
+
...call.positionIndex !== void 0 && call.args[call.positionIndex] ? { position: classify(call.args[call.positionIndex], code, scope) } : {},
|
|
604
|
+
...call.name ? { name: call.name } : {},
|
|
605
|
+
...call.effect ? { effect: call.effect } : {},
|
|
606
|
+
hash
|
|
607
|
+
};
|
|
608
|
+
for (const v of call.vars) {
|
|
609
|
+
const meta = {
|
|
610
|
+
...base,
|
|
611
|
+
role: v.role,
|
|
612
|
+
vars: analyzeVars(v.node, code, scope)
|
|
613
|
+
};
|
|
614
|
+
s.prependRight(v.node.start, "(globalThis.__dopesheet ?? ((v) => v))(");
|
|
615
|
+
s.appendLeft(v.node.end, `, ${JSON.stringify(meta)})`);
|
|
616
|
+
}
|
|
617
|
+
if (call.vars.length || call.kind === "tween") continue;
|
|
618
|
+
const meta = {
|
|
619
|
+
...base,
|
|
620
|
+
role: "vars",
|
|
621
|
+
vars: {
|
|
622
|
+
keys: {},
|
|
623
|
+
order: [],
|
|
624
|
+
hasSpread: false
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
const mark = `(globalThis.__dopesheetMark ?? ((m, v) => v))(${JSON.stringify(meta)}`;
|
|
628
|
+
const last = call.args[call.args.length - 1];
|
|
629
|
+
if (last) {
|
|
630
|
+
s.prependRight(last.start, mark + ", ");
|
|
631
|
+
s.appendLeft(last.end, ")");
|
|
632
|
+
} else s.appendLeft(openParen(code, call) + 1, mark + ")");
|
|
633
|
+
}
|
|
634
|
+
return {
|
|
635
|
+
code: s.toString(),
|
|
636
|
+
map: s.generateMap({
|
|
637
|
+
hires: "boundary",
|
|
638
|
+
source: filename,
|
|
639
|
+
includeContent: true
|
|
640
|
+
})
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
/** An edit failure with a taxonomy code (see SaveErrorCode). */
|
|
644
|
+
var EditError = class extends Error {
|
|
645
|
+
code;
|
|
646
|
+
constructor(message, code) {
|
|
647
|
+
super(message);
|
|
648
|
+
this.code = code;
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
function formatNumber(n) {
|
|
652
|
+
if (!Number.isFinite(n)) throw new EditError("Not a finite number", "structure");
|
|
653
|
+
const rounded = Math.round(n * 1e4) / 1e4;
|
|
654
|
+
return String(Object.is(rounded, -0) ? 0 : rounded);
|
|
655
|
+
}
|
|
656
|
+
function quoteOf(raw, fallback) {
|
|
657
|
+
const q = raw?.[0];
|
|
658
|
+
return q === "'" || q === "\"" || q === "`" ? q : fallback;
|
|
659
|
+
}
|
|
660
|
+
function formatLiteral(value, originalRaw, preferredQuote = "\"") {
|
|
661
|
+
if (typeof value === "number") return formatNumber(value);
|
|
662
|
+
if (typeof value === "boolean") return String(value);
|
|
663
|
+
const q = quoteOf(originalRaw, preferredQuote);
|
|
664
|
+
let body = value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n");
|
|
665
|
+
if (q === "`") body = body.replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
|
|
666
|
+
else body = body.split(q).join("\\" + q);
|
|
667
|
+
return q + body + q;
|
|
668
|
+
}
|
|
669
|
+
var IDENT = /^[A-Za-z_$][\w$]*$/;
|
|
670
|
+
function detectQuote(code) {
|
|
671
|
+
return (code.match(/'/g) ?? []).length > (code.match(/"/g) ?? []).length ? "'" : "\"";
|
|
672
|
+
}
|
|
673
|
+
var propKey = (key) => IDENT.test(key) ? key : JSON.stringify(key);
|
|
674
|
+
/** The object a (possibly dotted) key lives in, and the key inside it. */
|
|
675
|
+
function locate(vars, key) {
|
|
676
|
+
if (!key.includes(".") || findProp(vars, key)) return {
|
|
677
|
+
obj: vars,
|
|
678
|
+
key
|
|
679
|
+
};
|
|
680
|
+
const [parent, ...rest] = key.split(".");
|
|
681
|
+
const parentNode = unwrap(findProp(vars, parent)?.value);
|
|
682
|
+
if (parentNode?.type !== "ObjectExpression") throw new EditError(`No "${parent}" object in this call; add it in code first`, "structure");
|
|
683
|
+
return {
|
|
684
|
+
obj: parentNode,
|
|
685
|
+
key: rest.join(".")
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
/** Is a key written before a spread that may replace it? "known": a const spread supplies it. */
|
|
689
|
+
function shadowedBySpread(obj, key, code, scope) {
|
|
690
|
+
let state = null;
|
|
691
|
+
let seen = false;
|
|
692
|
+
for (const p of obj.properties) if (p.type === "SpreadElement") {
|
|
693
|
+
if (!seen) continue;
|
|
694
|
+
const keys = spreadKeys(p, code, scope);
|
|
695
|
+
if (!keys) state = state ?? "unknown";
|
|
696
|
+
else if (key in keys) state = "known";
|
|
697
|
+
} else if (keyName(p) === key) {
|
|
698
|
+
seen = true;
|
|
699
|
+
state = null;
|
|
700
|
+
}
|
|
701
|
+
return state;
|
|
702
|
+
}
|
|
703
|
+
/** The last spread in `obj` that supplies `key` from a same-file const, and that const's name. */
|
|
704
|
+
function spreadSource(obj, key, code, scope) {
|
|
705
|
+
let found;
|
|
706
|
+
for (const p of obj.properties) if (p.type === "SpreadElement") {
|
|
707
|
+
const keys = spreadKeys(p, code, scope);
|
|
708
|
+
if (keys && key in keys) found = unwrap(p.argument).name;
|
|
709
|
+
} else if (keyName(p) === key) found = void 0;
|
|
710
|
+
return found;
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Applies edits to the source. Only the edited spans change; formatting and comments are kept.
|
|
714
|
+
* The whole batch fails (code unchanged) if any edit fails.
|
|
715
|
+
*/
|
|
716
|
+
function applyEdits(code, filename, edits) {
|
|
717
|
+
const { calls, scope } = scan(code, filename);
|
|
718
|
+
const s = new MagicString(code);
|
|
719
|
+
const preferredQuote = detectQuote(code);
|
|
720
|
+
const results = [];
|
|
721
|
+
const unique = /* @__PURE__ */ new Map();
|
|
722
|
+
for (const e of edits) unique.set(`${e.ordinal}|${e.role}|${e.key}`, e);
|
|
723
|
+
const inserts = /* @__PURE__ */ new Map();
|
|
724
|
+
const timelineInserts = /* @__PURE__ */ new Map();
|
|
725
|
+
const bindingWrites = /* @__PURE__ */ new Map();
|
|
726
|
+
const removals = /* @__PURE__ */ new Map();
|
|
727
|
+
const removed = /* @__PURE__ */ new Set();
|
|
728
|
+
for (const edit of unique.values()) try {
|
|
729
|
+
const call = calls[edit.ordinal];
|
|
730
|
+
if (!call) throw new EditError("Call not found in the file", "not-found");
|
|
731
|
+
if (edit.key === "@position") {
|
|
732
|
+
editPosition(code, s, call, edit.value, preferredQuote, scope);
|
|
733
|
+
results.push({
|
|
734
|
+
edit,
|
|
735
|
+
ok: true
|
|
736
|
+
});
|
|
737
|
+
continue;
|
|
738
|
+
}
|
|
739
|
+
const vars = call.vars.find((v) => v.role === edit.role);
|
|
740
|
+
if (!vars && call.kind === "timeline" && call.args.length === 0 && !edit.key.includes(".") && edit.mode !== "remove" && edit.mode !== "binding") {
|
|
741
|
+
const list = timelineInserts.get(call) ?? [];
|
|
742
|
+
list.push(`${propKey(edit.key)}: ${formatLiteral(edit.value, void 0, preferredQuote)}`);
|
|
743
|
+
timelineInserts.set(call, list);
|
|
744
|
+
results.push({
|
|
745
|
+
edit,
|
|
746
|
+
ok: true
|
|
747
|
+
});
|
|
748
|
+
continue;
|
|
749
|
+
}
|
|
750
|
+
if (!vars) throw new EditError("The vars are not an object literal", "not-literal");
|
|
751
|
+
const { obj, key } = locate(vars.node, edit.key);
|
|
752
|
+
const mode = edit.mode ?? "value";
|
|
753
|
+
const shadow = shadowedBySpread(obj, key, code, scope);
|
|
754
|
+
if (shadow === "unknown" && mode !== "override" && mode !== "remove") throw new EditError("The value has no source form (A ...spread after this key may override it)", "not-literal");
|
|
755
|
+
const prop = shadow && mode !== "remove" ? void 0 : findProp(obj, key);
|
|
756
|
+
if (mode === "remove") {
|
|
757
|
+
if (!prop) throw new EditError(`"${edit.key}" is not written in this call`, "structure");
|
|
758
|
+
const set = removals.get(obj) ?? /* @__PURE__ */ new Set();
|
|
759
|
+
set.add(prop);
|
|
760
|
+
removals.set(obj, set);
|
|
761
|
+
removed.add(prop);
|
|
762
|
+
} else if (mode === "binding") {
|
|
763
|
+
let name;
|
|
764
|
+
let path;
|
|
765
|
+
if (prop) {
|
|
766
|
+
const v = prop.shorthand ? prop.key : unwrap(prop.value);
|
|
767
|
+
if (v?.type !== "Identifier") throw new EditError("The value is not read from a const", "not-literal");
|
|
768
|
+
name = v.name;
|
|
769
|
+
} else {
|
|
770
|
+
name = spreadSource(obj, key, code, scope);
|
|
771
|
+
path = key;
|
|
772
|
+
}
|
|
773
|
+
const b = name ? bindingOf(scope, name, code, path) : void 0;
|
|
774
|
+
if (!b) throw new EditError(`The value has no source form (${name ? `${name} is not a literal const in this file` : "not in code"})`, "not-literal");
|
|
775
|
+
bindingWrites.set(b.node, formatLiteral(edit.value, b.binding.raw, preferredQuote));
|
|
776
|
+
} else if (mode === "json") {
|
|
777
|
+
let next;
|
|
778
|
+
try {
|
|
779
|
+
next = JSON.parse(String(edit.value));
|
|
780
|
+
} catch {
|
|
781
|
+
throw new EditError("The new value is not valid JSON", "structure");
|
|
782
|
+
}
|
|
783
|
+
if (prop) {
|
|
784
|
+
if (prop.method || prop.shorthand) throw new EditError("The value has no source form (computed in code)", "not-literal");
|
|
785
|
+
writeJson(code, s, prop.value, next, preferredQuote);
|
|
786
|
+
} else {
|
|
787
|
+
const list = inserts.get(obj) ?? [];
|
|
788
|
+
list.push(`${propKey(key)}: ${formatValue(next, preferredQuote)}`);
|
|
789
|
+
inserts.set(obj, list);
|
|
790
|
+
}
|
|
791
|
+
} else if (prop) {
|
|
792
|
+
if (prop.method) throw new EditError("The value has no source form (Function in code)", "not-literal");
|
|
793
|
+
const current = prop.shorthand ? identifierValue(key, key, code, scope) : classify(prop.value, code, scope);
|
|
794
|
+
const overridable = mode === "override" && current.binding;
|
|
795
|
+
if (!current.editable && !overridable) throw new EditError(`The value has no source form (${current.reason})`, "not-literal");
|
|
796
|
+
const literal = formatLiteral(edit.value, current.binding ? void 0 : current.raw, preferredQuote);
|
|
797
|
+
if (prop.shorthand) s.overwrite(prop.start, prop.end, `${propKey(key)}: ${literal}`);
|
|
798
|
+
else {
|
|
799
|
+
const target = unwrap(prop.value);
|
|
800
|
+
s.overwrite(target.start, target.end, literal);
|
|
801
|
+
}
|
|
802
|
+
} else {
|
|
803
|
+
if (mode === "value" && spreadSource(obj, key, code, scope)) throw new EditError("The value comes from a spread; edit the const or override it here", "not-literal");
|
|
804
|
+
const list = inserts.get(obj) ?? [];
|
|
805
|
+
list.push(`${propKey(key)}: ${formatLiteral(edit.value, void 0, preferredQuote)}`);
|
|
806
|
+
inserts.set(obj, list);
|
|
807
|
+
}
|
|
808
|
+
results.push({
|
|
809
|
+
edit,
|
|
810
|
+
ok: true
|
|
811
|
+
});
|
|
812
|
+
} catch (err) {
|
|
813
|
+
const code = err instanceof EditError ? err.code : "structure";
|
|
814
|
+
results.push({
|
|
815
|
+
edit,
|
|
816
|
+
ok: false,
|
|
817
|
+
error: err.message,
|
|
818
|
+
code
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
for (const [node, text] of bindingWrites) s.overwrite(node.start, node.end, text);
|
|
822
|
+
for (const [obj, gone] of removals) removeProperties(s, obj, gone, inserts.has(obj));
|
|
823
|
+
for (const [obj, entries] of inserts) insertProperties(code, s, obj, entries, removed);
|
|
824
|
+
for (const [call, entries] of timelineInserts) s.appendLeft(openParen(code, call) + 1, `{ ${entries.join(", ")} }`);
|
|
825
|
+
if (results.some((r) => !r.ok)) return {
|
|
826
|
+
code,
|
|
827
|
+
results,
|
|
828
|
+
changed: false
|
|
829
|
+
};
|
|
830
|
+
const out = s.toString();
|
|
831
|
+
return {
|
|
832
|
+
code: out,
|
|
833
|
+
results,
|
|
834
|
+
changed: out !== code
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* Deletes properties and the commas that joined them. Each run of removed properties goes up to the
|
|
839
|
+
* next kept one (so the next one takes its place), or, at the end, from the previous kept one.
|
|
840
|
+
*/
|
|
841
|
+
function removeProperties(s, obj, gone, refill) {
|
|
842
|
+
const props = obj.properties;
|
|
843
|
+
if (props.every((p) => gone.has(p))) {
|
|
844
|
+
if (!refill) s.overwrite(obj.start, obj.end, "{}");
|
|
845
|
+
return;
|
|
846
|
+
}
|
|
847
|
+
for (let i = 0; i < props.length; i++) {
|
|
848
|
+
if (!gone.has(props[i])) continue;
|
|
849
|
+
let j = i;
|
|
850
|
+
while (j + 1 < props.length && gone.has(props[j + 1])) j++;
|
|
851
|
+
if (j + 1 < props.length) s.remove(props[i].start, props[j + 1].start);
|
|
852
|
+
else s.remove(props[i - 1].end, props[j].end);
|
|
853
|
+
i = j;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
/** Raw source of a key (or the position) of one call; undefined when it isn't written. */
|
|
857
|
+
function rawOf(code, filename, ordinal, role, key) {
|
|
858
|
+
const call = findCalls(code, filename)[ordinal];
|
|
859
|
+
if (!call) return void 0;
|
|
860
|
+
if (key === "@position") {
|
|
861
|
+
const a = call.positionIndex !== void 0 ? call.args[call.positionIndex] : void 0;
|
|
862
|
+
return a ? code.slice(a.start, a.end) : void 0;
|
|
863
|
+
}
|
|
864
|
+
const vars = call.vars.find((v) => v.role === role);
|
|
865
|
+
if (!vars) return void 0;
|
|
866
|
+
try {
|
|
867
|
+
const { obj, key: k } = locate(vars.node, key);
|
|
868
|
+
const p = findProp(obj, k);
|
|
869
|
+
return p ? code.slice(p.start, p.end) : void 0;
|
|
870
|
+
} catch {
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* Maps call ordinals in an old version of a file to the same calls in a new version. A call is the
|
|
876
|
+
* same when method, callee and target match and it is the only such call, or its full text matches
|
|
877
|
+
* exactly one candidate, or the k-th of n such calls stays the k-th of n. Otherwise null.
|
|
878
|
+
*/
|
|
879
|
+
function relocate(oldCode, newCode, filename, ordinals) {
|
|
880
|
+
const before = findCalls(oldCode, filename);
|
|
881
|
+
const after = findCalls(newCode, filename);
|
|
882
|
+
const fp = (c) => `${c.method}|${c.callee}|${c.target}`;
|
|
883
|
+
const text = (src, c) => src.slice(c.start, c.end);
|
|
884
|
+
const out = /* @__PURE__ */ new Map();
|
|
885
|
+
for (const ord of ordinals) {
|
|
886
|
+
const old = before[ord];
|
|
887
|
+
if (!old) {
|
|
888
|
+
out.set(ord, null);
|
|
889
|
+
continue;
|
|
890
|
+
}
|
|
891
|
+
const sameOld = before.filter((c) => fp(c) === fp(old));
|
|
892
|
+
const cands = after.filter((c) => fp(c) === fp(old));
|
|
893
|
+
let match;
|
|
894
|
+
if (cands.length === 1) match = cands[0];
|
|
895
|
+
else {
|
|
896
|
+
const exact = cands.filter((c) => text(newCode, c) === text(oldCode, old));
|
|
897
|
+
if (exact.length === 1) match = exact[0];
|
|
898
|
+
else if (cands.length === sameOld.length) match = cands[sameOld.indexOf(old)];
|
|
899
|
+
}
|
|
900
|
+
out.set(ord, match ? match.ordinal : null);
|
|
901
|
+
}
|
|
902
|
+
return out;
|
|
903
|
+
}
|
|
904
|
+
function insertProperties(code, s, obj, entries, removed = /* @__PURE__ */ new Set()) {
|
|
905
|
+
const props = obj.properties;
|
|
906
|
+
const kept = props.filter((p) => !removed.has(p));
|
|
907
|
+
if (kept.length === 0) {
|
|
908
|
+
s.overwrite(obj.start, obj.end, `{ ${entries.join(", ")} }`);
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
const anchor = kept[kept.length - 1];
|
|
912
|
+
const first = props[0];
|
|
913
|
+
const last = props[props.length - 1];
|
|
914
|
+
const multiline = code.slice(obj.start, first.start).includes("\n");
|
|
915
|
+
let indent = "";
|
|
916
|
+
if (multiline) {
|
|
917
|
+
const lineStart = code.lastIndexOf("\n", first.start - 1) + 1;
|
|
918
|
+
indent = code.slice(lineStart, first.start).match(/^\s*/)?.[0] ?? "";
|
|
919
|
+
}
|
|
920
|
+
let i = last.end;
|
|
921
|
+
while (i < obj.end && /\s/.test(code[i])) i++;
|
|
922
|
+
const trailingComma = code[i] === ",";
|
|
923
|
+
if (multiline) {
|
|
924
|
+
const eol = code.slice(obj.start, first.start).includes("\r\n") ? "\r\n" : "\n";
|
|
925
|
+
const text = entries.map((e) => `${eol}${indent}${e},`).join("");
|
|
926
|
+
if (trailingComma) s.appendLeft(i + 1, text);
|
|
927
|
+
else s.appendLeft(anchor.end, "," + text.slice(0, -1));
|
|
928
|
+
} else {
|
|
929
|
+
const text = entries.join(", ");
|
|
930
|
+
if (trailingComma) s.appendLeft(i + 1, ` ${text},`);
|
|
931
|
+
else s.appendLeft(anchor.end, `, ${text}`);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
/** Offset of the "(" that opens a call's argument list. */
|
|
935
|
+
function openParen(code, call) {
|
|
936
|
+
const i = code.indexOf("(", call.calleeEnd);
|
|
937
|
+
if (i < 0 || i > call.end) throw new EditError("No argument list", "structure");
|
|
938
|
+
return i;
|
|
939
|
+
}
|
|
940
|
+
/** Rewrites (or adds) the position argument of a call; never changes its other arguments. */
|
|
941
|
+
function editPosition(code, s, call, value, quote, scope) {
|
|
942
|
+
const index = call.positionIndex;
|
|
943
|
+
if (index === void 0) throw new EditError(`${call.method}() has no position parameter`, "structure");
|
|
944
|
+
const existing = call.args[index];
|
|
945
|
+
if (existing) {
|
|
946
|
+
const current = classify(existing, code, scope);
|
|
947
|
+
if (!current.editable) throw new EditError(`The position has no source form (${current.reason})`, "not-literal");
|
|
948
|
+
const target = unwrap(existing);
|
|
949
|
+
s.overwrite(target.start, target.end, formatLiteral(value, current.raw, quote));
|
|
950
|
+
return;
|
|
951
|
+
}
|
|
952
|
+
const text = [...Array.from({ length: index - call.args.length }, () => "undefined"), formatLiteral(value, void 0, quote)].join(", ");
|
|
953
|
+
const last = call.args[call.args.length - 1];
|
|
954
|
+
if (!last) {
|
|
955
|
+
s.appendLeft(openParen(code, call) + 1, text);
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
let i = last.end;
|
|
959
|
+
while (i < call.end && /\s/.test(code[i])) i++;
|
|
960
|
+
if (code[i] === ",") s.appendLeft(i + 1, ` ${text},`);
|
|
961
|
+
else s.appendLeft(last.end, `, ${text}`);
|
|
962
|
+
}
|
|
963
|
+
var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
964
|
+
/** A key as source text, quoted only when it isn't an identifier ("50%" keeps the file's quotes). */
|
|
965
|
+
function keyText(key, quote) {
|
|
966
|
+
return IDENT.test(key) ? key : formatLiteral(key, void 0, quote);
|
|
967
|
+
}
|
|
968
|
+
/** Source text for a new value: `{ x: 100, duration: 0.5 }`, `[0, 100]`, literals. */
|
|
969
|
+
function formatValue(v, quote) {
|
|
970
|
+
if (Array.isArray(v)) return `[${v.map((x) => formatValue(x, quote)).join(", ")}]`;
|
|
971
|
+
if (isObj(v)) {
|
|
972
|
+
const entries = Object.entries(v);
|
|
973
|
+
return entries.length ? `{ ${entries.map(([k, x]) => `${keyText(k, quote)}: ${formatValue(x, quote)}`).join(", ")} }` : "{}";
|
|
974
|
+
}
|
|
975
|
+
return formatLiteral(v, void 0, quote);
|
|
976
|
+
}
|
|
977
|
+
function deepEqual(a, b) {
|
|
978
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
979
|
+
}
|
|
980
|
+
/** 0..1: how alike two values are (objects: the share of entries that match). Aligns array edits. */
|
|
981
|
+
function similarity(a, b) {
|
|
982
|
+
if (deepEqual(a, b)) return 1;
|
|
983
|
+
if (isObj(a) && isObj(b)) {
|
|
984
|
+
const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
|
|
985
|
+
let same = 0;
|
|
986
|
+
for (const k of keys) if (deepEqual(a[k], b[k])) same++;
|
|
987
|
+
return keys.size ? same / keys.size : 1;
|
|
988
|
+
}
|
|
989
|
+
return 0;
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Rewrites `node` (as written in the file) into `next`, touching only what differs: literals that
|
|
993
|
+
* changed, entries added or removed, keys renamed (a keyframe moved from "50%" to "40%").
|
|
994
|
+
*/
|
|
995
|
+
function writeJson(code, s, node, next, quote) {
|
|
996
|
+
const n = unwrap(node);
|
|
997
|
+
if (n.type === "ObjectExpression" && isObj(next)) return writeObject(code, s, n, next, quote);
|
|
998
|
+
if (n.type === "ArrayExpression" && Array.isArray(next)) return writeArray(code, s, n, next, quote);
|
|
999
|
+
const current = literalJson(n);
|
|
1000
|
+
if (current === void 0 && n.type !== "ObjectExpression" && n.type !== "ArrayExpression") throw new EditError(`The value has no source form (${classify(n, code).reason ?? "computed in code"})`, "not-literal");
|
|
1001
|
+
if (deepEqual(current, next)) return;
|
|
1002
|
+
const raw = code.slice(n.start, n.end);
|
|
1003
|
+
s.overwrite(n.start, n.end, typeof next === "string" ? formatLiteral(next, raw, quote) : formatValue(next, quote));
|
|
1004
|
+
}
|
|
1005
|
+
function writeObject(code, s, obj, next, quote) {
|
|
1006
|
+
const props = obj.properties;
|
|
1007
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
1008
|
+
for (const p of props) {
|
|
1009
|
+
const k = p.type === "SpreadElement" || p.method ? void 0 : keyName(p);
|
|
1010
|
+
if (k === void 0 || byKey.has(k)) throw new EditError("The object has computed parts (a spread, method or computed key)", "structure");
|
|
1011
|
+
byKey.set(k, p);
|
|
1012
|
+
}
|
|
1013
|
+
const onlyOld = [...byKey.keys()].filter((k) => !(k in next));
|
|
1014
|
+
const onlyNew = Object.keys(next).filter((k) => !byKey.has(k));
|
|
1015
|
+
const renames = Math.min(onlyOld.length, onlyNew.length);
|
|
1016
|
+
for (let i = 0; i < renames; i++) {
|
|
1017
|
+
const p = byKey.get(onlyOld[i]);
|
|
1018
|
+
const raw = code.slice(p.key.start, p.key.end);
|
|
1019
|
+
s.overwrite(p.key.start, p.key.end, IDENT.test(onlyNew[i]) && !/^["'`]/.test(raw) ? onlyNew[i] : formatLiteral(onlyNew[i], raw, quote));
|
|
1020
|
+
writeJson(code, s, p.value, next[onlyNew[i]], quote);
|
|
1021
|
+
}
|
|
1022
|
+
for (const [k, p] of byKey) if (k in next) writeJson(code, s, p.value, next[k], quote);
|
|
1023
|
+
const gone = new Set(onlyOld.slice(renames).map((k) => byKey.get(k)));
|
|
1024
|
+
const added = onlyNew.slice(renames).map((k) => `${keyText(k, quote)}: ${formatValue(next[k], quote)}`);
|
|
1025
|
+
if (gone.size) removeProperties(s, obj, gone, added.length > 0);
|
|
1026
|
+
if (added.length) insertProperties(code, s, obj, added, gone);
|
|
1027
|
+
}
|
|
1028
|
+
function writeArray(code, s, arr, next, quote) {
|
|
1029
|
+
const els = arr.elements;
|
|
1030
|
+
if (els.some((e) => !e || e.type === "SpreadElement")) throw new EditError("The array has holes or spreads", "structure");
|
|
1031
|
+
const nodes = els;
|
|
1032
|
+
const old = nodes.map((e) => literalJson(e));
|
|
1033
|
+
const n = nodes.length;
|
|
1034
|
+
const m = next.length;
|
|
1035
|
+
if (m === n + 1 || m === n - 1) {
|
|
1036
|
+
const longer = m > n ? next : old;
|
|
1037
|
+
const shorter = m > n ? old : next;
|
|
1038
|
+
let best = shorter.length;
|
|
1039
|
+
let bestScore = -1;
|
|
1040
|
+
for (let k = 0; k <= shorter.length; k++) {
|
|
1041
|
+
let score = 0;
|
|
1042
|
+
for (let j = 0; j < shorter.length; j++) score += similarity(shorter[j], longer[j < k ? j : j + 1]);
|
|
1043
|
+
if (score > bestScore) {
|
|
1044
|
+
bestScore = score;
|
|
1045
|
+
best = k;
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
if (m > n) {
|
|
1049
|
+
nodes.forEach((node, j) => writeJson(code, s, node, next[j < best ? j : j + 1], quote));
|
|
1050
|
+
insertElement(code, s, arr, best, formatValue(next[best], quote));
|
|
1051
|
+
} else {
|
|
1052
|
+
next.forEach((v, j) => writeJson(code, s, nodes[j < best ? j : j + 1], v, quote));
|
|
1053
|
+
removeElements(s, arr, /* @__PURE__ */ new Set([nodes[best]]));
|
|
1054
|
+
}
|
|
1055
|
+
return;
|
|
1056
|
+
}
|
|
1057
|
+
for (let j = 0; j < Math.min(n, m); j++) writeJson(code, s, nodes[j], next[j], quote);
|
|
1058
|
+
if (m > n) for (let j = n; j < m; j++) insertElement(code, s, arr, n, formatValue(next[j], quote));
|
|
1059
|
+
else if (n > m) removeElements(s, arr, new Set(nodes.slice(m)));
|
|
1060
|
+
}
|
|
1061
|
+
/** Inserts one element before index `at` (or at the end), in the array's own layout. */
|
|
1062
|
+
function insertElement(code, s, arr, at, text) {
|
|
1063
|
+
const els = arr.elements;
|
|
1064
|
+
if (!els.length) {
|
|
1065
|
+
s.overwrite(arr.start, arr.end, `[${text}]`);
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
const first = els[0];
|
|
1069
|
+
const lead = code.slice(arr.start + 1, first.start);
|
|
1070
|
+
const multiline = lead.includes("\n");
|
|
1071
|
+
const eol = lead.includes("\r\n") ? "\r\n" : "\n";
|
|
1072
|
+
const indent = multiline ? code.slice(code.lastIndexOf("\n", first.start - 1) + 1, first.start).match(/^\s*/)?.[0] ?? "" : "";
|
|
1073
|
+
const sep = multiline ? eol + indent : " ";
|
|
1074
|
+
if (at < els.length) {
|
|
1075
|
+
s.prependRight(els[at].start, `${text},${sep}`);
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
const last = els[els.length - 1];
|
|
1079
|
+
let i = last.end;
|
|
1080
|
+
while (i < arr.end && /\s/.test(code[i])) i++;
|
|
1081
|
+
if (code[i] === ",") s.appendLeft(i + 1, multiline ? `${sep}${text},` : ` ${text},`);
|
|
1082
|
+
else s.appendLeft(last.end, `,${sep}${text}`);
|
|
1083
|
+
}
|
|
1084
|
+
/** Deletes elements and the commas that joined them (see removeProperties). */
|
|
1085
|
+
function removeElements(s, arr, gone) {
|
|
1086
|
+
const els = arr.elements;
|
|
1087
|
+
if (els.every((e) => gone.has(e))) {
|
|
1088
|
+
s.overwrite(arr.start, arr.end, "[]");
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
for (let i = 0; i < els.length; i++) {
|
|
1092
|
+
if (!gone.has(els[i])) continue;
|
|
1093
|
+
let j = i;
|
|
1094
|
+
while (j + 1 < els.length && gone.has(els[j + 1])) j++;
|
|
1095
|
+
if (j + 1 < els.length) s.remove(els[i].start, els[j + 1].start);
|
|
1096
|
+
else s.remove(els[i - 1].end, els[j].end);
|
|
1097
|
+
i = j;
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
// ../vite-plugin/src/index.ts
|
|
1101
|
+
var BOOT_ID = "virtual:dopesheet/boot";
|
|
1102
|
+
var RESOLVED_BOOT_ID = "\0" + BOOT_ID;
|
|
1103
|
+
var DOCK_ID = "virtual:dopesheet/dock";
|
|
1104
|
+
var RESOLVED_DOCK_ID = "\0" + DOCK_ID;
|
|
1105
|
+
var SCRIPT_RE = /\.[cm]?[jt]sx?$/;
|
|
1106
|
+
var QUICK_RE = /\.(to|from|fromTo|set|timeline)\s*\(|\.effects\./;
|
|
1107
|
+
var SELF_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
|
|
1108
|
+
function toPosix(p) {
|
|
1109
|
+
return p.split(sep).join("/");
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* Every file version a page was built from, by hash. Saves made against an older version are
|
|
1113
|
+
* relocated into the current file (or refused) by comparing the two.
|
|
1114
|
+
*/
|
|
1115
|
+
var SourceCache = class {
|
|
1116
|
+
map = /* @__PURE__ */ new Map();
|
|
1117
|
+
limit;
|
|
1118
|
+
dir;
|
|
1119
|
+
/**
|
|
1120
|
+
* `dir` also keeps each version on disk, for bundlers that transform files in other processes
|
|
1121
|
+
* than the one that saves (Turbopack, webpack workers).
|
|
1122
|
+
*/
|
|
1123
|
+
constructor(limit = 500, dir) {
|
|
1124
|
+
this.limit = limit;
|
|
1125
|
+
this.dir = dir;
|
|
1126
|
+
}
|
|
1127
|
+
remember(code) {
|
|
1128
|
+
const hash = hashText(code);
|
|
1129
|
+
this.map.delete(hash);
|
|
1130
|
+
this.map.set(hash, code);
|
|
1131
|
+
if (this.map.size > this.limit) this.map.delete(this.map.keys().next().value);
|
|
1132
|
+
if (this.dir) try {
|
|
1133
|
+
mkdirSync(this.dir, { recursive: true });
|
|
1134
|
+
const file = resolve(this.dir, `${hash}.txt`);
|
|
1135
|
+
if (!existsSync(file)) writeFileSync(file, code);
|
|
1136
|
+
} catch {}
|
|
1137
|
+
return hash;
|
|
1138
|
+
}
|
|
1139
|
+
get(hash) {
|
|
1140
|
+
const hit = this.map.get(hash);
|
|
1141
|
+
if (hit !== void 0 || !this.dir || !/^[\w-]+$/.test(hash)) return hit;
|
|
1142
|
+
try {
|
|
1143
|
+
return readFileSync(resolve(this.dir, `${hash}.txt`), "utf8");
|
|
1144
|
+
} catch {
|
|
1145
|
+
return;
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
};
|
|
1149
|
+
var DOCK_HTML = `<!doctype html>
|
|
1150
|
+
<html lang="en">
|
|
1151
|
+
<head>
|
|
1152
|
+
<meta charset="utf-8" />
|
|
1153
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
1154
|
+
<meta name="dopesheet" content="off" />
|
|
1155
|
+
<title>Dopesheet</title>
|
|
1156
|
+
<link rel="icon" href="data:," />
|
|
1157
|
+
<script type="module" src="/@id/__x00__${DOCK_ID}"><\/script>
|
|
1158
|
+
</head>
|
|
1159
|
+
<body></body>
|
|
1160
|
+
</html>`;
|
|
1161
|
+
function dopesheet(options = {}) {
|
|
1162
|
+
let root = process.cwd();
|
|
1163
|
+
const sources = new SourceCache();
|
|
1164
|
+
const mods = options.modules ?? {
|
|
1165
|
+
runtime: "@dopesheet/runtime",
|
|
1166
|
+
ui: "@dopesheet/ui"
|
|
1167
|
+
};
|
|
1168
|
+
return {
|
|
1169
|
+
name: "dopesheet",
|
|
1170
|
+
apply: "serve",
|
|
1171
|
+
enforce: "pre",
|
|
1172
|
+
configResolved(config) {
|
|
1173
|
+
root = config.root;
|
|
1174
|
+
},
|
|
1175
|
+
resolveId(id) {
|
|
1176
|
+
if (id === BOOT_ID) return RESOLVED_BOOT_ID;
|
|
1177
|
+
if (id === DOCK_ID) return RESOLVED_DOCK_ID;
|
|
1178
|
+
},
|
|
1179
|
+
load(id) {
|
|
1180
|
+
if (id === RESOLVED_DOCK_ID) return `import(${JSON.stringify(mods.ui)}).then((m) => m.mountDocked());`;
|
|
1181
|
+
if (id !== RESOLVED_BOOT_ID) return;
|
|
1182
|
+
const ui = options.ui !== false;
|
|
1183
|
+
return [
|
|
1184
|
+
`import { gsap } from "gsap";`,
|
|
1185
|
+
`import { install } from ${JSON.stringify(mods.runtime)};`,
|
|
1186
|
+
`const runtime = install(gsap);`,
|
|
1187
|
+
`const dock = window.parent !== window ? (() => { try { return window.parent.__DOPESHEET_DOCK__; } catch { return undefined; } })() : undefined;`,
|
|
1188
|
+
`if (dock) dock.attach(runtime, window);`,
|
|
1189
|
+
ui ? `else import(${JSON.stringify(mods.ui)}).then((m) => m.mount(runtime));` : ``
|
|
1190
|
+
].join("\n");
|
|
1191
|
+
},
|
|
1192
|
+
transformIndexHtml: {
|
|
1193
|
+
order: "pre",
|
|
1194
|
+
handler(html) {
|
|
1195
|
+
if (/<meta\s+name="dopesheet"\s+content="off"/.test(html)) return;
|
|
1196
|
+
return [{
|
|
1197
|
+
tag: "script",
|
|
1198
|
+
attrs: {
|
|
1199
|
+
type: "module",
|
|
1200
|
+
src: `/@id/__x00__${BOOT_ID}`
|
|
1201
|
+
},
|
|
1202
|
+
injectTo: "head-prepend"
|
|
1203
|
+
}];
|
|
1204
|
+
}
|
|
1205
|
+
},
|
|
1206
|
+
transform(code, id) {
|
|
1207
|
+
if (id.startsWith("\0") || id.includes("?") || id.includes("/node_modules/") || !SCRIPT_RE.test(id)) return;
|
|
1208
|
+
if (toPosix(id).startsWith(toPosix(SELF_DIR) + "/")) return;
|
|
1209
|
+
if (!QUICK_RE.test(code)) return;
|
|
1210
|
+
const fileId = toPosix(relative(root, id));
|
|
1211
|
+
sources.remember(code);
|
|
1212
|
+
return instrument(code, id, fileId);
|
|
1213
|
+
},
|
|
1214
|
+
configureServer(server) {
|
|
1215
|
+
server.middlewares.use(SAVE_ENDPOINT, (req, res) => {
|
|
1216
|
+
handleSave(root, req, res, sources).catch((err) => send(res, 500, {
|
|
1217
|
+
ok: false,
|
|
1218
|
+
error: String(err?.message ?? err)
|
|
1219
|
+
}));
|
|
1220
|
+
});
|
|
1221
|
+
server.middlewares.use(RELOCATE_ENDPOINT, (req, res) => {
|
|
1222
|
+
(async () => {
|
|
1223
|
+
if (req.method !== "POST") return send(res, 405, { error: "POST only" });
|
|
1224
|
+
const body = JSON.parse(await readBody(req));
|
|
1225
|
+
send(res, 200, await relocateSites(root, body, sources));
|
|
1226
|
+
})().catch((err) => send(res, 500, { error: String(err?.message ?? err) }));
|
|
1227
|
+
});
|
|
1228
|
+
server.middlewares.use(DOCK_PATH, (req, res, next) => {
|
|
1229
|
+
if (req.method !== "GET") return next();
|
|
1230
|
+
res.setHeader("content-type", "text/html");
|
|
1231
|
+
res.end(DOCK_HTML);
|
|
1232
|
+
});
|
|
1233
|
+
}
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
function send(res, status, body) {
|
|
1237
|
+
res.statusCode = status;
|
|
1238
|
+
res.setHeader("content-type", "application/json");
|
|
1239
|
+
res.end(JSON.stringify(body));
|
|
1240
|
+
}
|
|
1241
|
+
async function readBody(req) {
|
|
1242
|
+
const chunks = [];
|
|
1243
|
+
for await (const chunk of req) chunks.push(chunk);
|
|
1244
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
1245
|
+
}
|
|
1246
|
+
async function handleSave(root, req, res, sources = new SourceCache()) {
|
|
1247
|
+
if (req.method !== "POST") return send(res, 405, {
|
|
1248
|
+
ok: false,
|
|
1249
|
+
error: "POST only"
|
|
1250
|
+
});
|
|
1251
|
+
return send(res, 200, await saveEdits(root, JSON.parse(await readBody(req)), sources));
|
|
1252
|
+
}
|
|
1253
|
+
/** Resolves a project-relative file, refusing anything outside the project or in node_modules. */
|
|
1254
|
+
function projectFile(root, file) {
|
|
1255
|
+
const abs = resolve(root, file);
|
|
1256
|
+
const rel = relative(root, abs);
|
|
1257
|
+
if (isAbsolute(rel) || rel.startsWith("..") || abs.includes(`${sep}node_modules${sep}`)) return null;
|
|
1258
|
+
return abs;
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* Groups edits per file and applies each file's batch atomically (all of a file's changes or none).
|
|
1262
|
+
* Edits made against an older version of a file are relocated into the current one; a change whose
|
|
1263
|
+
* own text was edited outside the editor since the page loaded is refused, never overwritten.
|
|
1264
|
+
*/
|
|
1265
|
+
async function saveEdits(root, body, sources = new SourceCache()) {
|
|
1266
|
+
const results = [];
|
|
1267
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
1268
|
+
for (const e of body.edits ?? []) {
|
|
1269
|
+
const parsed = parseSiteId(e.site);
|
|
1270
|
+
if (!parsed) {
|
|
1271
|
+
results.push({
|
|
1272
|
+
site: e.site,
|
|
1273
|
+
role: e.role,
|
|
1274
|
+
key: e.key,
|
|
1275
|
+
ok: false,
|
|
1276
|
+
error: "Not a saveable call",
|
|
1277
|
+
code: "not-found"
|
|
1278
|
+
});
|
|
1279
|
+
continue;
|
|
1280
|
+
}
|
|
1281
|
+
const list = byFile.get(parsed.file) ?? [];
|
|
1282
|
+
list.push({
|
|
1283
|
+
site: e.site,
|
|
1284
|
+
edit: e,
|
|
1285
|
+
ordinal: parsed.ordinal
|
|
1286
|
+
});
|
|
1287
|
+
byFile.set(parsed.file, list);
|
|
1288
|
+
}
|
|
1289
|
+
const written = [];
|
|
1290
|
+
const hashes = {};
|
|
1291
|
+
for (const [file, entries] of byFile) {
|
|
1292
|
+
const fileResults = [];
|
|
1293
|
+
const fail = (p, error, code) => fileResults.push({
|
|
1294
|
+
site: p.site,
|
|
1295
|
+
role: p.edit.role,
|
|
1296
|
+
key: p.edit.key,
|
|
1297
|
+
ok: false,
|
|
1298
|
+
error,
|
|
1299
|
+
code
|
|
1300
|
+
});
|
|
1301
|
+
const failAll = (error, code) => entries.forEach((p) => fail(p, error, code));
|
|
1302
|
+
const abs = projectFile(root, file);
|
|
1303
|
+
let code;
|
|
1304
|
+
if (!abs) failAll("File is outside the project", "io");
|
|
1305
|
+
else try {
|
|
1306
|
+
code = await promises.readFile(abs, "utf8");
|
|
1307
|
+
} catch {
|
|
1308
|
+
failAll("File not found", "io");
|
|
1309
|
+
}
|
|
1310
|
+
if (abs && code !== void 0) {
|
|
1311
|
+
const current = hashText(code);
|
|
1312
|
+
const ready = [];
|
|
1313
|
+
for (const p of entries) {
|
|
1314
|
+
const hash = p.edit.hash;
|
|
1315
|
+
if (!hash || hash === current) {
|
|
1316
|
+
ready.push(p);
|
|
1317
|
+
continue;
|
|
1318
|
+
}
|
|
1319
|
+
const old = sources.get(hash);
|
|
1320
|
+
if (!old) {
|
|
1321
|
+
fail(p, "The file changed since the page loaded; reload the page to edit it", "conflict");
|
|
1322
|
+
continue;
|
|
1323
|
+
}
|
|
1324
|
+
let moved = null;
|
|
1325
|
+
try {
|
|
1326
|
+
moved = relocate(old, code, abs, [p.ordinal]).get(p.ordinal) ?? null;
|
|
1327
|
+
} catch (err) {
|
|
1328
|
+
fail(p, `Could not parse the file: ${err.message}`, "parse");
|
|
1329
|
+
continue;
|
|
1330
|
+
}
|
|
1331
|
+
if (moved === null) {
|
|
1332
|
+
fail(p, "This call changed or was removed in the file since the page loaded", "conflict");
|
|
1333
|
+
continue;
|
|
1334
|
+
}
|
|
1335
|
+
const was = rawOf(old, abs, p.ordinal, p.edit.role, p.edit.key);
|
|
1336
|
+
const now = rawOf(code, abs, moved, p.edit.role, p.edit.key);
|
|
1337
|
+
if (was !== now) {
|
|
1338
|
+
fail(p, `Edited in the file since the page loaded (was ${was ?? "not set"}, now ${now ?? "not set"}); reload to see it`, "conflict");
|
|
1339
|
+
continue;
|
|
1340
|
+
}
|
|
1341
|
+
ready.push({
|
|
1342
|
+
...p,
|
|
1343
|
+
ordinal: moved
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
let out;
|
|
1347
|
+
if (ready.length) try {
|
|
1348
|
+
const edits = ready.map((p) => ({
|
|
1349
|
+
ordinal: p.ordinal,
|
|
1350
|
+
role: p.edit.role,
|
|
1351
|
+
key: p.edit.key,
|
|
1352
|
+
value: p.edit.value,
|
|
1353
|
+
mode: p.edit.mode
|
|
1354
|
+
}));
|
|
1355
|
+
out = applyEdits(code, abs, edits);
|
|
1356
|
+
} catch (err) {
|
|
1357
|
+
ready.forEach((p) => fail(p, `Could not parse the file: ${err.message}`, "parse"));
|
|
1358
|
+
}
|
|
1359
|
+
if (out) out.results.forEach((r, i) => {
|
|
1360
|
+
const p = ready[i];
|
|
1361
|
+
const movedTo = p.ordinal !== parseSiteId(p.site).ordinal ? `${file}#${p.ordinal}` : void 0;
|
|
1362
|
+
fileResults.push({
|
|
1363
|
+
site: p.site,
|
|
1364
|
+
role: p.edit.role,
|
|
1365
|
+
key: p.edit.key,
|
|
1366
|
+
ok: r.ok,
|
|
1367
|
+
error: r.ok ? void 0 : r.error,
|
|
1368
|
+
code: r.code,
|
|
1369
|
+
...movedTo ? { movedTo } : {}
|
|
1370
|
+
});
|
|
1371
|
+
});
|
|
1372
|
+
if (fileResults.some((r) => !r.ok)) for (const r of fileResults) {
|
|
1373
|
+
if (!r.ok) continue;
|
|
1374
|
+
r.ok = false;
|
|
1375
|
+
r.error = "Not saved: another change in this file failed";
|
|
1376
|
+
r.code = "batch";
|
|
1377
|
+
}
|
|
1378
|
+
else if (out?.changed) {
|
|
1379
|
+
const tmp = `${abs}.dopesheet-${process.pid}.tmp`;
|
|
1380
|
+
try {
|
|
1381
|
+
await promises.writeFile(tmp, out.code, "utf8");
|
|
1382
|
+
await promises.rename(tmp, abs);
|
|
1383
|
+
hashes[file] = sources.remember(out.code);
|
|
1384
|
+
written.push(file);
|
|
1385
|
+
} catch (err) {
|
|
1386
|
+
await promises.rm(tmp, { force: true });
|
|
1387
|
+
for (const r of fileResults) Object.assign(r, {
|
|
1388
|
+
ok: false,
|
|
1389
|
+
error: `Could not write the file: ${err.message}`,
|
|
1390
|
+
code: "io"
|
|
1391
|
+
});
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
results.push(...fileResults);
|
|
1396
|
+
}
|
|
1397
|
+
return {
|
|
1398
|
+
ok: results.every((r) => r.ok),
|
|
1399
|
+
results,
|
|
1400
|
+
files: written,
|
|
1401
|
+
hashes
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
/** Where calls went in files that changed since the page that made the edits was built. */
|
|
1405
|
+
async function relocateSites(root, body, sources) {
|
|
1406
|
+
const moved = {};
|
|
1407
|
+
const conflicts = {};
|
|
1408
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
1409
|
+
for (const s of body.sites ?? []) {
|
|
1410
|
+
const parsed = parseSiteId(s.site);
|
|
1411
|
+
if (!parsed) continue;
|
|
1412
|
+
const list = byFile.get(parsed.file) ?? [];
|
|
1413
|
+
list.push({
|
|
1414
|
+
...s,
|
|
1415
|
+
ordinal: parsed.ordinal
|
|
1416
|
+
});
|
|
1417
|
+
byFile.set(parsed.file, list);
|
|
1418
|
+
}
|
|
1419
|
+
for (const [file, list] of byFile) {
|
|
1420
|
+
const abs = projectFile(root, file);
|
|
1421
|
+
let code;
|
|
1422
|
+
try {
|
|
1423
|
+
code = abs ? await promises.readFile(abs, "utf8") : void 0;
|
|
1424
|
+
} catch {
|
|
1425
|
+
code = void 0;
|
|
1426
|
+
}
|
|
1427
|
+
const current = code !== void 0 ? hashText(code) : void 0;
|
|
1428
|
+
for (const s of list) {
|
|
1429
|
+
if (s.hash === current) continue;
|
|
1430
|
+
const old = sources.get(s.hash);
|
|
1431
|
+
if (code === void 0 || !old || !abs) {
|
|
1432
|
+
moved[s.site] = null;
|
|
1433
|
+
continue;
|
|
1434
|
+
}
|
|
1435
|
+
try {
|
|
1436
|
+
const to = relocate(old, code, abs, [s.ordinal]).get(s.ordinal);
|
|
1437
|
+
moved[s.site] = to === null || to === void 0 ? null : `${file}#${to}`;
|
|
1438
|
+
if (to === null || to === void 0) continue;
|
|
1439
|
+
for (const k of s.keys ?? []) {
|
|
1440
|
+
const was = rawOf(old, abs, s.ordinal, k.role, k.key);
|
|
1441
|
+
const now = rawOf(code, abs, to, k.role, k.key);
|
|
1442
|
+
if (was !== now) conflicts[`${s.site}|${k.role}|${k.key}`] = `Edited in the file since this change was made (was ${was ?? "not set"}, now ${now ?? "not set"})`;
|
|
1443
|
+
}
|
|
1444
|
+
} catch {
|
|
1445
|
+
moved[s.site] = null;
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
return {
|
|
1450
|
+
moved,
|
|
1451
|
+
conflicts
|
|
1452
|
+
};
|
|
1453
|
+
}
|
|
1454
|
+
export { instrument as a, saveEdits as i, dopesheet as n, RELOCATE_ENDPOINT as o, relocateSites as r, SAVE_ENDPOINT as s, SourceCache as t };
|