@platejs/cli 0.0.0-stage → 54.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js ADDED
@@ -0,0 +1,2053 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { closeSync, existsSync, fsyncSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import path, { basename, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
5
+ import { Command } from "commander";
6
+ import { execFile, execFileSync } from "node:child_process";
7
+ import fs from "node:fs/promises";
8
+ import { promisify } from "node:util";
9
+ import prompts from "prompts";
10
+ import { ZodError, z } from "zod";
11
+ import { detect } from "@antfu/ni";
12
+ import { cyan, green, red, yellow } from "kleur/colors";
13
+ import ora from "ora";
14
+ import { createHash, randomUUID } from "node:crypto";
15
+ import { fileURLToPath, pathToFileURL } from "node:url";
16
+ import { build, stop } from "esbuild";
17
+ import { tmpdir } from "node:os";
18
+ import { SyntaxKind, isArrayTypeNode, isIndexSignatureDeclaration, isIntersectionTypeNode, isLiteralTypeNode, isNamedTupleMember, isOptionalTypeNode, isParenthesizedTypeNode, isPropertySignatureDeclaration, isRestTypeNode, isTemplateLiteralTypeNode, isTupleTypeNode, isTypeLiteralNode, isTypeOperatorNode, isTypeReferenceNode, isUnionTypeNode } from "typescript/unstable/ast";
19
+ import { API, ElementFlags, NodeBuilderFlags, SignatureKind, SymbolFlags, TypeFlags } from "typescript/unstable/async";
20
+ import { diffEditorSchemaContracts, readEditorSchemaContract } from "platejs";
21
+ //#region src/deps/utils/get-package-manager.ts
22
+ async function getPackageManager(targetDir, { programmatic = true, withFallback = true } = {}) {
23
+ const detected = await detect({
24
+ cwd: targetDir,
25
+ programmatic
26
+ });
27
+ if (detected) {
28
+ if (detected.startsWith("yarn")) return "yarn";
29
+ if (detected.startsWith("pnpm")) return "pnpm";
30
+ if (detected === "bun") return "bun";
31
+ if (detected === "npm") return "npm";
32
+ }
33
+ if (withFallback) {
34
+ const userAgent = process.env.npm_config_user_agent || "";
35
+ if (userAgent.startsWith("yarn")) return "yarn";
36
+ if (userAgent.startsWith("pnpm")) return "pnpm";
37
+ if (userAgent.startsWith("bun")) return "bun";
38
+ }
39
+ return "npm";
40
+ }
41
+ //#endregion
42
+ //#region src/deps/utils/logger.ts
43
+ const highlighter = {
44
+ error: red,
45
+ info: cyan,
46
+ success: green,
47
+ warn: yellow
48
+ };
49
+ const logger = {
50
+ break() {
51
+ console.info("");
52
+ },
53
+ error(...args) {
54
+ console.info(highlighter.error(args.join(" ")));
55
+ },
56
+ info(...args) {
57
+ console.info(highlighter.info(args.join(" ")));
58
+ },
59
+ log(...args) {
60
+ console.info(args.join(" "));
61
+ },
62
+ success(...args) {
63
+ console.info(highlighter.success(args.join(" ")));
64
+ },
65
+ warn(...args) {
66
+ console.info(highlighter.warn(args.join(" ")));
67
+ }
68
+ };
69
+ //#endregion
70
+ //#region src/deps/utils/handle-error.ts
71
+ function handleError(error) {
72
+ logger.error("Something went wrong. Please check the error below for more details.");
73
+ if (typeof error === "string") logger.error(error);
74
+ else if (error instanceof ZodError) {
75
+ logger.error("Validation failed:");
76
+ for (const [key, value] of Object.entries(error.flatten().fieldErrors)) logger.error(`- ${highlighter.info(key)}: ${value?.join(", ") ?? ""}`);
77
+ } else if (error instanceof Error) logger.error(error.message);
78
+ logger.break();
79
+ process.exit(1);
80
+ }
81
+ //#endregion
82
+ //#region src/deps/utils/spinner.ts
83
+ function spinner(text, options) {
84
+ return ora({
85
+ isSilent: options?.silent,
86
+ text
87
+ });
88
+ }
89
+ //#endregion
90
+ //#region src/deps/index.ts
91
+ const execFilePromise = promisify(execFile);
92
+ const VERSION_PREFIX_REGEX = /^\D*/;
93
+ const PackageJsonSchema = z.object({
94
+ dependencies: z.record(z.string()).optional(),
95
+ devDependencies: z.record(z.string()).optional()
96
+ }).passthrough();
97
+ const NpmVersionsSchema = z.union([z.string(), z.array(z.string())]);
98
+ const DepSyncOptionsSchema = z.object({
99
+ packageSpecifier: z.string().min(1, "Package specifier is required."),
100
+ targetVersion: z.string().optional(),
101
+ install: z.boolean().default(false),
102
+ yes: z.boolean().default(false),
103
+ cwd: z.string().default(process.cwd()),
104
+ silent: z.boolean().default(false)
105
+ });
106
+ const CliOptionsSchema = z.object({
107
+ cwd: z.string(),
108
+ install: z.boolean(),
109
+ latest: z.boolean(),
110
+ silent: z.boolean(),
111
+ yes: z.boolean()
112
+ });
113
+ async function getPackageJson(cwd, options) {
114
+ const targetPath = path.join(cwd, "./package.json");
115
+ const sp = spinner(`Reading package.json from ${targetPath}`, { silent: options.silent })?.start();
116
+ try {
117
+ const fileContent = await fs.readFile(targetPath, "utf-8");
118
+ sp?.succeed("Successfully read package.json");
119
+ return PackageJsonSchema.parse(JSON.parse(fileContent));
120
+ } catch (error) {
121
+ sp?.fail(`Error reading package.json at ${targetPath}`);
122
+ return handleError(error);
123
+ }
124
+ }
125
+ async function fetchPackageVersion(pkg, targetVersionString) {
126
+ try {
127
+ const versionSpecifier = targetVersionString ? `${pkg}@<=${targetVersionString}` : pkg;
128
+ const { stdout } = await execFilePromise("npm", [
129
+ "view",
130
+ "--json",
131
+ "--",
132
+ versionSpecifier,
133
+ "version"
134
+ ]);
135
+ const versions = NpmVersionsSchema.parse(JSON.parse(stdout));
136
+ const latestMatchingVersion = Array.isArray(versions) ? versions.at(-1) : versions;
137
+ if (latestMatchingVersion) return latestMatchingVersion.trim();
138
+ return null;
139
+ } catch (error) {
140
+ logger.error(error instanceof Error ? error.message : String(error));
141
+ return null;
142
+ }
143
+ }
144
+ async function fetchPackageVersions(packagesToFetch, currentPackageJson, options) {
145
+ const specifierDisplay = options.packageSpecifier ? ` matching "${options.packageSpecifier}"` : "";
146
+ const fetchingMessage = options.targetVersion ? `Fetching latest package versions${specifierDisplay} (up to ${options.targetVersion})` : `Fetching latest package versions${specifierDisplay}`;
147
+ logger.info(fetchingMessage);
148
+ const sp = spinner("Fetching package versions in parallel...", { silent: options.silent })?.start();
149
+ const versionPromises = packagesToFetch.map(async (pkg) => {
150
+ const version = await fetchPackageVersion(pkg, options.targetVersion);
151
+ if (version) return [pkg, {
152
+ currentVersion: currentPackageJson.dependencies?.[pkg]?.replace(VERSION_PREFIX_REGEX, "") || currentPackageJson.devDependencies?.[pkg]?.replace(VERSION_PREFIX_REGEX, "") || "Not installed",
153
+ version
154
+ }];
155
+ return null;
156
+ });
157
+ const results = await Promise.all(versionPromises);
158
+ const versionMap = new Map(results.filter((result) => result !== null));
159
+ sp?.succeed("Finished fetching package versions.");
160
+ return versionMap;
161
+ }
162
+ function preparePackageUpdates(currentPackageJson, versionMap) {
163
+ const updatedPackages = [];
164
+ const newPackageJson = structuredClone(currentPackageJson);
165
+ for (const [name, versions] of Array.from(versionMap.entries())) {
166
+ let changed = false;
167
+ if (newPackageJson.dependencies?.[name] && newPackageJson.dependencies[name].replace(VERSION_PREFIX_REGEX, "") !== versions.version) {
168
+ newPackageJson.dependencies[name] = versions.version;
169
+ changed = true;
170
+ }
171
+ if (newPackageJson.devDependencies?.[name] && newPackageJson.devDependencies[name].replace(VERSION_PREFIX_REGEX, "") !== versions.version) {
172
+ newPackageJson.devDependencies[name] = versions.version;
173
+ changed = true;
174
+ }
175
+ if (changed) updatedPackages.push({
176
+ name,
177
+ currentVersion: versions.currentVersion,
178
+ newVersion: versions.version
179
+ });
180
+ }
181
+ return {
182
+ updatedPackages,
183
+ newPackageJsonString: JSON.stringify(newPackageJson, null, 2)
184
+ };
185
+ }
186
+ async function runSync(options) {
187
+ let mainSpinner = spinner("Starting dependency synchronization...", { silent: options.silent })?.start();
188
+ let packageFilterFn;
189
+ let matchDescription;
190
+ if (options.packageSpecifier.endsWith("*")) {
191
+ const prefix = options.packageSpecifier.slice(0, -1);
192
+ packageFilterFn = (pkgName) => pkgName.startsWith(prefix);
193
+ matchDescription = `packages starting with "${prefix}"`;
194
+ } else if (options.packageSpecifier.startsWith("@") && !options.packageSpecifier.includes("/")) {
195
+ const scopeAsExact = options.packageSpecifier;
196
+ const scopeAsPrefix = `${options.packageSpecifier}/`;
197
+ packageFilterFn = (pkgName) => pkgName.startsWith(scopeAsPrefix) || pkgName === scopeAsExact;
198
+ matchDescription = `packages in scope "${options.packageSpecifier}"`;
199
+ } else {
200
+ packageFilterFn = (pkgName) => pkgName === options.packageSpecifier;
201
+ matchDescription = `package "${options.packageSpecifier}"`;
202
+ }
203
+ logger.info(`\nSynchronizing ${matchDescription}`);
204
+ if (options.targetVersion) logger.info(`Targeting version: ${options.targetVersion}`);
205
+ logger.info(`Working directory: ${options.cwd}`);
206
+ if (!options.yes) {
207
+ mainSpinner.stop();
208
+ mainSpinner.clear();
209
+ mainSpinner = spinner("Processing packages...", { silent: options.silent })?.start();
210
+ }
211
+ const currentPackageJson = await getPackageJson(options.cwd, options);
212
+ const allDependencies = {
213
+ ...currentPackageJson.dependencies,
214
+ ...currentPackageJson.devDependencies
215
+ };
216
+ const packagesToFetch = Object.keys(allDependencies).filter(packageFilterFn);
217
+ if (packagesToFetch.length === 0) {
218
+ mainSpinner.warn(`No packages found in dependencies for ${matchDescription}.`);
219
+ if (options.packageSpecifier && !options.packageSpecifier.endsWith("*") && !options.packageSpecifier.includes("/")) logger.info(`Did you mean '${options.packageSpecifier}/*' or an exact package name like '${options.packageSpecifier}/some-package'?`);
220
+ return;
221
+ }
222
+ logger.info(`Found ${packagesToFetch.length} package${packagesToFetch.length === 1 ? "" : "s"} to check: ${packagesToFetch.join(", ")}`);
223
+ const versionMap = await fetchPackageVersions(packagesToFetch, currentPackageJson, options);
224
+ if (versionMap.size === 0 && packagesToFetch.length > 0) {
225
+ mainSpinner.warn("Could not fetch versions for any of the targeted packages.");
226
+ return;
227
+ }
228
+ const { updatedPackages, newPackageJsonString } = preparePackageUpdates(currentPackageJson, versionMap);
229
+ mainSpinner.succeed("Package analysis complete.");
230
+ if (updatedPackages.length > 0) {
231
+ logger.info("The following packages will be updated:");
232
+ updatedPackages.forEach(({ name, currentVersion, newVersion }) => {
233
+ logger.log(` ${name}: ${currentVersion} -> ${newVersion}`);
234
+ });
235
+ logger.break();
236
+ let proceed = options.yes;
237
+ if (!options.yes) {
238
+ const answer = await prompts({
239
+ type: "confirm",
240
+ name: "confirmUpdate",
241
+ message: "Apply these changes to package.json?",
242
+ initial: true
243
+ });
244
+ const { confirmUpdate } = z.object({ confirmUpdate: z.boolean().optional() }).parse(answer);
245
+ proceed = confirmUpdate === true;
246
+ }
247
+ if (proceed) {
248
+ const writeSpinner = spinner("Updating package.json...", { silent: options.silent })?.start();
249
+ try {
250
+ await fs.writeFile(path.join(options.cwd, "./package.json"), newPackageJsonString);
251
+ writeSpinner?.succeed("package.json updated successfully.");
252
+ } catch (error) {
253
+ writeSpinner?.fail("Error writing to package.json.");
254
+ handleError(error);
255
+ }
256
+ let shouldRunInstall = options.install;
257
+ if (!options.install && !options.yes) {
258
+ const answer = await prompts({
259
+ type: "confirm",
260
+ name: "confirmInstall",
261
+ message: "Run package manager install command to apply these changes?",
262
+ initial: true
263
+ });
264
+ const { confirmInstall } = z.object({ confirmInstall: z.boolean() }).parse(answer);
265
+ shouldRunInstall = z.boolean().parse(confirmInstall);
266
+ }
267
+ if (shouldRunInstall) {
268
+ const pm = await getPackageManager(options.cwd);
269
+ const installCommand = `${pm} install`;
270
+ const installSpinner = spinner(`Running \`${installCommand}\`...`, { silent: options.silent })?.start();
271
+ try {
272
+ execFileSync(pm, ["install"], {
273
+ cwd: options.cwd,
274
+ stdio: options.silent ? "pipe" : "inherit"
275
+ });
276
+ installSpinner?.succeed(`Successfully ran \`${installCommand}\``);
277
+ } catch (error) {
278
+ installSpinner?.fail(`Error running \`${installCommand}\``);
279
+ handleError(error);
280
+ }
281
+ } else if (updatedPackages.length > 0 && !options.install && options.yes) logger.info("Skipping package installation as --install was not provided with --yes.");
282
+ else if (updatedPackages.length > 0 && !shouldRunInstall) logger.info("Skipping package installation.");
283
+ } else logger.info("Changes to package.json were not applied by user.");
284
+ } else logger.success("All specified packages are already up to date.");
285
+ logger.break();
286
+ }
287
+ function registerDepsCommand(program) {
288
+ program.command("deps").description("Synchronize package dependencies to their latest or a specific version.").argument("[package-specifier]", "Package name or pattern (e.g., \"@scope/foo*\", \"my-package\", \"@myorg\")").argument("[target-version]", "Target version (e.g., \"1.2.3\") - defaults to latest if omitted").option("-i, --install", "Automatically run install after updating package.json", false).option("-y, --yes", "Skip all confirmation prompts", false).option("-c, --cwd <path>", "Set the current working directory", process.cwd()).option("-s, --silent", "Silence all output except for errors", false).option("-L, --latest", "Use the latest version, skip version prompt", false).action(async (packageSpecifierArg, targetVersionArg, rawCliOptions) => {
289
+ try {
290
+ const cliOpts = CliOptionsSchema.parse(rawCliOptions);
291
+ let pkgSpec = packageSpecifierArg;
292
+ let targetVer = targetVersionArg;
293
+ if (!pkgSpec && !cliOpts.yes) {
294
+ const response = await prompts({
295
+ type: "text",
296
+ name: "packageSpecifier",
297
+ message: "Enter the package name or pattern to synchronize:",
298
+ validate: (value) => value && value.trim().length > 0 ? true : "Package specifier cannot be empty."
299
+ });
300
+ if (!response.packageSpecifier) {
301
+ logger.warn("Package specifier is required. Exiting.");
302
+ return;
303
+ }
304
+ pkgSpec = z.string().parse(response.packageSpecifier);
305
+ } else if (!pkgSpec && cliOpts.yes) {
306
+ logger.error("Error: package-specifier is required.");
307
+ process.exit(1);
308
+ }
309
+ if (!targetVer && !cliOpts.yes && !cliOpts.latest) {
310
+ const versionResponse = await prompts({
311
+ type: "text",
312
+ name: "targetVersion",
313
+ message: "Enter the target version (e.g., \"1.2.3\", or leave blank for latest):"
314
+ });
315
+ targetVer = z.string().optional().parse(versionResponse.targetVersion || void 0);
316
+ } else if (cliOpts.latest) targetVer = void 0;
317
+ const rawOptions = {
318
+ packageSpecifier: pkgSpec,
319
+ targetVersion: targetVer,
320
+ install: cliOpts.install,
321
+ yes: cliOpts.yes,
322
+ cwd: cliOpts.cwd,
323
+ silent: cliOpts.silent
324
+ };
325
+ const options = DepSyncOptionsSchema.parse(rawOptions);
326
+ if (options.silent) {
327
+ logger.info = () => {};
328
+ logger.success = () => {};
329
+ logger.warn = () => {};
330
+ logger.log = () => {};
331
+ logger.break = () => {};
332
+ }
333
+ await runSync(options);
334
+ } catch (error) {
335
+ if (typeof rawCliOptions === "object" && rawCliOptions !== null && "silent" in rawCliOptions && rawCliOptions.silent === true) {
336
+ logger.error = console.error;
337
+ logger.break = () => {
338
+ console.info("");
339
+ };
340
+ }
341
+ handleError(error);
342
+ }
343
+ });
344
+ }
345
+ //#endregion
346
+ //#region src/esbuild.ts
347
+ const STOPPED_SERVICE_PATTERN = /The service (?:was stopped|is no longer running)/;
348
+ /**
349
+ * esbuild shares one service process per host process and never respawns it,
350
+ * so once that child dies (a test runner's timeout cleanup, the OOM killer)
351
+ * every later build would fail. Stopping resets the service so the retry
352
+ * spawns a fresh one.
353
+ */
354
+ const build$1 = async (options) => {
355
+ try {
356
+ return await build(options);
357
+ } catch (error) {
358
+ if (!(error instanceof Error && STOPPED_SERVICE_PATTERN.test(error.message))) throw error;
359
+ await stop();
360
+ return build(options);
361
+ }
362
+ };
363
+ //#endregion
364
+ //#region src/internal/failInvariant.ts
365
+ function failInvariant(message) {
366
+ throw new Error(`Invariant failed: ${message}`);
367
+ }
368
+ //#endregion
369
+ //#region src/state.ts
370
+ const stateRoots = /* @__PURE__ */ new Map();
371
+ const fingerprint = (value) => createHash("sha256").update(value).digest("hex").slice(0, 32);
372
+ const existingAncestor = (path) => {
373
+ let candidate = path;
374
+ while (!existsSync(candidate)) {
375
+ const parent = dirname(candidate);
376
+ if (parent === candidate) return candidate;
377
+ candidate = parent;
378
+ }
379
+ return candidate;
380
+ };
381
+ const findProjectRoot = (path) => {
382
+ let directory = dirname(resolve(path));
383
+ while (dirname(directory) !== directory) {
384
+ if (existsSync(join(directory, "package.json"))) return directory;
385
+ directory = dirname(directory);
386
+ }
387
+ return dirname(resolve(path));
388
+ };
389
+ const usableStateRoot = (path, device) => {
390
+ let descriptor;
391
+ const probe = join(path, `.write-${process.pid}-${randomUUID()}`);
392
+ try {
393
+ mkdirSync(path, {
394
+ mode: 448,
395
+ recursive: true
396
+ });
397
+ if (!statSync(path).isDirectory() || statSync(path).dev !== device) return;
398
+ descriptor = openSync(probe, "wx", 384);
399
+ return path;
400
+ } catch {} finally {
401
+ if (descriptor !== void 0) {
402
+ closeSync(descriptor);
403
+ rmSync(probe, { force: true });
404
+ }
405
+ }
406
+ };
407
+ /** Private durable state on the artifact filesystem, never in tracked source. */
408
+ const artifactStateRoot = (artifactPath) => {
409
+ const projectRoot = realpathSync(findProjectRoot(artifactPath));
410
+ const artifactDevice = statSync(existingAncestor(dirname(artifactPath))).dev;
411
+ const cacheKey = `${projectRoot}\0${artifactDevice}`;
412
+ const cached = stateRoots.get(cacheKey);
413
+ if (cached) return cached;
414
+ const projectCache = join(projectRoot, "node_modules", ".cache", "plate", "state");
415
+ const statePath = statSync(existingAncestor(projectCache)).dev === artifactDevice ? projectCache : void 0;
416
+ const root = statePath ? usableStateRoot(statePath, artifactDevice) : void 0;
417
+ if (!root) throw new Error(`Plate could not create private state on the generated artifact filesystem: ${artifactPath}`);
418
+ stateRoots.set(cacheKey, root);
419
+ return root;
420
+ };
421
+ /** Prefix for a private compiler directory created atomically by `mkdtemp`. */
422
+ const compilerDirectoryPrefix = (entryPath) => join(tmpdir(), `plate-compiler-${fingerprint(resolve(entryPath)).slice(0, 12)}-`);
423
+ const canonicalPath = (path) => {
424
+ const resolved = resolve(path);
425
+ if (existsSync(resolved)) return realpathSync(resolved);
426
+ const ancestor = existingAncestor(dirname(resolved));
427
+ return join(realpathSync(ancestor), resolved.slice(ancestor.length + 1));
428
+ };
429
+ const pathFingerprint = (path) => fingerprint(canonicalPath(path));
430
+ //#endregion
431
+ //#region src/typescript.ts
432
+ const NODE_MODULES_PATH_PATTERN = /(^|[\\/])node_modules([\\/]|$)/;
433
+ const PROPERTY_NAME_PATTERN$1 = /^[$A-Z_a-z][$\w]*$/;
434
+ const propertyName$1 = (name) => PROPERTY_NAME_PATTERN$1.test(name) ? name : JSON.stringify(name);
435
+ const findEditorConfig = (entryPath) => {
436
+ let directory = dirname(entryPath);
437
+ while (true) {
438
+ const candidate = join(directory, "tsconfig.json");
439
+ if (existsSync(candidate)) return candidate;
440
+ const parent = dirname(directory);
441
+ if (parent === directory) return void 0;
442
+ directory = parent;
443
+ }
444
+ };
445
+ const diagnosticText = (diagnostic) => {
446
+ const chain = diagnostic.messageChain?.map(diagnosticText).filter(Boolean);
447
+ return chain?.length ? `${diagnostic.text}\n${chain.join("\n")}` : diagnostic.text;
448
+ };
449
+ const formatDiagnostics = (diagnostics, cwd, helpers) => diagnostics.map((diagnostic) => {
450
+ const message = diagnosticText(diagnostic);
451
+ if (!diagnostic.fileName || diagnostic.pos < 0) return message;
452
+ const before = (helpers.get(resolve(diagnostic.fileName)) ?? (existsSync(diagnostic.fileName) ? readFileSync(diagnostic.fileName, "utf-8") : "")).slice(0, diagnostic.pos);
453
+ const line = before.split("\n").length;
454
+ const character = diagnostic.pos - Math.max(before.lastIndexOf("\n") + 1, 0) + 1;
455
+ return `${relative(cwd, diagnostic.fileName)}:${line}:${character} ${message}`;
456
+ }).join("\n");
457
+ const escapeTemplateLiteralText = (value) => value.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${");
458
+ const nodeName = (node) => {
459
+ if ("text" in node && typeof node.text === "string") return node.text;
460
+ };
461
+ const printedNamedTypes = /* @__PURE__ */ new WeakMap();
462
+ const printNamedType = async (checker, type, seen, excludeUndefined = false) => {
463
+ let cache = printedNamedTypes.get(checker);
464
+ if (!cache) {
465
+ cache = /* @__PURE__ */ new Map();
466
+ printedNamedTypes.set(checker, cache);
467
+ }
468
+ const key = `${type.id}:${excludeUndefined ? 1 : 0}`;
469
+ const cacheable = seen.size === 0;
470
+ const cached = cacheable ? cache.get(key) : void 0;
471
+ if (cached && !seen.has(type.id)) return cached;
472
+ if (seen.has(type.id)) return "unknown";
473
+ const nextSeen = new Set(seen).add(type.id);
474
+ try {
475
+ const printed = await (async () => {
476
+ if (type.isStringLiteralType()) return JSON.stringify(type.value);
477
+ if (type.isNumberLiteralType()) return String(type.value);
478
+ if (type.isBooleanLiteralType()) return type.value ? "true" : "false";
479
+ if (type.flags & TypeFlags.Any) return "unknown";
480
+ if (type.flags & TypeFlags.Never) throw new Error("Generated editor property types cannot contain `never`.");
481
+ if (type.flags & TypeFlags.Unknown) return "unknown";
482
+ if (type.isTemplateLiteralType()) {
483
+ const types = await type.getTypes();
484
+ return `\`${(await Promise.all(type.texts.map(async (text, index) => {
485
+ const nested = types[index];
486
+ return `${escapeTemplateLiteralText(text)}${nested ? `\${${await printNamedType(checker, nested, nextSeen)}}` : ""}`;
487
+ }))).join("")}\``;
488
+ }
489
+ if (type.flags & TypeFlags.StringLike) return "string";
490
+ if (type.flags & TypeFlags.NumberLike) return "number";
491
+ if (type.flags & TypeFlags.BigIntLike) return "bigint";
492
+ if (type.flags & TypeFlags.BooleanLike) return "boolean";
493
+ if (type.flags & TypeFlags.ESSymbolLike) return "symbol";
494
+ if (type.flags & TypeFlags.Null) return "null";
495
+ if (type.flags & (TypeFlags.Undefined | TypeFlags.Void)) return "undefined";
496
+ if (type.isUnionType()) {
497
+ const unionTypes = await type.getTypes();
498
+ const values = await Promise.all(unionTypes.filter((item) => !excludeUndefined || !(item.flags & (TypeFlags.Undefined | TypeFlags.Void))).map((item) => printNamedType(checker, item, nextSeen)));
499
+ const unique = [...new Set(values)];
500
+ if (unique.includes("unknown")) return "unknown";
501
+ if (unique.includes("false") && unique.includes("true")) {
502
+ unique.splice(unique.indexOf("false"), 1);
503
+ unique.splice(unique.indexOf("true"), 1);
504
+ unique.push("boolean");
505
+ }
506
+ return unique.sort().join(" | ") || "undefined";
507
+ }
508
+ if (type.isIntersectionType()) {
509
+ const intersectionTypes = await type.getTypes();
510
+ const values = (await Promise.all(intersectionTypes.map(async (item) => ({
511
+ item,
512
+ printed: await printNamedType(checker, item, nextSeen)
513
+ })))).flatMap(({ item, printed: innerPrinted }) => innerPrinted === "unknown" ? [] : [item.isUnionType() ? `(${innerPrinted})` : innerPrinted]);
514
+ return [...new Set(values)].join(" & ") || "unknown";
515
+ }
516
+ if (type.isTupleType()) {
517
+ const tuple = type;
518
+ const tupleTypes = await checker.getTypeArguments(tuple);
519
+ return `readonly [${(await Promise.all(tupleTypes.map(async (item, index) => {
520
+ const flag = tuple.elementFlags[index] ?? ElementFlags.Required;
521
+ const innerPrinted2 = await printNamedType(checker, item, nextSeen, Boolean(flag & ElementFlags.Optional));
522
+ if (flag & (ElementFlags.Rest | ElementFlags.Variadic)) return `...${item.isUnionType() ? `(${innerPrinted2})` : innerPrinted2}[]`;
523
+ return flag & ElementFlags.Optional ? `${innerPrinted2}?` : innerPrinted2;
524
+ }))).join(", ")}]`;
525
+ }
526
+ if (await checker.isTupleType(type)) {
527
+ const node = await checker.typeToTypeNode(type, void 0, NodeBuilderFlags.NoTruncation | NodeBuilderFlags.InTypeAlias);
528
+ if (node && isTupleTypeNode(node)) return printTypeNode(checker, node, nextSeen);
529
+ }
530
+ if (await checker.isArrayType(type)) {
531
+ const item = (await checker.getIndexInfosOfType(type)).find((index) => index.keyType.flags & TypeFlags.NumberLike)?.valueType;
532
+ return `readonly (${item ? await printNamedType(checker, item, nextSeen) : "unknown"})[]`;
533
+ }
534
+ if (type.isTypeParameter()) {
535
+ const constraint = await checker.getBaseConstraintOfType(type);
536
+ return constraint ? printNamedType(checker, constraint, nextSeen) : "unknown";
537
+ }
538
+ if ((await type.getAliasSymbol() ?? await type.getSymbol())?.declarations.some((declaration) => NODE_MODULES_PATH_PATTERN.test(declaration.path))) return "unknown";
539
+ if (!type.isObjectType()) throw new Error(`Cannot materialize editor property type "${await checker.typeToString(type)}".`);
540
+ if ((await checker.getSignaturesOfType(type, SignatureKind.Call)).length > 0) return "unknown";
541
+ const [symbols, indexInfos] = await Promise.all([checker.getPropertiesOfType(type), checker.getIndexInfosOfType(type)]);
542
+ const types = await checker.getTypeOfSymbol(symbols);
543
+ const [fields, indexFields] = await Promise.all([Promise.all(symbols.map(async (property, index) => {
544
+ const optional = (property.flags & SymbolFlags.Optional) !== 0;
545
+ const value = types[index];
546
+ return `readonly ${propertyName$1(property.name)}${optional ? "?" : ""}: ${value ? await printNamedType(checker, value, nextSeen, optional) : "unknown"};`;
547
+ })), Promise.all(indexInfos.map(async (index) => {
548
+ return `readonly [key: ${index.keyType.flags & TypeFlags.NumberLike ? "number" : "string"}]: ${await printNamedType(checker, index.valueType, nextSeen)};`;
549
+ }))]);
550
+ return `{ ${[...fields, ...indexFields].join(" ")} }`;
551
+ })();
552
+ if (cacheable) cache.set(key, printed);
553
+ return printed;
554
+ } catch (error) {
555
+ cache.delete(key);
556
+ throw error;
557
+ }
558
+ };
559
+ const printTypeNode = async (checker, node, seen, excludeUndefined = false) => {
560
+ switch (node.kind) {
561
+ case SyntaxKind.AnyKeyword:
562
+ case SyntaxKind.ObjectKeyword:
563
+ case SyntaxKind.UnknownKeyword: return "unknown";
564
+ case SyntaxKind.BigIntKeyword: return "bigint";
565
+ case SyntaxKind.BooleanKeyword: return "boolean";
566
+ case SyntaxKind.NeverKeyword: throw new Error("Generated editor property types cannot contain `never`.");
567
+ case SyntaxKind.NumberKeyword: return "number";
568
+ case SyntaxKind.StringKeyword: return "string";
569
+ case SyntaxKind.SymbolKeyword: return "symbol";
570
+ case SyntaxKind.UndefinedKeyword:
571
+ case SyntaxKind.VoidKeyword: return "undefined";
572
+ default: break;
573
+ }
574
+ if (isLiteralTypeNode(node)) {
575
+ const value = node.literal;
576
+ if (value.kind === SyntaxKind.NullKeyword) return "null";
577
+ if (value.kind === SyntaxKind.TrueKeyword) return "true";
578
+ if (value.kind === SyntaxKind.FalseKeyword) return "false";
579
+ if (value.kind === SyntaxKind.StringLiteral) return JSON.stringify(nodeName(value) ?? "");
580
+ if (value.kind === SyntaxKind.NumericLiteral || value.kind === SyntaxKind.BigIntLiteral) return nodeName(value) ?? "unknown";
581
+ return "unknown";
582
+ }
583
+ if (isUnionTypeNode(node)) {
584
+ const values = [...new Set(node.types.filter((item) => !excludeUndefined || item.kind !== SyntaxKind.UndefinedKeyword).map((item) => item))];
585
+ const printed = [];
586
+ for (const item of values) printed.push(await printTypeNode(checker, item, seen));
587
+ const unique = [...new Set(printed)];
588
+ if (unique.includes("unknown")) return "unknown";
589
+ if (unique.includes("false") && unique.includes("true")) {
590
+ unique.splice(unique.indexOf("false"), 1);
591
+ unique.splice(unique.indexOf("true"), 1);
592
+ unique.push("boolean");
593
+ }
594
+ return unique.sort().join(" | ") || "undefined";
595
+ }
596
+ if (isIntersectionTypeNode(node)) {
597
+ const printed = [];
598
+ for (const item of node.types) {
599
+ const value = await printTypeNode(checker, item, seen);
600
+ if (value !== "unknown") printed.push(isUnionTypeNode(item) ? `(${value})` : value);
601
+ }
602
+ return [...new Set(printed)].join(" & ") || "unknown";
603
+ }
604
+ if (isParenthesizedTypeNode(node)) return printTypeNode(checker, node.type, seen);
605
+ if (isTypeOperatorNode(node)) return printTypeNode(checker, node.type, seen);
606
+ if (isArrayTypeNode(node)) return `readonly (${await printTypeNode(checker, node.elementType, seen)})[]`;
607
+ if (isTupleTypeNode(node)) {
608
+ const values = [];
609
+ for (const element of node.elements) if (isNamedTupleMember(element)) {
610
+ const printed = await printTypeNode(checker, element.type, seen, Boolean(element.questionToken));
611
+ if (element.dotDotDotToken) values.push(isArrayTypeNode(element.type) ? `...${await printTypeNode(checker, element.type.elementType, seen)}[]` : `...${printed}`);
612
+ else values.push(element.questionToken ? `${printed}?` : printed);
613
+ } else if (isRestTypeNode(element)) {
614
+ const printed = await printTypeNode(checker, element.type, seen);
615
+ values.push(isArrayTypeNode(element.type) ? `...${await printTypeNode(checker, element.type.elementType, seen)}[]` : `...${printed}`);
616
+ } else if (isOptionalTypeNode(element)) values.push(`${await printTypeNode(checker, element.type, seen, true)}?`);
617
+ else values.push(await printTypeNode(checker, element, seen));
618
+ return `readonly [${values.join(", ")}]`;
619
+ }
620
+ if (isTemplateLiteralTypeNode(node)) {
621
+ const spans = [];
622
+ for (const span of node.templateSpans) spans.push(`\${${await printTypeNode(checker, span.type, seen)}}${escapeTemplateLiteralText(span.literal.text)}`);
623
+ return `\`${escapeTemplateLiteralText(node.head.text)}${spans.join("")}\``;
624
+ }
625
+ if (isTypeLiteralNode(node)) {
626
+ const fields = [];
627
+ for (const member of node.members) if (isPropertySignatureDeclaration(member)) {
628
+ const name = nodeName(member.name);
629
+ if (!name) return "unknown";
630
+ const optional = member.postfixToken?.kind === SyntaxKind.QuestionToken;
631
+ fields.push(`readonly ${propertyName$1(name)}${optional ? "?" : ""}: ${await printTypeNode(checker, member.type, seen, optional)};`);
632
+ } else if (isIndexSignatureDeclaration(member)) {
633
+ const key = (member.parameters[0]?.type)?.kind === SyntaxKind.NumberKeyword ? "number" : "string";
634
+ fields.push(`readonly [key: ${key}]: ${await printTypeNode(checker, member.type, seen)};`);
635
+ } else return "unknown";
636
+ return `{ ${fields.join(" ")} }`;
637
+ }
638
+ if (isTypeReferenceNode(node)) {
639
+ const type = await checker.getTypeFromTypeNode(node);
640
+ return type ? printNamedType(checker, type, seen, excludeUndefined) : "unknown";
641
+ }
642
+ return "unknown";
643
+ };
644
+ const printedPropertyTypes = /* @__PURE__ */ new WeakMap();
645
+ const printRootPropertyType = async (checker, type, excludeUndefined) => {
646
+ let cache = printedPropertyTypes.get(checker);
647
+ if (!cache) {
648
+ cache = /* @__PURE__ */ new Map();
649
+ printedPropertyTypes.set(checker, cache);
650
+ }
651
+ const key = `${type.id}:${excludeUndefined ? 1 : 0}`;
652
+ const cached = cache.get(key);
653
+ if (cached) return cached;
654
+ try {
655
+ const printed = await printNamedType(checker, type, /* @__PURE__ */ new Set(), excludeUndefined);
656
+ cache.set(key, printed);
657
+ return printed;
658
+ } catch (error) {
659
+ cache.delete(key);
660
+ throw error;
661
+ }
662
+ };
663
+ const readTypePropertiesCache = /* @__PURE__ */ new WeakMap();
664
+ const readTypeProperties = async (checker, type, propertyNames) => {
665
+ if (propertyNames?.length === 0) return Object.freeze({});
666
+ let cache = readTypePropertiesCache.get(checker);
667
+ if (!cache) {
668
+ cache = /* @__PURE__ */ new Map();
669
+ readTypePropertiesCache.set(checker, cache);
670
+ }
671
+ const key = `${type.id}:${JSON.stringify(propertyNames ?? null)}`;
672
+ const cached = cache.get(key);
673
+ if (cached) return cached;
674
+ const reading = (async () => {
675
+ const propertyNameSet = propertyNames ? new Set(propertyNames) : void 0;
676
+ const symbols = (await checker.getPropertiesOfType(type)).filter((symbol) => !propertyNameSet || propertyNameSet.has(symbol.name));
677
+ const types = await checker.getTypeOfSymbol(symbols);
678
+ const entries = await Promise.all(symbols.map(async (symbol, index) => {
679
+ const optional = (symbol.flags & SymbolFlags.Optional) !== 0;
680
+ const value = types[index];
681
+ let printed = "unknown";
682
+ try {
683
+ if (value) printed = await printRootPropertyType(checker, value, optional);
684
+ } catch (error) {
685
+ throw new Error(`Cannot materialize schema property "${symbol.name}": ${error instanceof Error ? error.message : String(error)}`, { cause: error });
686
+ }
687
+ return [symbol.name, Object.freeze({
688
+ optional,
689
+ type: printed
690
+ })];
691
+ }));
692
+ return Object.freeze(Object.fromEntries(entries));
693
+ })();
694
+ cache.set(key, reading);
695
+ try {
696
+ return await reading;
697
+ } catch (error) {
698
+ cache.delete(key);
699
+ throw error;
700
+ }
701
+ };
702
+ const projectForHelper = async (snapshot, helperPath, configPath) => (configPath ? snapshot.getProject(configPath) : void 0) ?? await snapshot.getDefaultProjectForFile(helperPath);
703
+ var NativeTypeScriptSession = class {
704
+ #api;
705
+ #cwd;
706
+ #helperPathByEntry = /* @__PURE__ */ new Map();
707
+ #helperSources = /* @__PURE__ */ new Map();
708
+ #snapshot;
709
+ constructor(cwd) {
710
+ this.#cwd = resolve(cwd);
711
+ this.#api = new API({
712
+ cwd: this.#cwd,
713
+ fs: {
714
+ getAccessibleEntries: (directoryName) => {
715
+ const directory = resolve(directoryName);
716
+ const virtualFiles = [...this.#helperSources.keys()].filter((path) => dirname(path) === directory);
717
+ if (virtualFiles.length === 0) return void 0;
718
+ const entries = readdirSync(directory, { withFileTypes: true });
719
+ return {
720
+ directories: entries.filter((entry) => entry.isDirectory()).map(({ name }) => name),
721
+ files: [.../* @__PURE__ */ new Set([...entries.filter((entry) => entry.isFile()).map(({ name }) => name), ...virtualFiles.map((path) => basename(path))])]
722
+ };
723
+ },
724
+ fileExists: (path) => this.#helperSources.has(resolve(path)) ? true : void 0,
725
+ readFile: (path) => this.#helperSources.get(resolve(path))
726
+ }
727
+ });
728
+ }
729
+ discardHelpers(paths) {
730
+ paths.forEach((path) => {
731
+ const resolvedPath = resolve(path);
732
+ this.#helperSources.delete(resolvedPath);
733
+ });
734
+ }
735
+ helperPath(entryPath) {
736
+ const resolvedEntryPath = resolve(entryPath);
737
+ const existing = this.#helperPathByEntry.get(resolvedEntryPath);
738
+ if (existing) return existing;
739
+ const path = join(dirname(resolvedEntryPath), `__editor_schema_${process.pid}_${randomUUID()}.ts`);
740
+ this.#helperPathByEntry.set(resolvedEntryPath, path);
741
+ return path;
742
+ }
743
+ async materialize(helpers) {
744
+ const configs = helpers.map(({ path }) => findEditorConfig(path));
745
+ const helperSources = new Map(helpers.map(({ path, source }) => [resolve(path), source]));
746
+ const createdHelpers = [...helperSources.keys()].filter((path) => !this.#helperSources.has(path));
747
+ const deletedHelpers = [...this.#helperSources.keys()].filter((path) => !helperSources.has(path));
748
+ const changedHelpers = [...helperSources].flatMap(([path, source]) => this.#helperSources.get(path) !== source && this.#helperSources.has(path) ? [path] : []);
749
+ const previousSnapshot = this.#snapshot;
750
+ const previousHelperSources = this.#helperSources;
751
+ let nextSnapshot;
752
+ this.#helperSources = helperSources;
753
+ try {
754
+ nextSnapshot = await this.#api.updateSnapshot({
755
+ ...changedHelpers.length > 0 || createdHelpers.length > 0 || deletedHelpers.length > 0 ? { fileChanges: {
756
+ ...changedHelpers.length > 0 ? { changed: changedHelpers } : {},
757
+ ...createdHelpers.length > 0 ? { created: createdHelpers } : {},
758
+ ...deletedHelpers.length > 0 ? { deleted: deletedHelpers } : {}
759
+ } } : {},
760
+ openFiles: helpers.map(({ path }) => path),
761
+ openProjects: [...new Set(configs.filter((path) => Boolean(path)))]
762
+ });
763
+ } catch (error) {
764
+ this.#helperSources = previousHelperSources;
765
+ throw error;
766
+ }
767
+ this.#snapshot = nextSnapshot;
768
+ if (previousSnapshot) await previousSnapshot.dispose();
769
+ const projects = /* @__PURE__ */ new Map();
770
+ const projectEntries = [];
771
+ for (const [helperIndex, helper] of helpers.entries()) {
772
+ const configPath = configs[helperIndex];
773
+ const projectKey = configPath ?? helper.path;
774
+ let project = projects.get(projectKey);
775
+ if (!projects.has(projectKey)) {
776
+ project = await projectForHelper(nextSnapshot, helper.path, configPath);
777
+ projects.set(projectKey, project);
778
+ }
779
+ if (!project) throw new Error(`Plate could not open a TypeScript project for "${helper.path}".`);
780
+ projectEntries.push({
781
+ helper,
782
+ project,
783
+ projectKey
784
+ });
785
+ }
786
+ const configDiagnosticsByProject = /* @__PURE__ */ new Map();
787
+ const results = await Promise.all(projectEntries.map(async ({ helper, project, projectKey }) => {
788
+ let configDiagnostics = configDiagnosticsByProject.get(projectKey);
789
+ if (!configDiagnostics) {
790
+ configDiagnostics = project.program.getConfigFileParsingDiagnostics();
791
+ configDiagnosticsByProject.set(projectKey, configDiagnostics);
792
+ }
793
+ const [config, syntactic, semantic, types] = await Promise.all([
794
+ configDiagnostics,
795
+ project.program.getSyntacticDiagnostics(helper.path),
796
+ project.program.getSemanticDiagnostics(helper.path),
797
+ project.checker.getTypeAtPosition(helper.path, helper.aliases.map(({ position }) => position))
798
+ ]);
799
+ const diagnostics = [
800
+ ...config,
801
+ ...syntactic,
802
+ ...semantic
803
+ ];
804
+ if (diagnostics.length > 0) throw new Error(formatDiagnostics(diagnostics, this.#cwd, helperSources));
805
+ const propertyEntries = await Promise.all(helper.aliases.map(async (alias, index) => {
806
+ const type = types[index];
807
+ if (!type) throw new Error(`Missing generated type helper for "${alias.name}".`);
808
+ if (type.isErrorType()) throw new Error(`Cannot resolve generated type helper "${alias.name}" in ${project.configFileName}: ${await project.checker.typeToString(type)}`);
809
+ try {
810
+ return [alias.name, await readTypeProperties(project.checker, type, alias.propertyNames)];
811
+ } catch (error) {
812
+ throw new Error(`Cannot materialize schema property "${alias.name}": ${error instanceof Error ? error.message : String(error)}`, { cause: error });
813
+ }
814
+ }));
815
+ return Object.freeze({ properties: Object.freeze(Object.fromEntries(propertyEntries)) });
816
+ }));
817
+ return Object.freeze(results);
818
+ }
819
+ async close() {
820
+ try {
821
+ if (this.#snapshot) await this.#snapshot.dispose();
822
+ } finally {
823
+ this.#snapshot = void 0;
824
+ try {
825
+ this.#helperPathByEntry.clear();
826
+ this.#helperSources.clear();
827
+ } finally {
828
+ await this.#api.close();
829
+ }
830
+ }
831
+ }
832
+ };
833
+ //#endregion
834
+ //#region src/generate.ts
835
+ const ANY_PATH_PATTERN = /.*/;
836
+ const CAMEL_BOUNDARY_PATTERN = /([a-z\d])([A-Z])/g;
837
+ const CSS_PATH_PATTERN = /\.css$/;
838
+ const EDITOR_ENTRY_PATTERN = /^plate:editor$/;
839
+ const LEADING_DIGIT_PATTERN = /^\d/;
840
+ const NON_IDENTIFIER_PATTERN = /[^A-Z_a-z\d]+/;
841
+ const PROPERTY_NAME_PATTERN = /^[$A-Z_a-z][$\w]*$/;
842
+ const PORTABLE_SHELL_PATH_PATTERN = /^[./A-Z_a-z\d-]+$/;
843
+ const SHELL_EXPANSION_PATTERN = /["$`%!\r\n]/;
844
+ const REACT_LITE_YOUTUBE_EMBED_PATTERN = /^react-lite-youtube-embed$/;
845
+ const SOURCE_EXTENSION_PATTERN = /\.[cm]?[jt]sx?$/;
846
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
847
+ const bundleEditor = (entryPath) => {
848
+ const configPath = findEditorConfig(entryPath);
849
+ return build$1({
850
+ banner: { js: `import { createRequire as __plateCreateRequire } from 'node:module'; const __plateEntryUrl = ${JSON.stringify(pathToFileURL(entryPath).href)}; const require = __plateCreateRequire(__plateEntryUrl); const __plateImportMetaResolve = (specifier) => import.meta.resolve(specifier, __plateEntryUrl);` },
851
+ bundle: true,
852
+ conditions: ["production"],
853
+ define: {
854
+ "import.meta.dirname": JSON.stringify(dirname(entryPath)),
855
+ "import.meta.filename": JSON.stringify(entryPath),
856
+ "import.meta.resolve": "__plateImportMetaResolve",
857
+ "import.meta.url": JSON.stringify(pathToFileURL(entryPath).href)
858
+ },
859
+ format: "esm",
860
+ jsx: "automatic",
861
+ logLevel: "info",
862
+ logOverride: { "ignored-bare-import": "silent" },
863
+ platform: "node",
864
+ plugins: [
865
+ {
866
+ name: "plate-editor-entry",
867
+ setup(context) {
868
+ context.onResolve({ filter: EDITOR_ENTRY_PATTERN }, () => ({ path: entryPath }));
869
+ }
870
+ },
871
+ {
872
+ name: "plate-empty-styles",
873
+ setup(context) {
874
+ context.onResolve({ filter: CSS_PATH_PATTERN }, ({ path }) => ({
875
+ namespace: "plate-empty-style",
876
+ path
877
+ }));
878
+ context.onLoad({
879
+ filter: ANY_PATH_PATTERN,
880
+ namespace: "plate-empty-style"
881
+ }, () => ({
882
+ contents: "export default {};",
883
+ loader: "js"
884
+ }));
885
+ }
886
+ },
887
+ {
888
+ name: "plate-codegen-runtime-stubs",
889
+ setup(context) {
890
+ context.onResolve({ filter: REACT_LITE_YOUTUBE_EMBED_PATTERN }, ({ path }) => ({
891
+ namespace: "plate-codegen-runtime-stub",
892
+ path
893
+ }));
894
+ context.onLoad({
895
+ filter: ANY_PATH_PATTERN,
896
+ namespace: "plate-codegen-runtime-stub"
897
+ }, () => ({
898
+ contents: "export default function PlateCodegenRuntimeStub() { return null; }",
899
+ loader: "js"
900
+ }));
901
+ }
902
+ }
903
+ ],
904
+ sourcemap: false,
905
+ stdin: {
906
+ contents: `import * as editorModule from 'plate:editor';
907
+ import { compileEditor } from 'platejs/compiler';
908
+ import { isNominalPluginDescriptor } from 'platejs';
909
+
910
+ const entryLabel = ${JSON.stringify(`Plate editor entry "${entryPath}"`)};
911
+ const exports = Object.entries(editorModule);
912
+ const formatCandidates = (candidates) =>
913
+ candidates.length === 0
914
+ ? ''
915
+ : ' candidates (' + candidates.map(([name]) => name).join(', ') + ')';
916
+ const pluginCandidates = exports.filter(([, value]) =>
917
+ Array.isArray(value) &&
918
+ value.length > 0 &&
919
+ value.every(isNominalPluginDescriptor)
920
+ );
921
+
922
+ if (pluginCandidates.length !== 1) {
923
+ throw new TypeError(
924
+ entryLabel +
925
+ ' must export exactly one Plate plugin tuple; found ' +
926
+ pluginCandidates.length +
927
+ formatCandidates(pluginCandidates) +
928
+ '.'
929
+ );
930
+ }
931
+ const [pluginExportName, plugins] = pluginCandidates[0];
932
+ const schemaFields = new Set(['id', 'overrides', 'properties', 'root', 'version']);
933
+ const isRecord = (value) =>
934
+ typeof value === 'object' && value !== null && !Array.isArray(value);
935
+ const looksLikeApplicationSchema = (value) => {
936
+ if (!isRecord(value)) return false;
937
+ const keys = Object.keys(value);
938
+
939
+ if (
940
+ keys.length === 0 ||
941
+ keys.some((key) => !schemaFields.has(key)) ||
942
+ ((value.id === undefined) !== (value.version === undefined)) ||
943
+ (value.id !== undefined &&
944
+ (typeof value.id !== 'string' ||
945
+ value.id.length === 0 ||
946
+ typeof value.version !== 'number')) ||
947
+ (value.overrides !== undefined && !Array.isArray(value.overrides)) ||
948
+ (value.properties !== undefined &&
949
+ (!isRecord(value.properties) ||
950
+ Object.values(value.properties).some(
951
+ (property) => !isRecord(property)
952
+ )))
953
+ ) {
954
+ return false;
955
+ }
956
+
957
+ return true;
958
+ };
959
+ const schemaCandidates = exports.filter(([, value]) =>
960
+ looksLikeApplicationSchema(value)
961
+ );
962
+
963
+ if (schemaCandidates.length > 1) {
964
+ throw new TypeError(
965
+ entryLabel +
966
+ ' must export at most one Plate application schema; found ' +
967
+ schemaCandidates.length +
968
+ formatCandidates(schemaCandidates) +
969
+ '.'
970
+ );
971
+ }
972
+ const applicationSchema = schemaCandidates[0]?.[1];
973
+ const { bindings, schema } = compileEditor({ plugins, schema: applicationSchema });
974
+
975
+ export default {
976
+ applicationName: applicationSchema?.id ?? 'editor',
977
+ applicationProperties: Object.entries(applicationSchema?.properties ?? {}).map(
978
+ ([localId, property]) => ({
979
+ key: property.key ?? localId,
980
+ localId,
981
+ })
982
+ ),
983
+ bindings,
984
+ pluginExportName,
985
+ schema,
986
+ };
987
+ `,
988
+ loader: "ts",
989
+ resolveDir: dirname(entryPath),
990
+ sourcefile: "plate-codegen-entry.ts"
991
+ },
992
+ tsconfig: configPath,
993
+ write: false
994
+ });
995
+ };
996
+ const evaluationWorkerPath = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./evaluation-worker.ts" : "./evaluation-worker.js", import.meta.url));
997
+ const evaluateEditor = (bundlePath, resultPath, cwd) => new Promise((resolvePromise, reject) => {
998
+ execFile(process.execPath, [
999
+ "--experimental-import-meta-resolve",
1000
+ evaluationWorkerPath,
1001
+ bundlePath,
1002
+ resultPath
1003
+ ], {
1004
+ cwd,
1005
+ maxBuffer: 16 * 1024 * 1024
1006
+ }, (error, _stdout, stderr) => {
1007
+ if (!error) {
1008
+ resolvePromise();
1009
+ return;
1010
+ }
1011
+ reject(new Error(stderr.trim() || `Plate could not evaluate the bundled editor entry: ${error.message}`));
1012
+ });
1013
+ });
1014
+ const readEditor = async (entryPath, cwd) => {
1015
+ const output = (await bundleEditor(entryPath)).outputFiles?.[0];
1016
+ if (!output) throw new Error(`Plate could not bundle "${entryPath}".`);
1017
+ const outputDirectory = mkdtempSync(compilerDirectoryPrefix(entryPath));
1018
+ const outputPath = join(outputDirectory, "editor.mjs");
1019
+ const resultPath = join(outputDirectory, "editor.json");
1020
+ let imported;
1021
+ try {
1022
+ writeDurableFile(outputPath, output.text);
1023
+ await evaluateEditor(outputPath, resultPath, cwd);
1024
+ imported = JSON.parse(readFileSync(resultPath, "utf-8"));
1025
+ } finally {
1026
+ rmSync(outputDirectory, {
1027
+ force: true,
1028
+ recursive: true
1029
+ });
1030
+ }
1031
+ if (!isRecord(imported) || typeof imported.applicationName !== "string" || imported.applicationName.length === 0 || !Array.isArray(imported.bindings) || !Array.isArray(imported.applicationProperties) || typeof imported.pluginExportName !== "string" || imported.pluginExportName.length === 0 || !isRecord(imported.schema)) throw new Error(`Plate editor entry "${entryPath}" did not produce a valid compiled editor contract.`);
1032
+ return imported;
1033
+ };
1034
+ const propertyName = (name) => PROPERTY_NAME_PATTERN.test(name) ? name : JSON.stringify(name);
1035
+ const materializePropertyGroups = async (requests, cwd, existingSession) => {
1036
+ const session = existingSession ?? new NativeTypeScriptSession(cwd);
1037
+ const ownsSession = !existingSession;
1038
+ const helperPaths = [];
1039
+ let prepared;
1040
+ try {
1041
+ prepared = requests.map(({ bindings, entryPath, owners, pluginExportName, schema }) => {
1042
+ const helperPath = session.helperPath(entryPath);
1043
+ helperPaths.push(helperPath);
1044
+ const relativeEntry = relative(dirname(helperPath), entryPath.slice(0, -extname(entryPath).length)).replaceAll("\\", "/");
1045
+ const entryImport = relativeEntry.startsWith(".") ? relativeEntry : `./${relativeEntry}`;
1046
+ const bindingByType = new Map(bindings.map((binding) => [binding.type, binding]));
1047
+ const groupMap = /* @__PURE__ */ new Map();
1048
+ schema.properties.byId.forEach((property) => {
1049
+ if (typeof property.key !== "string" || property.descriptor.kind !== "json") return;
1050
+ let groupKey = "text";
1051
+ let aliasName = "__PlateText";
1052
+ let source = "__PlateProperties[\"text\"]";
1053
+ if (property.placement === "element") {
1054
+ const element = schema.properties.byId.some((candidate) => candidate.id !== property.id && candidate.owner === property.owner && candidate.key === property.key) ? schema.elements.byType.find(({ propertyIds }) => propertyIds.includes(property.id)) : void 0;
1055
+ const binding = element ? bindingByType.get(element.type) : void 0;
1056
+ if (binding) {
1057
+ const bindingIndex = bindings.indexOf(binding);
1058
+ groupKey = `element:${binding.name}`;
1059
+ aliasName = `__PlateElement${bindingIndex}`;
1060
+ source = `__PlateProperties["elements"][${JSON.stringify(binding.name)}]`;
1061
+ } else {
1062
+ groupKey = `owner:${property.owner}`;
1063
+ aliasName = `__PlateOwner${owners.indexOf(property.owner)}`;
1064
+ source = `__PlateOwnerProperties<${JSON.stringify(property.owner)}>`;
1065
+ }
1066
+ }
1067
+ const group = groupMap.get(groupKey) ?? {
1068
+ aliasName,
1069
+ properties: [],
1070
+ source
1071
+ };
1072
+ group.properties.push({
1073
+ key: property.key,
1074
+ propertyId: property.id
1075
+ });
1076
+ groupMap.set(groupKey, group);
1077
+ });
1078
+ const groups = [...groupMap.values()];
1079
+ const aliases = groups.map(({ aliasName, source }) => `type ${aliasName} = ${source};`).join("\n");
1080
+ const aliasSource = `type __PlatePlugins = (typeof EditorModule)[${JSON.stringify(pluginExportName)}];\ntype __PlateProperties = EditorPropertyTypes<__PlatePlugins>;\ntype __PlateOwnerProperties<N extends string> = N extends keyof __PlateProperties["owners"] ? __PlateProperties["owners"][N] : Readonly<Record<never, never>>;\n${aliases}\n`;
1081
+ const helper = `import type * as EditorModule from ${JSON.stringify(entryImport)};\nimport type { EditorPropertyTypes } from 'platejs/compiler';\n${aliasSource}\n`;
1082
+ return {
1083
+ groups,
1084
+ helper,
1085
+ helperPath,
1086
+ nativeAliases: groups.map(({ aliasName, properties }) => ({
1087
+ name: aliasName,
1088
+ position: helper.indexOf(`type ${aliasName} =`) + 5,
1089
+ propertyNames: properties.map(({ key }) => key)
1090
+ }))
1091
+ };
1092
+ });
1093
+ } catch (error) {
1094
+ session.discardHelpers(helperPaths);
1095
+ if (ownsSession) await session.close();
1096
+ throw error;
1097
+ }
1098
+ try {
1099
+ return (await session.materialize(prepared.map(({ helper, helperPath, nativeAliases }) => ({
1100
+ aliases: nativeAliases,
1101
+ path: helperPath,
1102
+ source: helper
1103
+ })))).map(({ properties }, index) => {
1104
+ const request = prepared[index];
1105
+ return Object.freeze({ byPropertyId: Object.freeze(Object.fromEntries(request.groups.flatMap((group) => group.properties.map(({ key, propertyId }) => [propertyId, properties[group.aliasName][key]])))) });
1106
+ });
1107
+ } finally {
1108
+ if (ownsSession) await session.close();
1109
+ }
1110
+ };
1111
+ const toPascalCase = (value) => {
1112
+ const result = value.replace(CAMEL_BOUNDARY_PATTERN, "$1 $2").split(NON_IDENTIFIER_PATTERN).filter(Boolean).map((part) => `${part[0].toUpperCase()}${part.slice(1)}`).join("");
1113
+ return LEADING_DIGIT_PATTERN.test(result) ? `Node${result}` : result || "Node";
1114
+ };
1115
+ const createBindings = (compiledBindings, schema) => {
1116
+ const names = new Map(compiledBindings.flatMap(({ name, type }) => type ? [[type, name]] : []));
1117
+ const used = /* @__PURE__ */ new Map([["EditorElement", 1]]);
1118
+ return schema.elements.byType.map(({ type }) => {
1119
+ const name = names.get(type);
1120
+ if (!name) throw new Error(`Compiled element type "${type}" has no Plate plugin owner.`);
1121
+ const base = `${toPascalCase(name)}Element`;
1122
+ const count = used.get(base) ?? 0;
1123
+ used.set(base, count + 1);
1124
+ return Object.freeze({
1125
+ name,
1126
+ type,
1127
+ typeName: count === 0 ? base : `${base}${count + 1}`
1128
+ });
1129
+ });
1130
+ };
1131
+ const renderProperties = (properties, indent) => Object.entries(properties).sort(([left], [right]) => left.localeCompare(right)).map(([name, value]) => `${indent}readonly ${propertyName(name)}${value.optional ? "?" : ""}: ${value.type};`).join("\n");
1132
+ const renderExactReadonlyRecord = (fields, closingIndent = "") => fields ? `Readonly<{\n${fields}\n${closingIndent}}>` : "Readonly<Record<PropertyKey, never>>";
1133
+ const propertyTypeFromContract = (descriptor) => {
1134
+ let type;
1135
+ switch (descriptor.kind) {
1136
+ case "boolean":
1137
+ type = "boolean";
1138
+ break;
1139
+ case "enum":
1140
+ type = descriptor.values?.map((value) => JSON.stringify(value)).join(" | ") || "string";
1141
+ break;
1142
+ case "number":
1143
+ type = "number";
1144
+ break;
1145
+ case "set":
1146
+ type = `readonly (${descriptor.item ? propertyTypeFromContract(descriptor.item).type : "unknown"})[]`;
1147
+ break;
1148
+ case "string":
1149
+ type = "string";
1150
+ break;
1151
+ default: type = "unknown";
1152
+ }
1153
+ return Object.freeze({
1154
+ optional: !descriptor.required,
1155
+ type
1156
+ });
1157
+ };
1158
+ const childUnion = (program, bindingByType, textName) => {
1159
+ const children = program.allowedElementTypes.map((type) => {
1160
+ return bindingByType.get(type)?.typeName ?? "Element";
1161
+ });
1162
+ if (program.allowsUnknownElements) children.push("Element");
1163
+ if (program.allowsText) children.push(textName);
1164
+ return [...new Set(children)].join(" | ") || "never";
1165
+ };
1166
+ const childrenType = (program, bindingByType, textName) => {
1167
+ if (!program) return "readonly []";
1168
+ const child = childUnion(program, bindingByType, textName);
1169
+ if (program.max === 1 && program.min === 1) return `readonly [${child}]`;
1170
+ if (program.max === 1 && program.min === 0) return `readonly [] | readonly [${child}]`;
1171
+ return `readonly (${child})[]`;
1172
+ };
1173
+ const relativeImport = (fromPath, toPath) => {
1174
+ const value = relative(dirname(fromPath), toPath).replaceAll("\\", "/").replace(SOURCE_EXTENSION_PATTERN, "");
1175
+ return value.startsWith(".") ? value : `./${value}`;
1176
+ };
1177
+ const portableShellArgument = (value) => {
1178
+ if (SHELL_EXPANSION_PATTERN.test(value)) return void 0;
1179
+ return PORTABLE_SHELL_PATH_PATTERN.test(value) ? value : `"${value}"`;
1180
+ };
1181
+ const generatedHeader = (entryPath) => {
1182
+ const packageRoot = findProjectRoot(entryPath);
1183
+ const configPath = findEditorConfig(entryPath);
1184
+ const source = relative(existsSync(join(packageRoot, "package.json")) ? packageRoot : configPath ? dirname(configPath) : dirname(entryPath), entryPath).replaceAll("\\", "/");
1185
+ const commentSource = JSON.stringify(source).slice(1, -1).replaceAll("*/", "*\\/");
1186
+ const argument = portableShellArgument(source);
1187
+ const command = source === "src/editor.ts" ? "pnpm exec plate generate" : argument ? `pnpm exec plate generate -- ${argument}` : void 0;
1188
+ return `/* Generated by @platejs/cli from ${commentSource}.\n * ${command ? `Regenerate with: ${command}` : "Regenerate with @platejs/cli using the source path above."}\n * Do not edit.\n */`;
1189
+ };
1190
+ const renderGeneratedTypes = (entryPath, typesPath, pluginExportName, schema, bindings, properties, compiledBindings, applicationProperties, applicationName) => {
1191
+ const bindingByType = new Map(bindings.map((binding) => [binding.type, binding]));
1192
+ const elementByType = new Map(schema.elements.byType.map((element) => [element.type, element]));
1193
+ const compiledBindingByName = new Map(compiledBindings.map((binding) => [binding.name, binding]));
1194
+ const propertyById = new Map(schema.properties.byId.map((property) => [property.id, property]));
1195
+ const getProperty = (propertyId) => {
1196
+ const property = propertyById.get(propertyId);
1197
+ if (!property) throw new Error(`Generated property binding "${propertyId}" does not exist in the compiled schema.`);
1198
+ return property;
1199
+ };
1200
+ const renderPropertyKeyType = (key) => typeof key === "string" ? JSON.stringify(key) : `Readonly<{ readonly kind: 'prefix'; readonly prefix: ${JSON.stringify(key.prefix)} }>`;
1201
+ const renderPropertyKeyValue = (key) => typeof key === "string" ? JSON.stringify(key) : `Object.freeze({ kind: 'prefix' as const, prefix: ${JSON.stringify(key.prefix)} })`;
1202
+ const renderPropertyHandleType = (propertyId) => {
1203
+ const property = getProperty(propertyId);
1204
+ return `SchemaPropertyHandle<${renderPropertyKeyType(property.key)}, ${propertyTypeFromContract(property.descriptor).type}, ${JSON.stringify(property.placement)}>`;
1205
+ };
1206
+ const renderPropertyHandleValue = (propertyId) => {
1207
+ const property = getProperty(propertyId);
1208
+ return `Object.freeze({ id: ${JSON.stringify(property.id)}, key: ${renderPropertyKeyValue(property.key)}, kind: 'schema-property' as const, placement: ${JSON.stringify(property.placement)} })`;
1209
+ };
1210
+ const applicationOwner = `schema:application:${applicationName}`;
1211
+ const resolvedApplicationProperties = applicationProperties.map(({ key, localId }) => {
1212
+ const matches = schema.properties.byId.filter((property) => property.owner === applicationOwner && (typeof property.key === "string" ? property.key === key : typeof key !== "string" && property.key.prefix === key.prefix));
1213
+ if (matches.length !== 1) throw new Error(`Application property "${localId}" must resolve to exactly one compiled property; found ${matches.length}.`);
1214
+ return Object.freeze({
1215
+ localId,
1216
+ property: matches[0]
1217
+ });
1218
+ });
1219
+ const schemaPluginBindings = compiledBindings.filter((binding) => binding.type || binding.key);
1220
+ const schemaPluginTypeFields = schemaPluginBindings.map((binding) => {
1221
+ const identity = [binding.type ? `readonly type: ${JSON.stringify(binding.type)};` : "", binding.key ? `readonly key: ${JSON.stringify(binding.key)};` : ""].filter(Boolean).join(" ");
1222
+ return ` readonly ${propertyName(binding.name)}: Readonly<{ ${identity} }>;`;
1223
+ }).join("\n");
1224
+ const schemaApplicationTypeFields = resolvedApplicationProperties.map(({ localId, property }) => ` readonly ${propertyName(localId)}: ${renderPropertyHandleType(property.id)};`).join("\n");
1225
+ const schemaPluginValueFields = schemaPluginBindings.map((binding) => {
1226
+ const identity = [binding.type ? `type: ${JSON.stringify(binding.type)}` : "", binding.key ? `key: ${JSON.stringify(binding.key)}` : ""].filter(Boolean).join(", ");
1227
+ return ` ${propertyName(binding.name)}: Object.freeze({ ${identity} }),`;
1228
+ }).join("\n");
1229
+ const schemaApplicationValueFields = resolvedApplicationProperties.map(({ localId, property }) => ` ${propertyName(localId)}: ${renderPropertyHandleValue(property.id)},`).join("\n");
1230
+ const resolveElementProperties = (binding) => {
1231
+ const element = elementByType.get(binding.type) ?? failInvariant("Expected value to be defined");
1232
+ const persisted = {};
1233
+ const construction = {};
1234
+ const materializedPropertyIds = new Set(element.construction.materializedPropertyIds);
1235
+ element.propertyIds.forEach((propertyId) => {
1236
+ const property = propertyById.get(propertyId);
1237
+ if (!property || typeof property.key !== "string") return;
1238
+ const fallback = propertyTypeFromContract(property.descriptor);
1239
+ const type = property.descriptor.kind === "json" ? properties.byPropertyId[propertyId]?.type ?? fallback.type : fallback.type;
1240
+ persisted[property.key] = Object.freeze({
1241
+ optional: !property.descriptor.required && (!materializedPropertyIds.has(propertyId) || property.descriptor.omitDefault),
1242
+ type
1243
+ });
1244
+ construction[property.key] = Object.freeze({
1245
+ optional: !property.descriptor.required,
1246
+ type
1247
+ });
1248
+ });
1249
+ return Object.freeze({
1250
+ construction,
1251
+ persisted
1252
+ });
1253
+ };
1254
+ const resolvedProperties = new Map(bindings.map((binding) => [binding.name, resolveElementProperties(binding)]));
1255
+ const resolvedTextProperties = Object.freeze(Object.fromEntries(schema.properties.byId.flatMap((property) => property.placement === "text" && typeof property.key === "string" ? [[property.key, properties.byPropertyId[property.id] ?? propertyTypeFromContract(property.descriptor)]] : [])));
1256
+ const elementDeclarations = bindings.map((binding) => {
1257
+ const element = elementByType.get(binding.type) ?? failInvariant("Expected value to be defined");
1258
+ const fields = renderProperties((resolvedProperties.get(binding.name) ?? failInvariant("Expected value to be defined")).persisted, " ");
1259
+ const childRoots = element.contentRoots.length > 0 ? `\n readonly childRoots: Readonly<{ ${element.contentRoots.map(([slot]) => `${propertyName(slot)}: string;`).join(" ")} }>;` : "";
1260
+ return `export interface ${binding.typeName} extends Element {\n readonly children: ${childrenType(element.content, bindingByType, "EditorText")};${childRoots}\n readonly type: ${JSON.stringify(binding.type)};${fields ? `\n${fields}` : ""}\n}`;
1261
+ }).join("\n\n");
1262
+ const allowedElementTypeSet = new Set(schema.primaryRoot.content.allowedElementTypes);
1263
+ const mutationDeclarations = bindings.map((binding) => {
1264
+ const element = elementByType.get(binding.type) ?? failInvariant("Expected value to be defined");
1265
+ const mutation = resolvedProperties.get(binding.name) ?? failInvariant("Expected value to be defined");
1266
+ const construction = renderProperties(mutation.construction, " ");
1267
+ const persisted = renderProperties(mutation.persisted, " ");
1268
+ const block = `\n readonly block: ${!element.behavior.inline};`;
1269
+ const toggle = element.groups.includes("textBlock") && allowedElementTypeSet.has(binding.type) && Object.values(mutation.construction).every((property) => property.optional) && compiledBindingByName.get(binding.name)?.authoredToggle !== true ? "\n readonly toggle: true;" : "";
1270
+ return ` readonly ${propertyName(binding.name)}: Readonly<{${block}\n readonly construction: ${renderExactReadonlyRecord(construction, " ")};\n readonly properties: ${renderExactReadonlyRecord(persisted, " ")};${toggle}\n readonly type: ${JSON.stringify(binding.type)};\n }>;`;
1271
+ }).join("\n");
1272
+ const textFields = renderProperties(resolvedTextProperties, " ");
1273
+ const rootType = childrenType(schema.primaryRoot.content, bindingByType, "EditorText");
1274
+ const elementUnion = bindings.map(({ typeName }) => typeName).join(" | ") || "Element";
1275
+ const editorImport = relativeImport(typesPath, entryPath);
1276
+ const coreTypeImports = [
1277
+ "Element",
1278
+ ...schemaApplicationTypeFields ? ["SchemaPropertyHandle"] : [],
1279
+ "Text"
1280
+ ].join(", ");
1281
+ return `${generatedHeader(entryPath)}\nimport type { ${coreTypeImports} } from 'platejs';\nimport type { GeneratedEditorTypeProvider } from 'platejs/compiler';\nimport type { Editor as BaseEditor } from 'platejs/react';\n\nimport type * as EditorModule from ${JSON.stringify(editorImport)};\n\nexport interface EditorText extends Text {\n readonly text: string;${textFields ? `\n${textFields}` : ""}\n}\n\n${elementDeclarations}\n\nexport type EditorElement = ${elementUnion};\nexport type Value = ${rootType};\nexport type Schema = Readonly<{\n readonly plugins: ${renderExactReadonlyRecord(schemaPluginTypeFields, " ")};\n readonly properties: ${renderExactReadonlyRecord(schemaApplicationTypeFields, " ")};\n}>;\nexport type Mutations = ${renderExactReadonlyRecord(mutationDeclarations)};\ntype Types = Readonly<{\n element: EditorElement;\n mutations: Mutations;\n schema: Schema;\n text: EditorText;\n value: Value;\n}>;\n\nexport const schema = Object.freeze({\n plugins: Object.freeze({${schemaPluginValueFields ? `\n${schemaPluginValueFields}\n ` : ""}}),\n properties: Object.freeze({${schemaApplicationValueFields ? `\n${schemaApplicationValueFields}\n ` : ""}}),\n}) satisfies Schema;\n\ntype EditorPlugins = (typeof EditorModule)[${JSON.stringify(pluginExportName)}] & GeneratedEditorTypeProvider<Types>;\n\nexport type Editor = BaseEditor<Value, readonly [], EditorPlugins>;\n`;
1282
+ };
1283
+ const outputPaths = (entryPath) => {
1284
+ const base = basename(entryPath, extname(entryPath));
1285
+ const directory = dirname(entryPath);
1286
+ return {
1287
+ schemaPath: join(directory, `${base}.schema.json`),
1288
+ typesPath: join(directory, `${base}.generated.ts`)
1289
+ };
1290
+ };
1291
+ const writeDurableFile = (path, content) => {
1292
+ mkdirSync(dirname(path), { recursive: true });
1293
+ const descriptor = openSync(path, "w");
1294
+ try {
1295
+ writeFileSync(descriptor, content);
1296
+ fsyncSync(descriptor);
1297
+ } finally {
1298
+ closeSync(descriptor);
1299
+ }
1300
+ };
1301
+ const ARTIFACT_PROCESS_TOKEN = randomUUID();
1302
+ var SimulatedArtifactProcessInterruptionError = class extends Error {
1303
+ name = "SimulatedArtifactProcessInterruptionError";
1304
+ constructor() {
1305
+ super("simulated process interruption");
1306
+ }
1307
+ };
1308
+ const artifactBatchFingerprint = (paths) => createHash("sha256").update(paths.map(canonicalPath).sort().join("\0")).digest("hex").slice(0, 32);
1309
+ const artifactJournalPath = (paths) => {
1310
+ const sorted = [...paths].sort();
1311
+ return join(artifactStateRoot(sorted[0]), "transactions", `${artifactBatchFingerprint(sorted)}.json`);
1312
+ };
1313
+ const artifactJournalReferencePath = (artifactPath) => join(artifactStateRoot(artifactPath), "artifacts", `${pathFingerprint(artifactPath)}.json`);
1314
+ const artifactLockPath = (artifactPath) => join(artifactStateRoot(artifactPath), "locks", `artifact-${pathFingerprint(artifactPath)}`);
1315
+ const artifactBatchLockPath = (paths) => {
1316
+ const sorted = [...paths].sort();
1317
+ return join(artifactStateRoot(sorted[0]), "locks", `transaction-${artifactBatchFingerprint(sorted)}`);
1318
+ };
1319
+ const isProcessAlive = (pid) => {
1320
+ try {
1321
+ process.kill(pid, 0);
1322
+ return true;
1323
+ } catch (error) {
1324
+ return error.code !== "ESRCH";
1325
+ }
1326
+ };
1327
+ const acquireArtifactLock = (lockPath) => {
1328
+ const directory = dirname(lockPath);
1329
+ const prefix = `${basename(lockPath)}.`;
1330
+ const token = randomUUID();
1331
+ const path = join(directory, `${prefix}${process.pid}-${token}.json`);
1332
+ const temporary = `${path}.tmp`;
1333
+ mkdirSync(directory, { recursive: true });
1334
+ try {
1335
+ writeFileSync(temporary, `${JSON.stringify({
1336
+ pid: process.pid,
1337
+ processToken: ARTIFACT_PROCESS_TOKEN,
1338
+ token,
1339
+ version: 1
1340
+ })}\n`);
1341
+ renameSync(temporary, path);
1342
+ } finally {
1343
+ rmSync(temporary, { force: true });
1344
+ }
1345
+ try {
1346
+ for (const name of readdirSync(directory)) {
1347
+ if (!name.startsWith(prefix)) continue;
1348
+ const candidate = join(directory, name);
1349
+ if (candidate === path) continue;
1350
+ const owner = JSON.parse(readFileSync(candidate, "utf-8"));
1351
+ if (owner.version !== 1 || typeof owner.pid !== "number" || typeof owner.processToken !== "string" || typeof owner.token !== "string") throw new Error(`Invalid Plate artifact lock: ${path}`);
1352
+ if (owner.processToken === ARTIFACT_PROCESS_TOKEN || owner.pid !== process.pid && isProcessAlive(owner.pid)) throw new Error("Another process is already replacing these generated artifacts.");
1353
+ rmSync(candidate, { force: true });
1354
+ }
1355
+ return { path };
1356
+ } catch (error) {
1357
+ rmSync(path, { force: true });
1358
+ throw error;
1359
+ }
1360
+ };
1361
+ const releaseArtifactLock = ({ path }) => {
1362
+ rmSync(path, { force: true });
1363
+ };
1364
+ const acquireArtifactPublicationGates = (artifactPaths) => {
1365
+ const locks = [];
1366
+ try {
1367
+ [...artifactPaths].sort().forEach((artifactPath) => {
1368
+ locks.push(acquireArtifactLock(artifactLockPath(artifactPath)));
1369
+ });
1370
+ } catch (error) {
1371
+ locks.reverse().forEach(releaseArtifactLock);
1372
+ throw error;
1373
+ }
1374
+ return locks;
1375
+ };
1376
+ const releaseArtifactPublicationGates = (locks) => {
1377
+ [...locks].reverse().forEach(releaseArtifactLock);
1378
+ };
1379
+ const writeArtifactJournal = (path, journal) => {
1380
+ const temporary = `${path}.${process.pid}-${randomUUID()}.tmp`;
1381
+ try {
1382
+ writeDurableFile(temporary, `${JSON.stringify(journal)}\n`);
1383
+ renameSync(temporary, path);
1384
+ } finally {
1385
+ rmSync(temporary, { force: true });
1386
+ }
1387
+ };
1388
+ const writeArtifactJournalReference = (artifactPath, journalPath) => {
1389
+ const path = artifactJournalReferencePath(artifactPath);
1390
+ const temporary = `${path}.${process.pid}-${randomUUID()}.tmp`;
1391
+ try {
1392
+ writeDurableFile(temporary, `${JSON.stringify({
1393
+ journalPath,
1394
+ version: 1
1395
+ })}\n`);
1396
+ renameSync(temporary, path);
1397
+ } finally {
1398
+ rmSync(temporary, { force: true });
1399
+ }
1400
+ };
1401
+ const readArtifactJournalReference = (artifactPath) => {
1402
+ const path = artifactJournalReferencePath(artifactPath);
1403
+ if (!existsSync(path)) return void 0;
1404
+ const reference = JSON.parse(readFileSync(path, "utf-8"));
1405
+ if (reference.version !== 1 || typeof reference.journalPath !== "string" || !isAbsolute(reference.journalPath)) throw new Error(`Invalid Plate artifact journal reference: ${path}`);
1406
+ return reference;
1407
+ };
1408
+ const readArtifactJournal = (path, expectedPaths) => {
1409
+ if (!existsSync(path)) return void 0;
1410
+ const journal = JSON.parse(readFileSync(path, "utf-8"));
1411
+ const actual = journal.artifacts.map((artifact) => artifact.path).sort();
1412
+ const expected = expectedPaths ? new Set(expectedPaths) : void 0;
1413
+ if (journal.version !== 1 || journal.phase !== "installed" && journal.phase !== "installing" || actual.length === 0 || new Set(actual).size !== actual.length || expected && actual.some((value) => !expected.has(value))) throw new Error(`Invalid Plate artifact journal: ${path}`);
1414
+ return journal;
1415
+ };
1416
+ const recoverArtifactJournal = (path, expectedPaths) => {
1417
+ const journal = readArtifactJournal(path, expectedPaths);
1418
+ if (!journal) return;
1419
+ if (journal.phase === "installed") journal.artifacts.forEach(({ backup, temporary }) => {
1420
+ rmSync(backup, { force: true });
1421
+ rmSync(temporary, { force: true });
1422
+ });
1423
+ else journal.artifacts.forEach(({ backup, existed, path: innerPath, temporary }) => {
1424
+ rmSync(temporary, { force: true });
1425
+ if (existsSync(backup)) {
1426
+ rmSync(innerPath, { force: true });
1427
+ renameSync(backup, innerPath);
1428
+ } else if (!existed) rmSync(innerPath, { force: true });
1429
+ else if (!existsSync(innerPath)) throw new Error(`Cannot recover Plate artifact transaction because both the artifact and backup are missing: ${innerPath}`);
1430
+ });
1431
+ new Set(journal.artifacts.map(({ backup }) => dirname(backup))).forEach((directory) => {
1432
+ rmSync(directory, {
1433
+ force: true,
1434
+ recursive: true
1435
+ });
1436
+ });
1437
+ journal.artifacts.forEach(({ path: innerPath2 }) => {
1438
+ rmSync(artifactJournalReferencePath(innerPath2), { force: true });
1439
+ });
1440
+ rmSync(path, { force: true });
1441
+ };
1442
+ const acquireArtifactRecoveryGates = (artifactPaths) => {
1443
+ let paths = [...new Set(artifactPaths.map((path) => resolve(path)))].sort();
1444
+ while (true) {
1445
+ const gates = acquireArtifactPublicationGates(paths);
1446
+ try {
1447
+ const journalPaths = /* @__PURE__ */ new Set();
1448
+ paths.forEach((path) => {
1449
+ const reference = readArtifactJournalReference(path);
1450
+ if (!reference) return;
1451
+ if (!existsSync(reference.journalPath)) {
1452
+ rmSync(artifactJournalReferencePath(path), { force: true });
1453
+ return;
1454
+ }
1455
+ journalPaths.add(reference.journalPath);
1456
+ });
1457
+ const recoveredPaths = [...journalPaths].flatMap((journalPath) => {
1458
+ return readArtifactJournal(journalPath)?.artifacts.map(({ path }) => path) ?? [];
1459
+ });
1460
+ const nextPaths = [.../* @__PURE__ */ new Set([...paths, ...recoveredPaths])].sort();
1461
+ if (nextPaths.length === paths.length && nextPaths.every((path, index) => path === paths[index])) return {
1462
+ gates,
1463
+ journalPaths,
1464
+ paths
1465
+ };
1466
+ releaseArtifactPublicationGates(gates);
1467
+ paths = nextPaths;
1468
+ } catch (error) {
1469
+ releaseArtifactPublicationGates(gates);
1470
+ throw error;
1471
+ }
1472
+ }
1473
+ };
1474
+ const recoverReferencedArtifactJournals = (journalPaths) => {
1475
+ journalPaths.forEach((journalPath) => {
1476
+ const journal = readArtifactJournal(journalPath);
1477
+ if (journal) recoverArtifactJournal(journalPath, journal.artifacts.map(({ path }) => path));
1478
+ });
1479
+ };
1480
+ const isCurrent = (path, content) => existsSync(path) && readFileSync(path, "utf-8") === content;
1481
+ const replaceArtifactsWithResult = (artifacts, { afterInstall, interruptAfterInstall, interruptAfterReference, removeBackup = (path) => {
1482
+ rmSync(path, { force: true });
1483
+ } } = {}) => {
1484
+ if (artifacts.length === 0) return Object.freeze([]);
1485
+ const paths = artifacts.map(({ path }) => resolve(path));
1486
+ if (new Set(paths).size !== paths.length) throw new Error("Plate cannot replace the same generated artifact twice.");
1487
+ const journalPath = artifactJournalPath(paths);
1488
+ mkdirSync(dirname(journalPath), { recursive: true });
1489
+ const recovery = acquireArtifactRecoveryGates(paths);
1490
+ let lock;
1491
+ try {
1492
+ lock = paths.length === 1 ? void 0 : acquireArtifactLock(artifactBatchLockPath(paths));
1493
+ recoverReferencedArtifactJournals(recovery.journalPaths);
1494
+ if (!recovery.journalPaths.has(journalPath)) recoverArtifactJournal(journalPath, paths);
1495
+ if (artifacts.every(({ content }, index) => isCurrent(paths[index], content))) return Object.freeze([]);
1496
+ const token = `${process.pid}-${randomUUID()}`;
1497
+ const prepared = artifacts.flatMap((artifact, index) => {
1498
+ const path = paths[index];
1499
+ const stagingDirectory = join(artifactStateRoot(path), "staging", token);
1500
+ const artifactFingerprint = pathFingerprint(path);
1501
+ return existsSync(path) && readFileSync(path, "utf-8") === artifact.content ? [] : [{
1502
+ ...artifact,
1503
+ backup: join(stagingDirectory, `${artifactFingerprint}.backup`),
1504
+ existed: existsSync(path),
1505
+ path,
1506
+ temporary: join(stagingDirectory, `${artifactFingerprint}.generated`)
1507
+ }];
1508
+ });
1509
+ if (prepared.length === 0) return Object.freeze([]);
1510
+ const journal = {
1511
+ artifacts: prepared.map(({ backup, existed, path, temporary }) => ({
1512
+ backup,
1513
+ existed,
1514
+ path,
1515
+ temporary
1516
+ })),
1517
+ phase: "installing",
1518
+ version: 1
1519
+ };
1520
+ prepared.forEach(({ path }, index) => {
1521
+ writeArtifactJournalReference(path, journalPath);
1522
+ if (interruptAfterReference === index) throw new SimulatedArtifactProcessInterruptionError();
1523
+ });
1524
+ writeArtifactJournal(journalPath, journal);
1525
+ try {
1526
+ prepared.forEach(({ content, path, temporary }) => {
1527
+ mkdirSync(dirname(path), { recursive: true });
1528
+ writeDurableFile(temporary, content);
1529
+ });
1530
+ } catch (error) {
1531
+ recoverArtifactJournal(journalPath, paths);
1532
+ throw error;
1533
+ }
1534
+ try {
1535
+ prepared.forEach(({ backup, existed, path }) => {
1536
+ if (existed) renameSync(path, backup);
1537
+ });
1538
+ prepared.forEach(({ path, temporary }, index) => {
1539
+ renameSync(temporary, path);
1540
+ if (interruptAfterInstall === index) throw new SimulatedArtifactProcessInterruptionError();
1541
+ afterInstall?.(path, index);
1542
+ });
1543
+ writeArtifactJournal(journalPath, {
1544
+ ...journal,
1545
+ phase: "installed"
1546
+ });
1547
+ } catch (error) {
1548
+ if (error instanceof SimulatedArtifactProcessInterruptionError) throw error;
1549
+ recoverArtifactJournal(journalPath, paths);
1550
+ throw error;
1551
+ }
1552
+ const cleanupErrors = [];
1553
+ prepared.forEach(({ backup }, index) => {
1554
+ try {
1555
+ removeBackup(backup, index);
1556
+ } catch (error) {
1557
+ cleanupErrors.push(error instanceof Error ? error.message : String(error));
1558
+ }
1559
+ });
1560
+ if (cleanupErrors.length > 0) process.stderr.write(`Generated artifacts were committed, but backup cleanup failed: ${cleanupErrors.join("; ")}\n`);
1561
+ else {
1562
+ new Set(prepared.map(({ backup }) => dirname(backup))).forEach((directory) => {
1563
+ rmSync(directory, {
1564
+ force: true,
1565
+ recursive: true
1566
+ });
1567
+ });
1568
+ prepared.forEach(({ path }) => {
1569
+ rmSync(artifactJournalReferencePath(path), { force: true });
1570
+ });
1571
+ rmSync(journalPath, { force: true });
1572
+ }
1573
+ return Object.freeze(prepared.map(({ path }) => path));
1574
+ } finally {
1575
+ if (lock) releaseArtifactLock(lock);
1576
+ releaseArtifactPublicationGates(recovery.gates);
1577
+ }
1578
+ };
1579
+ /**
1580
+ * Exported only for atomic rollback proof.
1581
+ *
1582
+ * @internal
1583
+ */
1584
+ const replaceArtifacts = (...args) => replaceArtifactsWithResult(...args).length > 0;
1585
+ /**
1586
+ * Resolve entries and reject overlapping artifact ownership.
1587
+ *
1588
+ * @internal
1589
+ */
1590
+ const resolveEditorEntryPaths = (entries, cwd = process.cwd()) => {
1591
+ const entryPaths = [...new Set(entries.map((entry) => canonicalPath(resolve(cwd, entry))))];
1592
+ if (entryPaths.length === 0) throw new Error("Plate requires at least one editor module.");
1593
+ entryPaths.forEach((entryPath) => {
1594
+ if (!existsSync(entryPath) || !statSync(entryPath).isFile()) throw new Error(`Plate editor entry does not exist: ${entryPath}`);
1595
+ });
1596
+ const outputOwners = /* @__PURE__ */ new Map();
1597
+ entryPaths.forEach((entryPath) => {
1598
+ Object.values(outputPaths(entryPath)).forEach((outputPath) => {
1599
+ const owner = outputOwners.get(outputPath);
1600
+ if (owner) throw new Error(`Plate editor modules produce the same generated artifact: ${owner} and ${entryPath} -> ${outputPath}`);
1601
+ outputOwners.set(outputPath, entryPath);
1602
+ });
1603
+ });
1604
+ return Object.freeze(entryPaths);
1605
+ };
1606
+ /**
1607
+ * Compile editors without mutating generated artifacts.
1608
+ *
1609
+ * @internal
1610
+ */
1611
+ const compileEditors = async (entries, options = {}, session) => {
1612
+ const cwd = resolve(options.cwd ?? process.cwd());
1613
+ const entryPaths = resolveEditorEntryPaths(entries, cwd);
1614
+ const prepared = (await Promise.all(entryPaths.map((entryPath) => readEditor(entryPath, cwd)))).map((editor, index) => {
1615
+ const entryPath = entryPaths[index];
1616
+ const { schema } = editor;
1617
+ const bindings = createBindings(editor.bindings, schema);
1618
+ const owners = [...new Set(schema.properties.byId.map(({ owner }) => owner))].sort();
1619
+ const { schemaPath, typesPath } = outputPaths(entryPath);
1620
+ return {
1621
+ bindings,
1622
+ editor,
1623
+ entryPath,
1624
+ owners,
1625
+ schema,
1626
+ schemaPath,
1627
+ typesPath
1628
+ };
1629
+ });
1630
+ const materialized = await materializePropertyGroups(prepared.map(({ bindings, editor, entryPath, owners, schema }) => ({
1631
+ bindings,
1632
+ entryPath,
1633
+ owners,
1634
+ pluginExportName: editor.pluginExportName,
1635
+ schema
1636
+ })), cwd, session);
1637
+ return Object.freeze(prepared.map((current, index) => {
1638
+ const properties = materialized[index];
1639
+ const schemaSource = `${JSON.stringify(current.schema, null, 2)}\n`;
1640
+ const typesSource = renderGeneratedTypes(current.entryPath, current.typesPath, current.editor.pluginExportName, current.schema, current.bindings, properties, current.editor.bindings, current.editor.applicationProperties, current.editor.applicationName);
1641
+ return Object.freeze({
1642
+ entryPath: current.entryPath,
1643
+ schema: current.schema,
1644
+ schemaPath: current.schemaPath,
1645
+ schemaSource,
1646
+ typesPath: current.typesPath,
1647
+ typesSource
1648
+ });
1649
+ }));
1650
+ };
1651
+ /**
1652
+ * Compile one editor without mutating generated artifacts.
1653
+ *
1654
+ * @internal
1655
+ */
1656
+ const compileEditor = async (entry, options = {}) => {
1657
+ return (await compileEditors([entry], options))[0];
1658
+ };
1659
+ const generateEditors = async (entries, options = {}, session) => {
1660
+ const compiled = await compileEditors(entries, options, session);
1661
+ const artifacts = compiled.flatMap(({ schemaPath, schemaSource, typesPath, typesSource }) => [{
1662
+ content: typesSource,
1663
+ path: typesPath
1664
+ }, {
1665
+ content: schemaSource,
1666
+ path: schemaPath
1667
+ }]);
1668
+ let publishedPaths = /* @__PURE__ */ new Set();
1669
+ if (options.check) {
1670
+ const recovery = acquireArtifactRecoveryGates(artifacts.map(({ path }) => path));
1671
+ let stale;
1672
+ try {
1673
+ recoverReferencedArtifactJournals(recovery.journalPaths);
1674
+ stale = artifacts.flatMap(({ content, path }) => isCurrent(path, content) ? [] : [path]);
1675
+ } finally {
1676
+ releaseArtifactPublicationGates(recovery.gates);
1677
+ }
1678
+ if (stale.length > 0) throw new Error(`Generated Plate artifacts are stale:\n${stale.map((path) => `- ${path}`).join("\n")}`);
1679
+ } else publishedPaths = new Set(replaceArtifactsWithResult(artifacts));
1680
+ return Object.freeze(compiled.map((current) => {
1681
+ const { schemaSource: _schemaSource, typesSource: _typesSource, ...innerArtifacts } = current;
1682
+ return Object.freeze({
1683
+ ...innerArtifacts,
1684
+ status: publishedPaths.has(current.typesPath) || publishedPaths.has(current.schemaPath) ? "generated" : "upToDate"
1685
+ });
1686
+ }));
1687
+ };
1688
+ //#endregion
1689
+ //#region src/migrate.ts
1690
+ const FINGERPRINT_PREFIX_PATTERN = /^.*:/;
1691
+ const MIGRATION_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
1692
+ const sha256 = (value) => createHash("sha256").update(value).digest("hex");
1693
+ const readGitFile = (path, cwd) => {
1694
+ try {
1695
+ const root = execFileSync("git", ["rev-parse", "--show-toplevel"], {
1696
+ cwd,
1697
+ encoding: "utf-8",
1698
+ stdio: [
1699
+ "ignore",
1700
+ "pipe",
1701
+ "ignore"
1702
+ ]
1703
+ }).trim();
1704
+ const repositoryPath = relative(root, path).replaceAll("\\", "/");
1705
+ if (repositoryPath.startsWith("../")) throw new Error("outside repository");
1706
+ return execFileSync("git", ["show", `HEAD:${repositoryPath}`], {
1707
+ cwd: root,
1708
+ encoding: "utf-8",
1709
+ stdio: [
1710
+ "ignore",
1711
+ "pipe",
1712
+ "ignore"
1713
+ ]
1714
+ });
1715
+ } catch {
1716
+ throw new Error(`Plate migrations require a committed generated artifact: ${path}`);
1717
+ }
1718
+ };
1719
+ const schemaTypesSnapshot = (source, fingerprint) => {
1720
+ const start = source.indexOf("export interface EditorText");
1721
+ const end = source.indexOf("\nexport type Schema =");
1722
+ if (start === -1 || end < start) throw new Error("Invalid generated editor type artifact.");
1723
+ return `/* Generated schema type snapshot. Do not edit. */\nimport type { EditorSchemaContract, Element, Text } from 'platejs';\n\n${source.slice(start, end).trim()}\n\nexport type SchemaContract = EditorSchemaContract;\nexport const fingerprint = ${JSON.stringify(fingerprint)};\n`;
1724
+ };
1725
+ const migrationDirectoryName = (schema, name) => {
1726
+ if (!MIGRATION_NAME_PATTERN.test(name)) throw new Error("Plate migration names must be lowercase kebab-case identifiers.");
1727
+ return `${schema.identity.kind === "named" ? `v${schema.identity.version}` : schema.fingerprint.replace(FINGERPRINT_PREFIX_PATTERN, "").slice(0, 12)}-${name}`;
1728
+ };
1729
+ const createEditorMigration = async (entry, name, options = {}) => {
1730
+ const cwd = resolve(options.cwd ?? process.cwd());
1731
+ const compiled = await compileEditor(entry, { cwd });
1732
+ const readCommitted = options.readCommittedFile ?? ((path) => readGitFile(path, cwd));
1733
+ const previousSchemaSource = readCommitted(compiled.schemaPath);
1734
+ const previousTypesSource = readCommitted(compiled.typesPath);
1735
+ let previousInput;
1736
+ try {
1737
+ previousInput = JSON.parse(previousSchemaSource);
1738
+ } catch {
1739
+ throw new Error(`Committed Plate schema artifact is not valid JSON: ${compiled.schemaPath}`);
1740
+ }
1741
+ const previous = readEditorSchemaContract(previousInput);
1742
+ if (!previous) throw new Error(`Committed Plate schema artifact is invalid: ${compiled.schemaPath}`);
1743
+ const diff = diffEditorSchemaContracts(previous, compiled.schema);
1744
+ if (diff.changes.length === 0) throw new Error("Plate cannot scaffold a migration without schema changes.");
1745
+ if (diff.requiresMigration) {
1746
+ const from = previous.identity;
1747
+ const to = compiled.schema.identity;
1748
+ if (from.kind !== "named" || to.kind !== "named" || from.id !== to.id || to.version <= from.version) throw new Error("Migration-required schema changes need the same named schema id and a higher version.");
1749
+ }
1750
+ const directory = join(dirname(compiled.entryPath), "migrations", migrationDirectoryName(compiled.schema, name));
1751
+ const fromSchemaPath = join(directory, "from.schema.json");
1752
+ const toSchemaPath = join(directory, "to.schema.json");
1753
+ const fromTypesPath = join(directory, "from.ts");
1754
+ const toTypesPath = join(directory, "to.ts");
1755
+ const manifestPath = join(directory, "manifest.json");
1756
+ const migrationPath = join(directory, "migration.ts");
1757
+ const paths = [
1758
+ fromSchemaPath,
1759
+ toSchemaPath,
1760
+ fromTypesPath,
1761
+ toTypesPath,
1762
+ manifestPath,
1763
+ migrationPath
1764
+ ];
1765
+ if (paths.some(existsSync)) throw new Error(`Plate migration already exists: ${directory}`);
1766
+ const fromSchema = `${JSON.stringify(previous, null, 2)}\n`;
1767
+ const toSchema = compiled.schemaSource;
1768
+ const fromTypes = schemaTypesSnapshot(previousTypesSource, previous.fingerprint);
1769
+ const toTypes = schemaTypesSnapshot(compiled.typesSource, compiled.schema.fingerprint);
1770
+ const migration = `import type { EditorDocumentValue } from 'platejs';\nimport type { DocumentMigration } from 'platejs/migrations';\n\nimport type { Value as FromValue } from './from';\nimport type { Value as ToValue } from './to';\n\ntype FromDocument = EditorDocumentValue<FromValue>;\ntype ToDocument = EditorDocumentValue<ToValue>;\n\n/** Add this target-version step to the application document migration chain. */\nexport const migrate: DocumentMigration<\n FromDocument,\n ToDocument,\n ${previous.identity.kind === "named" ? previous.identity.version : "number"},\n ${compiled.schema.identity.kind === "named" ? compiled.schema.identity.version : "number"}\n> = ({ document }) => {\n void document;\n throw new Error('Implement schema migration: ${name}');\n};\n`;
1771
+ const manifest = `${JSON.stringify({
1772
+ checksums: {
1773
+ fromSchema: sha256(fromSchema),
1774
+ fromTypes: sha256(fromTypes),
1775
+ migration: sha256(migration),
1776
+ toSchema: sha256(toSchema),
1777
+ toTypes: sha256(toTypes)
1778
+ },
1779
+ diff,
1780
+ editor: relative(cwd, compiled.entryPath).replaceAll("\\", "/"),
1781
+ formatVersion: 1,
1782
+ from: previous.identity,
1783
+ name,
1784
+ to: compiled.schema.identity
1785
+ }, null, 2)}\n`;
1786
+ replaceArtifacts([
1787
+ {
1788
+ content: fromSchema,
1789
+ path: fromSchemaPath
1790
+ },
1791
+ {
1792
+ content: toSchema,
1793
+ path: toSchemaPath
1794
+ },
1795
+ {
1796
+ content: fromTypes,
1797
+ path: fromTypesPath
1798
+ },
1799
+ {
1800
+ content: toTypes,
1801
+ path: toTypesPath
1802
+ },
1803
+ {
1804
+ content: manifest,
1805
+ path: manifestPath
1806
+ },
1807
+ {
1808
+ content: migration,
1809
+ path: migrationPath
1810
+ }
1811
+ ]);
1812
+ return Object.freeze({
1813
+ diff,
1814
+ directory,
1815
+ manifestPath,
1816
+ migrationPath,
1817
+ paths: Object.freeze(paths)
1818
+ });
1819
+ };
1820
+ //#endregion
1821
+ //#region src/run-migration.ts
1822
+ const CSS_FILE_PATTERN = /\.css$/;
1823
+ const ANY_FILE_PATTERN = /.*/;
1824
+ const MIGRATION_ENTRY_PATTERN = /^plate-migration:entry$/;
1825
+ const JSON_EQUAL_SOURCE = `
1826
+ const jsonEqual = (left, right) => {
1827
+ if (Object.is(left, right)) return true;
1828
+ if (Array.isArray(left) || Array.isArray(right)) {
1829
+ return Array.isArray(left) && Array.isArray(right) &&
1830
+ left.length === right.length &&
1831
+ left.every((value, index) => jsonEqual(value, right[index]));
1832
+ }
1833
+ if (!left || !right || typeof left !== 'object' || typeof right !== 'object') {
1834
+ return false;
1835
+ }
1836
+ const keys = Object.keys(left);
1837
+ return keys.length === Object.keys(right).length &&
1838
+ keys.every((key) => Object.hasOwn(right, key) && jsonEqual(left[key], right[key]));
1839
+ };
1840
+ `;
1841
+ const evaluate = (bundlePath, request, resultPath, cwd) => new Promise((resolvePromise, reject) => {
1842
+ const child = execFile(process.execPath, [bundlePath, resultPath], {
1843
+ cwd,
1844
+ maxBuffer: 16 * 1024 * 1024
1845
+ }, (error, _stdout, stderr) => {
1846
+ if (!error) {
1847
+ resolvePromise();
1848
+ return;
1849
+ }
1850
+ reject(new Error(stderr.trim() || `Plate could not run the bundled migration: ${error.message}`));
1851
+ });
1852
+ child.stdin?.on("error", () => {});
1853
+ child.stdin?.end(request);
1854
+ });
1855
+ const migrateDocuments = async (entry, documents, options) => {
1856
+ const cwd = resolve(options.cwd ?? process.cwd());
1857
+ const entryPath = resolve(cwd, entry);
1858
+ const outputDirectory = mkdtempSync(join(tmpdir(), "plate-migrate-run-"));
1859
+ const bundlePath = join(outputDirectory, "runner.mjs");
1860
+ const resultPath = join(outputDirectory, "result.json");
1861
+ try {
1862
+ const output = (await build$1({
1863
+ bundle: true,
1864
+ conditions: ["production"],
1865
+ format: "esm",
1866
+ jsx: "automatic",
1867
+ logLevel: "silent",
1868
+ platform: "node",
1869
+ plugins: [{
1870
+ name: "plate-migration-entry",
1871
+ setup(context) {
1872
+ context.onResolve({ filter: MIGRATION_ENTRY_PATTERN }, () => ({
1873
+ namespace: "plate-migration-entry",
1874
+ path: entryPath
1875
+ }));
1876
+ context.onLoad({
1877
+ filter: ANY_FILE_PATTERN,
1878
+ namespace: "plate-migration-entry"
1879
+ }, () => ({
1880
+ contents: `export { EditorMigrations } from ${JSON.stringify(entryPath)};`,
1881
+ loader: "js",
1882
+ resolveDir: dirname(entryPath)
1883
+ }));
1884
+ }
1885
+ }, {
1886
+ name: "plate-empty-styles",
1887
+ setup(context) {
1888
+ context.onResolve({ filter: CSS_FILE_PATTERN }, ({ path }) => ({
1889
+ namespace: "plate-empty-style",
1890
+ path
1891
+ }));
1892
+ context.onLoad({
1893
+ filter: ANY_FILE_PATTERN,
1894
+ namespace: "plate-empty-style"
1895
+ }, () => ({
1896
+ contents: "",
1897
+ loader: "js"
1898
+ }));
1899
+ }
1900
+ }],
1901
+ stdin: {
1902
+ contents: `import { readFileSync, writeFileSync } from 'node:fs';
1903
+ ${JSON_EQUAL_SOURCE}
1904
+
1905
+ const readRequest = async () => {
1906
+ const chunks = [];
1907
+ for await (const chunk of process.stdin) chunks.push(chunk);
1908
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
1909
+ };
1910
+ const request = await readRequest();
1911
+ const { EditorMigrations: migrations } = await import('plate-migration:entry');
1912
+ const { migrateDocument } = await import('platejs/migrations');
1913
+ const holds = (value, field) => Object.hasOwn(value, field) && value[field] !== undefined;
1914
+ const isEnvelope = (value) =>
1915
+ value !== null && typeof value === 'object' && !Array.isArray(value) &&
1916
+ holds(value, 'document') && holds(value, 'schema') && !holds(value, 'children');
1917
+ const outputs = request.documents.map(({ label, path, text }) => {
1918
+ let source;
1919
+ let migration;
1920
+
1921
+ try {
1922
+ source = JSON.parse(path === undefined ? text : readFileSync(path, 'utf8'));
1923
+ if (request.source !== undefined && isEnvelope(source)) {
1924
+ throw new Error('A persisted document envelope carries its own schema version; run it without --from.');
1925
+ }
1926
+ migration = migrateDocument(source, {
1927
+ migrations,
1928
+ ...(request.source === undefined ? {} : { source: request.source }),
1929
+ });
1930
+ } catch (error) {
1931
+ throw new Error(label + ': ' + (error instanceof Error ? error.message : String(error)), { cause: error });
1932
+ }
1933
+ const output = migration.output;
1934
+ const outputText = JSON.stringify(output, null, 2) + '\\n';
1935
+
1936
+ return { applied: migration.applied, changed: !jsonEqual(source, output), outputText, path: label };
1937
+ });
1938
+
1939
+ writeFileSync(process.argv[2], JSON.stringify(outputs), 'utf8');
1940
+ `,
1941
+ loader: "ts",
1942
+ resolveDir: dirname(entryPath),
1943
+ sourcefile: "plate-migration-runner.ts"
1944
+ },
1945
+ write: false
1946
+ })).outputFiles?.[0];
1947
+ if (!output) throw new Error(`Plate could not bundle "${entryPath}".`);
1948
+ writeFileSync(bundlePath, output.text, "utf-8");
1949
+ await evaluate(bundlePath, JSON.stringify({
1950
+ documents,
1951
+ source: options.from
1952
+ }), resultPath, cwd);
1953
+ return JSON.parse(readFileSync(resultPath, "utf-8"));
1954
+ } finally {
1955
+ rmSync(outputDirectory, {
1956
+ force: true,
1957
+ recursive: true
1958
+ });
1959
+ }
1960
+ };
1961
+ const runEditorMigrations = async (entry, files, options = {}) => {
1962
+ if (options.check && options.write) throw new Error("plate migrate run cannot combine --check and --write.");
1963
+ if (files.length === 0) throw new Error("plate migrate run requires at least one JSON document.");
1964
+ const cwd = resolve(options.cwd ?? process.cwd());
1965
+ const evaluated = await migrateDocuments(entry, files.map((file) => {
1966
+ const path = resolve(cwd, file);
1967
+ return {
1968
+ label: path,
1969
+ path
1970
+ };
1971
+ }), options);
1972
+ if (options.write) replaceArtifacts(evaluated.filter(({ changed }) => changed).map(({ outputText, path }) => ({
1973
+ content: outputText,
1974
+ path
1975
+ })));
1976
+ return Object.freeze({
1977
+ changed: evaluated.filter(({ changed }) => changed).length,
1978
+ files: Object.freeze(evaluated.map(({ applied, changed, outputText, path }) => Object.freeze({
1979
+ applied: Object.freeze(applied),
1980
+ changed,
1981
+ outputText,
1982
+ path
1983
+ })))
1984
+ });
1985
+ };
1986
+ const runEditorMigrationInput = async (entry, sourceText, options = {}) => {
1987
+ const [file] = await migrateDocuments(entry, [{
1988
+ label: "stdin",
1989
+ text: sourceText
1990
+ }], options);
1991
+ return Object.freeze({
1992
+ applied: Object.freeze(file.applied),
1993
+ changed: file.changed,
1994
+ outputText: file.outputText
1995
+ });
1996
+ };
1997
+ //#endregion
1998
+ //#region src/bin.ts
1999
+ const DEFAULT_ENTRY = "src/editor.ts";
2000
+ const packageJson = createRequire(import.meta.url)("../package.json");
2001
+ const displayPath = (path) => relative(process.cwd(), path) || ".";
2002
+ const parseMigrationSource = (value) => {
2003
+ if (value === "current") return value;
2004
+ const version = Number(value);
2005
+ if (!Number.isSafeInteger(version) || version < 1) throw new Error("--from must be a positive schema version or \"current\".");
2006
+ return version;
2007
+ };
2008
+ const program = new Command().name("plate").version(packageJson.version).description("Generate exact Plate editor schema contracts.");
2009
+ registerDepsCommand(program);
2010
+ program.command("generate").description("Generate one or more exact editor contracts.").argument("[entries...]", "editor module files", [DEFAULT_ENTRY]).option("--check", "fail when committed artifacts are stale").action(async (entries, options) => {
2011
+ const startedAt = performance.now();
2012
+ const results = await generateEditors(entries, { check: options.check });
2013
+ const elapsed = ((performance.now() - startedAt) / 1e3).toFixed(2);
2014
+ const generated = results.filter(({ status }) => status === "generated").length;
2015
+ const verb = options.check ? "Checked" : generated === 0 ? "Up to date" : "Generated";
2016
+ process.stdout.write(`${verb} ${results.length} editor${results.length === 1 ? "" : "s"} in ${elapsed}s\n`);
2017
+ results.forEach(({ schemaPath, typesPath }) => {
2018
+ process.stdout.write(` ${displayPath(typesPath)}\n ${displayPath(schemaPath)}\n`);
2019
+ });
2020
+ });
2021
+ const migrateCommand = program.command("migrate").description("Create or run typed editor schema migrations.");
2022
+ migrateCommand.command("new").argument("<name>", "lowercase kebab-case migration name").option("--entry <path>", "editor module file", DEFAULT_ENTRY).action(async (name, options) => {
2023
+ const result = await createEditorMigration(options.entry, name);
2024
+ process.stdout.write(`Created migration ${displayPath(result.directory)}\n`);
2025
+ result.paths.forEach((path) => {
2026
+ process.stdout.write(` ${displayPath(path)}\n`);
2027
+ });
2028
+ });
2029
+ migrateCommand.command("run").description("Dry-run, check, or write document migrations to the current schema.").argument("[files...]", "JSON document files", []).option("--entry <path>", "editor module file", DEFAULT_ENTRY).option("--check", "exit nonzero when files require migration").option("--from <version>", "read every input as a raw document from this version, or \"current\"", parseMigrationSource).option("--stdin", "read one JSON document from standard input").option("--write", "atomically replace changed files").action(async (files, options) => {
2030
+ if (options.stdin) {
2031
+ if (files.length > 0) throw new Error("plate migrate run --stdin cannot include file paths.");
2032
+ if (options.write) throw new Error("plate migrate run --stdin cannot use --write.");
2033
+ const result = await runEditorMigrationInput(options.entry, readFileSync(0, "utf-8"), options);
2034
+ if (options.check) {
2035
+ process.stderr.write(`${result.changed ? "change" : "current"} stdin${result.applied.length > 0 ? ` (${result.applied.join(" -> ")})` : ""}\n`);
2036
+ if (result.changed) process.exitCode = 1;
2037
+ } else process.stdout.write(result.outputText);
2038
+ return;
2039
+ }
2040
+ const result = await runEditorMigrations(options.entry, files, options);
2041
+ const verb = options.write ? "Migrated" : options.check ? "Checked" : "Would migrate";
2042
+ process.stdout.write(`${verb} ${result.changed} of ${result.files.length} document${result.files.length === 1 ? "" : "s"}\n`);
2043
+ result.files.forEach(({ applied, changed, path }) => {
2044
+ process.stdout.write(` ${changed ? "change" : "current"} ${displayPath(path)}${applied.length > 0 ? ` (${applied.join(" -> ")})` : ""}\n`);
2045
+ });
2046
+ if (options.check && result.changed > 0) process.exitCode = 1;
2047
+ });
2048
+ program.parseAsync().catch((error) => {
2049
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
2050
+ process.exitCode = 1;
2051
+ });
2052
+ //#endregion
2053
+ export {};