@wp-operations/wp-ide 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +339 -339
- package/README.md +35 -42
- package/cli.js +56 -0
- package/dist/index.js +680 -1
- package/package.json +9 -4
package/dist/index.js
CHANGED
|
@@ -133,15 +133,694 @@ async function runBlueprint(php, blueprint) {
|
|
|
133
133
|
}
|
|
134
134
|
return { executed, skipped };
|
|
135
135
|
}
|
|
136
|
+
|
|
137
|
+
// src/platform.ts
|
|
138
|
+
import fs3 from "fs";
|
|
139
|
+
import path4 from "path";
|
|
140
|
+
var LAYOUT_FILE = ".github/platform.json";
|
|
141
|
+
var PLUGIN_TYPE = "psr4-plugin";
|
|
142
|
+
var APP_TYPE = "wp-app";
|
|
143
|
+
var COMPOSER_ACTIONS = ["add", "remove", "update"];
|
|
144
|
+
var DEFAULT_KINDS = [
|
|
145
|
+
{
|
|
146
|
+
key: "service-apps",
|
|
147
|
+
label: "Service apps",
|
|
148
|
+
folder: "service-apps",
|
|
149
|
+
manifest: ".github/service-apps.json"
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
key: "homepages",
|
|
153
|
+
label: "Homepages",
|
|
154
|
+
folder: "homepages",
|
|
155
|
+
manifest: ".github/homepages.json"
|
|
156
|
+
}
|
|
157
|
+
];
|
|
158
|
+
function slug(value) {
|
|
159
|
+
const result = value.trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
160
|
+
return result === "." || result === ".." ? "" : result.replace(/\.+$/, "");
|
|
161
|
+
}
|
|
162
|
+
function folder(value) {
|
|
163
|
+
return value.replace(/\\/g, "/").split("/").map(slug).filter((part) => part.length > 0).join("/");
|
|
164
|
+
}
|
|
165
|
+
function labelFor(key) {
|
|
166
|
+
return key.split("-").map((word) => word ? word[0].toUpperCase() + word.slice(1) : word).join(" ");
|
|
167
|
+
}
|
|
168
|
+
function readJson(file) {
|
|
169
|
+
if (!fs3.existsSync(file)) {
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
const raw = fs3.readFileSync(file, "utf8").replace(/^/, "");
|
|
173
|
+
try {
|
|
174
|
+
return JSON.parse(raw);
|
|
175
|
+
} catch (error) {
|
|
176
|
+
throw new Error(`${file} is not valid JSON: ${error.message}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function encodeJson(data) {
|
|
180
|
+
return JSON.stringify(data, null, 4) + "\n";
|
|
181
|
+
}
|
|
182
|
+
function writeJson(file, data) {
|
|
183
|
+
fs3.mkdirSync(path4.dirname(file), { recursive: true });
|
|
184
|
+
fs3.writeFileSync(file, encodeJson(data));
|
|
185
|
+
}
|
|
186
|
+
function normalizeLayout(data) {
|
|
187
|
+
const kinds = [];
|
|
188
|
+
const seen = /* @__PURE__ */ new Set();
|
|
189
|
+
const apps = data && typeof data.apps === "object" && data.apps ? data.apps : {};
|
|
190
|
+
for (const rawKey of Object.keys(apps)) {
|
|
191
|
+
const key = slug(rawKey);
|
|
192
|
+
const value = apps[rawKey];
|
|
193
|
+
const kind = typeof value === "string" ? { manifest: value } : value && typeof value === "object" ? value : {};
|
|
194
|
+
const dir = folder(String(kind.folder ?? key));
|
|
195
|
+
if (key === "" || dir === "" || seen.has(key)) {
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
seen.add(key);
|
|
199
|
+
kinds.push({
|
|
200
|
+
key,
|
|
201
|
+
label: String(kind.label ?? labelFor(key)),
|
|
202
|
+
folder: dir,
|
|
203
|
+
manifest: folder(String(kind.manifest ?? `.github/${key}.json`))
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
platform: data && typeof data.platform === "object" && data.platform ? data.platform : {},
|
|
208
|
+
packages: folder(String(data?.packages ?? "packages")) || "packages",
|
|
209
|
+
kinds
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
function hasLayout(rootDir) {
|
|
213
|
+
return fs3.existsSync(path4.join(rootDir, LAYOUT_FILE));
|
|
214
|
+
}
|
|
215
|
+
function readLayout(rootDir) {
|
|
216
|
+
const data = readJson(path4.join(rootDir, LAYOUT_FILE));
|
|
217
|
+
if (data === null) {
|
|
218
|
+
throw new Error(
|
|
219
|
+
`${LAYOUT_FILE} was not found in ${rootDir}. Run "wp-ops init" first.`
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
return normalizeLayout(data);
|
|
223
|
+
}
|
|
224
|
+
function layoutJson(layout) {
|
|
225
|
+
const apps = {};
|
|
226
|
+
for (const kind of layout.kinds) {
|
|
227
|
+
apps[kind.key] = {
|
|
228
|
+
label: kind.label,
|
|
229
|
+
folder: kind.folder,
|
|
230
|
+
manifest: kind.manifest
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
return { platform: layout.platform, packages: layout.packages, apps };
|
|
234
|
+
}
|
|
235
|
+
function findKind(layout, key) {
|
|
236
|
+
const kind = layout.kinds.find(
|
|
237
|
+
(item) => item.key === key || item.folder === key
|
|
238
|
+
);
|
|
239
|
+
if (!kind) {
|
|
240
|
+
throw new Error(
|
|
241
|
+
`Unknown kind "${key}". Kinds: ${layout.kinds.map((item) => item.key).join(", ") || "none"}.`
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
return kind;
|
|
245
|
+
}
|
|
246
|
+
function readManifest(rootDir, kind) {
|
|
247
|
+
const data = readJson(path4.join(rootDir, kind.manifest));
|
|
248
|
+
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
249
|
+
}
|
|
250
|
+
function writeManifest(rootDir, kind, manifest) {
|
|
251
|
+
writeJson(path4.join(rootDir, kind.manifest), manifest);
|
|
252
|
+
}
|
|
253
|
+
function subdirs(dir) {
|
|
254
|
+
if (!fs3.existsSync(dir)) {
|
|
255
|
+
return [];
|
|
256
|
+
}
|
|
257
|
+
return fs3.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name).sort();
|
|
258
|
+
}
|
|
259
|
+
function listApps(rootDir, layout = readLayout(rootDir)) {
|
|
260
|
+
const apps = [];
|
|
261
|
+
for (const kind of layout.kinds) {
|
|
262
|
+
const manifest = readManifest(rootDir, kind);
|
|
263
|
+
const kindDir = path4.join(rootDir, kind.folder);
|
|
264
|
+
const slugs = /* @__PURE__ */ new Set([...subdirs(kindDir), ...Object.keys(manifest)]);
|
|
265
|
+
for (const appSlug of [...slugs].sort()) {
|
|
266
|
+
const dir = path4.join(kindDir, appSlug);
|
|
267
|
+
const composer = readJson(path4.join(dir, "composer.json"));
|
|
268
|
+
const type = String(composer?.type ?? "");
|
|
269
|
+
const warnings = [];
|
|
270
|
+
if (!fs3.existsSync(dir)) {
|
|
271
|
+
warnings.push("listed in the manifest but the folder is missing");
|
|
272
|
+
} else if (!composer) {
|
|
273
|
+
warnings.push("no composer.json");
|
|
274
|
+
} else if (type !== APP_TYPE) {
|
|
275
|
+
warnings.push(`type is "${type || "none"}", expected "${APP_TYPE}"`);
|
|
276
|
+
}
|
|
277
|
+
if (fs3.existsSync(dir) && !manifest[appSlug]) {
|
|
278
|
+
warnings.push(`not in ${kind.manifest}`);
|
|
279
|
+
}
|
|
280
|
+
apps.push({
|
|
281
|
+
kind: kind.key,
|
|
282
|
+
label: kind.label,
|
|
283
|
+
slug: appSlug,
|
|
284
|
+
path: `${kind.folder}/${appSlug}`,
|
|
285
|
+
dir,
|
|
286
|
+
type,
|
|
287
|
+
name: String(composer?.name ?? ""),
|
|
288
|
+
manifest: manifest[appSlug] ?? null,
|
|
289
|
+
warnings
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
return apps;
|
|
294
|
+
}
|
|
295
|
+
function listPlugins(rootDir, layout = readLayout(rootDir)) {
|
|
296
|
+
const base = path4.join(rootDir, layout.packages);
|
|
297
|
+
const found = [];
|
|
298
|
+
const visit = (dir, depth) => {
|
|
299
|
+
for (const name of subdirs(dir)) {
|
|
300
|
+
if (name === "vendor" || name === "node_modules") {
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
const child = path4.join(dir, name);
|
|
304
|
+
const data = readJson(path4.join(child, "composer.json"));
|
|
305
|
+
if (data && typeof data.name === "string" && data.name !== "") {
|
|
306
|
+
const type = String(data.type ?? "library");
|
|
307
|
+
found.push({
|
|
308
|
+
name: data.name,
|
|
309
|
+
version: String(data.version ?? ""),
|
|
310
|
+
description: String(data.description ?? ""),
|
|
311
|
+
type,
|
|
312
|
+
path: path4.relative(rootDir, child).split(path4.sep).join("/"),
|
|
313
|
+
dir: child,
|
|
314
|
+
namespace: Object.keys(data.autoload?.["psr-4"] ?? {})[0] ?? "",
|
|
315
|
+
warnings: type === PLUGIN_TYPE ? [] : [`type is "${type}", expected "${PLUGIN_TYPE}"`]
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
if (depth < 2) {
|
|
319
|
+
visit(child, depth + 1);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
visit(base, 1);
|
|
324
|
+
return found.sort((a, b) => a.name.localeCompare(b.name));
|
|
325
|
+
}
|
|
326
|
+
function relativePath(from, to) {
|
|
327
|
+
const a = from.split("/").filter(Boolean);
|
|
328
|
+
const b = to.split("/").filter(Boolean);
|
|
329
|
+
while (a.length && b.length && a[0] === b[0]) {
|
|
330
|
+
a.shift();
|
|
331
|
+
b.shift();
|
|
332
|
+
}
|
|
333
|
+
return "../".repeat(a.length) + b.join("/");
|
|
334
|
+
}
|
|
335
|
+
var PACKAGE_NAME = /^[a-z0-9_.-]+\/[a-z0-9_.-]+$/;
|
|
336
|
+
function editComposer(data, action, appPath, plugins, constraint = "*") {
|
|
337
|
+
const result = JSON.parse(JSON.stringify(data));
|
|
338
|
+
for (const plugin of plugins) {
|
|
339
|
+
if (action === "add") {
|
|
340
|
+
result.require = { ...result.require ?? {} };
|
|
341
|
+
result.require[plugin.name] = constraint;
|
|
342
|
+
const url = `${relativePath(appPath, path4.posix.dirname(plugin.path))}/*`;
|
|
343
|
+
const repositories = Array.isArray(result.repositories) ? [...result.repositories] : result.repositories && typeof result.repositories === "object" ? Object.values(result.repositories) : [];
|
|
344
|
+
const urls = repositories.filter((repo) => repo && typeof repo === "object").map((repo) => repo.url);
|
|
345
|
+
if (!urls.includes(url)) {
|
|
346
|
+
const position = repositories.filter(
|
|
347
|
+
(repo) => repo && typeof repo === "object" && repo.type === "path"
|
|
348
|
+
).length;
|
|
349
|
+
repositories.splice(position, 0, {
|
|
350
|
+
type: "path",
|
|
351
|
+
url,
|
|
352
|
+
options: { symlink: false }
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
result.repositories = repositories;
|
|
356
|
+
} else if (result.require && typeof result.require === "object") {
|
|
357
|
+
delete result.require[plugin.name];
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return result;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// src/editor.ts
|
|
364
|
+
import crypto from "crypto";
|
|
365
|
+
import fs4 from "fs";
|
|
366
|
+
import http from "http";
|
|
367
|
+
import path5 from "path";
|
|
368
|
+
import { execFileSync } from "child_process";
|
|
369
|
+
|
|
370
|
+
// src/editor-page.ts
|
|
371
|
+
var EDITOR_PAGE = String.raw`<!doctype html>
|
|
372
|
+
<html lang="en">
|
|
373
|
+
<head>
|
|
374
|
+
<meta charset="utf-8">
|
|
375
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
376
|
+
<title>wp-ide</title>
|
|
377
|
+
<style>
|
|
378
|
+
:root { color-scheme: dark; --bg:#0d1117; --panel:#131a24; --line:#232d3b; --text:#d6dde8; --dim:#7d8aa0; --accent:#6aa7ff; --ok:#3fb950; --bad:#f85149; }
|
|
379
|
+
* { box-sizing: border-box; }
|
|
380
|
+
html, body { margin:0; height:100%; background:var(--bg); color:var(--text); font:13px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; }
|
|
381
|
+
button, select { font:inherit; color:inherit; background:var(--panel); border:1px solid var(--line); border-radius:6px; padding:4px 10px; cursor:pointer; }
|
|
382
|
+
button:hover { border-color:var(--accent); }
|
|
383
|
+
button:disabled { opacity:.5; cursor:default; }
|
|
384
|
+
header { height:42px; display:flex; align-items:center; gap:12px; padding:0 12px; border-bottom:1px solid var(--line); }
|
|
385
|
+
header b { font-size:14px; }
|
|
386
|
+
header .grow { flex:1; }
|
|
387
|
+
.dim { color:var(--dim); }
|
|
388
|
+
main { display:grid; grid-template-columns:230px 260px 1fr; height:calc(100% - 42px); }
|
|
389
|
+
main.with-preview { grid-template-columns:230px 260px 1fr 1fr; }
|
|
390
|
+
nav, .files { border-right:1px solid var(--line); overflow:auto; }
|
|
391
|
+
nav h4 { margin:12px 12px 4px; font-size:11px; text-transform:uppercase; letter-spacing:.06em; color:var(--dim); }
|
|
392
|
+
.item { display:block; width:100%; text-align:left; border:0; border-radius:0; background:none; padding:4px 12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
|
393
|
+
.item:hover { background:#1a2330; }
|
|
394
|
+
.item.active { background:#1d2a3d; color:#fff; }
|
|
395
|
+
.item small { color:var(--dim); margin-left:6px; }
|
|
396
|
+
.warn { color:#d29922; }
|
|
397
|
+
.editor { display:flex; flex-direction:column; min-width:0; }
|
|
398
|
+
.bar { display:flex; align-items:center; gap:8px; padding:6px 10px; border-bottom:1px solid var(--line); min-height:38px; }
|
|
399
|
+
.bar .path { font-family:ui-monospace, Consolas, monospace; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; flex:1; }
|
|
400
|
+
textarea, pre { flex:1; margin:0; width:100%; resize:none; border:0; outline:0; padding:10px 12px; background:var(--bg); color:var(--text); font:12.5px/1.55 ui-monospace, Consolas, monospace; tab-size:4; white-space:pre; overflow:auto; }
|
|
401
|
+
pre .add { color:var(--ok); } pre .del { color:var(--bad); } pre .hunk { color:var(--accent); }
|
|
402
|
+
iframe { width:100%; height:100%; border:0; background:#fff; }
|
|
403
|
+
.preview { display:flex; flex-direction:column; border-left:1px solid var(--line); }
|
|
404
|
+
.preview .frame { flex:1; }
|
|
405
|
+
.empty { padding:24px; color:var(--dim); }
|
|
406
|
+
#status.ok { color:var(--ok); } #status.bad { color:var(--bad); }
|
|
407
|
+
</style>
|
|
408
|
+
</head>
|
|
409
|
+
<body>
|
|
410
|
+
<header>
|
|
411
|
+
<b>wp-ide</b><span class="dim" id="root"></span>
|
|
412
|
+
<span class="grow"></span>
|
|
413
|
+
<span class="dim" id="branch"></span>
|
|
414
|
+
<button id="changes">Changes</button>
|
|
415
|
+
<button id="previewToggle" disabled>Preview</button>
|
|
416
|
+
</header>
|
|
417
|
+
<main id="main">
|
|
418
|
+
<nav id="nav"></nav>
|
|
419
|
+
<div class="files" id="files"><div class="empty">Pick an app, a plugin or the repository.</div></div>
|
|
420
|
+
<section class="editor">
|
|
421
|
+
<div class="bar"><span class="path" id="path">No file open</span><span id="status" class="dim"></span><button id="save" disabled>Save</button></div>
|
|
422
|
+
<textarea id="text" spellcheck="false" disabled></textarea>
|
|
423
|
+
<pre id="diff" hidden></pre>
|
|
424
|
+
</section>
|
|
425
|
+
<section class="preview" id="previewPane" hidden>
|
|
426
|
+
<div class="bar"><span class="path" id="previewUrl"></span><button id="reload">Reload</button></div>
|
|
427
|
+
<div class="frame"><iframe id="frame" title="Preview"></iframe></div>
|
|
428
|
+
</section>
|
|
429
|
+
</main>
|
|
430
|
+
<script>
|
|
431
|
+
(function () {
|
|
432
|
+
var hash = new URLSearchParams(location.hash.slice(1));
|
|
433
|
+
if (hash.get('token')) { sessionStorage.setItem('wp-ide-token', hash.get('token')); history.replaceState(null, '', location.pathname); }
|
|
434
|
+
var token = sessionStorage.getItem('wp-ide-token') || '';
|
|
435
|
+
var $ = function (id) { return document.getElementById(id); };
|
|
436
|
+
var state = null, scope = null, current = null, saved = '';
|
|
437
|
+
|
|
438
|
+
function api(method, url, body) {
|
|
439
|
+
return fetch(url, { method: method, headers: { 'x-wp-ide-token': token, 'content-type': 'application/json' }, body: body ? JSON.stringify(body) : undefined })
|
|
440
|
+
.then(function (r) { return r.json().then(function (d) { if (!r.ok) throw new Error(d.error || ('HTTP ' + r.status)); return d; }); });
|
|
441
|
+
}
|
|
442
|
+
function el(tag, cls, text) { var n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n; }
|
|
443
|
+
function status(text, cls) { var s = $('status'); s.textContent = text; s.className = cls || 'dim'; }
|
|
444
|
+
function dirty() { return current && $('text').value !== saved; }
|
|
445
|
+
|
|
446
|
+
function item(label, hint, warn, onClick) {
|
|
447
|
+
var b = el('button', 'item', label);
|
|
448
|
+
if (hint) b.appendChild(el('small', '', hint));
|
|
449
|
+
if (warn) { b.classList.add('warn'); b.title = warn; }
|
|
450
|
+
b.onclick = function () { document.querySelectorAll('nav .item').forEach(function (n) { n.classList.remove('active'); }); b.classList.add('active'); onClick(); };
|
|
451
|
+
return b;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function renderNav() {
|
|
455
|
+
var nav = $('nav'); nav.textContent = '';
|
|
456
|
+
if (state.layout) {
|
|
457
|
+
state.layout.kinds.forEach(function (kind) {
|
|
458
|
+
nav.appendChild(el('h4', '', kind.label));
|
|
459
|
+
var apps = state.apps.filter(function (a) { return a.kind === kind.key; });
|
|
460
|
+
if (!apps.length) nav.appendChild(el('div', 'item dim', 'none yet'));
|
|
461
|
+
apps.forEach(function (app) {
|
|
462
|
+
nav.appendChild(item(app.slug, '', app.warnings.join('; '), function () { open({ dir: app.path, app: app }); }));
|
|
463
|
+
});
|
|
464
|
+
});
|
|
465
|
+
nav.appendChild(el('h4', '', 'Plugins'));
|
|
466
|
+
if (!state.plugins.length) nav.appendChild(el('div', 'item dim', 'none yet'));
|
|
467
|
+
state.plugins.forEach(function (p) {
|
|
468
|
+
nav.appendChild(item(p.name, p.version, p.warnings.join('; '), function () { open({ dir: p.path }); }));
|
|
469
|
+
});
|
|
470
|
+
} else {
|
|
471
|
+
nav.appendChild(el('div', 'empty', 'No .github/platform.json here. Run "wp-ops init" to make this a platform repository.'));
|
|
472
|
+
}
|
|
473
|
+
nav.appendChild(el('h4', '', 'Repository'));
|
|
474
|
+
nav.appendChild(item('All files', '', '', function () { open({ dir: '' }); }));
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function open(next) {
|
|
478
|
+
if (dirty() && !confirm('Discard unsaved changes to ' + current + '?')) return;
|
|
479
|
+
scope = next; current = null; saved = '';
|
|
480
|
+
$('text').value = ''; $('text').disabled = true; $('save').disabled = true; $('path').textContent = 'No file open'; status('');
|
|
481
|
+
var files = $('files'); files.textContent = ''; files.appendChild(el('div', 'empty', 'Loading…'));
|
|
482
|
+
api('GET', '/api/tree?dir=' + encodeURIComponent(next.dir)).then(function (d) {
|
|
483
|
+
files.textContent = '';
|
|
484
|
+
if (!d.files.length) files.appendChild(el('div', 'empty', 'Empty folder.'));
|
|
485
|
+
d.files.forEach(function (f) {
|
|
486
|
+
var b = el('button', 'item', f);
|
|
487
|
+
b.onclick = function () { openFile(next.dir ? next.dir + '/' + f : f, b); };
|
|
488
|
+
files.appendChild(b);
|
|
489
|
+
});
|
|
490
|
+
}).catch(function (e) { files.textContent = ''; files.appendChild(el('div', 'empty', e.message)); });
|
|
491
|
+
$('previewToggle').disabled = !(state.preview && next.app);
|
|
492
|
+
if (!$('previewPane').hidden) showPreview();
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function openFile(rel, button) {
|
|
496
|
+
if (dirty() && !confirm('Discard unsaved changes to ' + current + '?')) return;
|
|
497
|
+
document.querySelectorAll('.files .item').forEach(function (n) { n.classList.remove('active'); });
|
|
498
|
+
if (button) button.classList.add('active');
|
|
499
|
+
$('diff').hidden = true; $('text').hidden = false;
|
|
500
|
+
api('GET', '/api/file?path=' + encodeURIComponent(rel)).then(function (d) {
|
|
501
|
+
$('path').textContent = d.path;
|
|
502
|
+
if (d.binary || d.tooLarge) {
|
|
503
|
+
current = null; $('text').value = ''; $('text').disabled = true; $('save').disabled = true;
|
|
504
|
+
status(d.binary ? 'Binary file, not editable here.' : 'Larger than 400 KB, not editable here.', 'bad');
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
current = d.path; saved = d.content; $('text').value = d.content; $('text').disabled = false; $('save').disabled = false; status('');
|
|
508
|
+
}).catch(function (e) { status(e.message, 'bad'); });
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function save() {
|
|
512
|
+
if (!current) return;
|
|
513
|
+
var content = $('text').value;
|
|
514
|
+
status('Saving…');
|
|
515
|
+
api('PUT', '/api/file', { path: current, content: content }).then(function () {
|
|
516
|
+
saved = content; status('Saved', 'ok'); refreshGit();
|
|
517
|
+
if (!$('previewPane').hidden) $('frame').src = $('frame').src;
|
|
518
|
+
}).catch(function (e) { status(e.message, 'bad'); });
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function refreshGit() {
|
|
522
|
+
api('GET', '/api/git').then(function (d) { $('branch').textContent = (d.branch ? d.branch + ' · ' : '') + d.status.length + ' changed'; }).catch(function () {});
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function showChanges() {
|
|
526
|
+
api('GET', '/api/diff').then(function (d) {
|
|
527
|
+
var pre = $('diff'); pre.textContent = '';
|
|
528
|
+
(d.diff || 'No changes against HEAD (new untracked files are not shown).').split('\n').forEach(function (line) {
|
|
529
|
+
var cls = line.indexOf('@@') === 0 ? 'hunk' : (line[0] === '+' && line.indexOf('+++') !== 0) ? 'add' : (line[0] === '-' && line.indexOf('---') !== 0) ? 'del' : '';
|
|
530
|
+
pre.appendChild(el('span', cls, line + '\n'));
|
|
531
|
+
});
|
|
532
|
+
$('text').hidden = true; pre.hidden = false; $('path').textContent = 'Changes'; status('');
|
|
533
|
+
}).catch(function (e) { status(e.message, 'bad'); });
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function showPreview() {
|
|
537
|
+
if (!scope || !scope.app || !state.preview) return;
|
|
538
|
+
var url = state.preview + '/' + encodeURIComponent(scope.app.kind) + '/' + encodeURIComponent(scope.app.slug) + '/';
|
|
539
|
+
$('previewUrl').textContent = url; $('frame').src = url;
|
|
540
|
+
$('previewPane').hidden = false; $('main').classList.add('with-preview');
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
$('save').onclick = save;
|
|
544
|
+
$('changes').onclick = showChanges;
|
|
545
|
+
$('reload').onclick = function () { $('frame').src = $('frame').src; };
|
|
546
|
+
$('previewToggle').onclick = function () {
|
|
547
|
+
if ($('previewPane').hidden) showPreview();
|
|
548
|
+
else { $('previewPane').hidden = true; $('main').classList.remove('with-preview'); $('frame').src = 'about:blank'; }
|
|
549
|
+
};
|
|
550
|
+
$('text').addEventListener('input', function () { status(dirty() ? 'Unsaved' : ''); });
|
|
551
|
+
$('text').addEventListener('keydown', function (e) {
|
|
552
|
+
if (e.key === 'Tab') { e.preventDefault(); var t = e.target, s = t.selectionStart; t.setRangeText('\t', s, t.selectionEnd, 'end'); status('Unsaved'); }
|
|
553
|
+
});
|
|
554
|
+
window.addEventListener('keydown', function (e) { if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') { e.preventDefault(); save(); } });
|
|
555
|
+
window.addEventListener('beforeunload', function (e) { if (dirty()) { e.preventDefault(); e.returnValue = ''; } });
|
|
556
|
+
|
|
557
|
+
api('GET', '/api/state').then(function (d) {
|
|
558
|
+
state = d; $('root').textContent = d.root; renderNav(); refreshGit();
|
|
559
|
+
}).catch(function (e) { $('nav').appendChild(el('div', 'empty', e.message)); });
|
|
560
|
+
})();
|
|
561
|
+
</script>
|
|
562
|
+
</body>
|
|
563
|
+
</html>
|
|
564
|
+
`;
|
|
565
|
+
|
|
566
|
+
// src/editor.ts
|
|
567
|
+
var MAX_FILE_BYTES = 4e5;
|
|
568
|
+
var MAX_TREE_ENTRIES = 5e3;
|
|
569
|
+
var BLOCKED_SEGMENTS = /* @__PURE__ */ new Set([".git", "node_modules", "vendor", ".local"]);
|
|
570
|
+
var HttpError = class extends Error {
|
|
571
|
+
constructor(status, message) {
|
|
572
|
+
super(message);
|
|
573
|
+
this.status = status;
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
function realRoot(root) {
|
|
577
|
+
return fs4.realpathSync.native(path5.resolve(root));
|
|
578
|
+
}
|
|
579
|
+
function safePath(root, rel) {
|
|
580
|
+
const clean = String(rel ?? "").replace(/\\/g, "/").replace(/^\/+/, "");
|
|
581
|
+
const parts = clean.split("/").filter(Boolean);
|
|
582
|
+
if (parts.some((part) => part === ".." || part.includes(":") || BLOCKED_SEGMENTS.has(part))) {
|
|
583
|
+
throw new HttpError(403, `Not allowed: ${clean}`);
|
|
584
|
+
}
|
|
585
|
+
const target = path5.resolve(root, ...parts);
|
|
586
|
+
const inside = (candidate) => candidate === root || candidate.startsWith(root + path5.sep);
|
|
587
|
+
if (!inside(target)) {
|
|
588
|
+
throw new HttpError(403, `Outside the repository: ${clean}`);
|
|
589
|
+
}
|
|
590
|
+
let probe = target;
|
|
591
|
+
while (!fs4.existsSync(probe)) {
|
|
592
|
+
probe = path5.dirname(probe);
|
|
593
|
+
}
|
|
594
|
+
if (!inside(fs4.realpathSync.native(probe))) {
|
|
595
|
+
throw new HttpError(403, `Outside the repository: ${clean}`);
|
|
596
|
+
}
|
|
597
|
+
return target;
|
|
598
|
+
}
|
|
599
|
+
function toRel(root, file) {
|
|
600
|
+
return path5.relative(root, file).split(path5.sep).join("/");
|
|
601
|
+
}
|
|
602
|
+
function listTree(root, dirRel) {
|
|
603
|
+
const start = safePath(root, dirRel);
|
|
604
|
+
if (!fs4.existsSync(start) || !fs4.statSync(start).isDirectory()) {
|
|
605
|
+
throw new HttpError(404, `Not a folder: ${dirRel}`);
|
|
606
|
+
}
|
|
607
|
+
const files = [];
|
|
608
|
+
const walk = (dir) => {
|
|
609
|
+
const entries = fs4.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
610
|
+
for (const entry of entries) {
|
|
611
|
+
if (files.length >= MAX_TREE_ENTRIES) return;
|
|
612
|
+
if (BLOCKED_SEGMENTS.has(entry.name)) continue;
|
|
613
|
+
const full = path5.join(dir, entry.name);
|
|
614
|
+
if (entry.isDirectory()) walk(full);
|
|
615
|
+
else if (entry.isFile()) files.push(toRel(start, full));
|
|
616
|
+
}
|
|
617
|
+
};
|
|
618
|
+
walk(start);
|
|
619
|
+
return files;
|
|
620
|
+
}
|
|
621
|
+
function isBinary(buffer) {
|
|
622
|
+
return buffer.subarray(0, 8e3).includes(0);
|
|
623
|
+
}
|
|
624
|
+
function git(root, args) {
|
|
625
|
+
try {
|
|
626
|
+
return execFileSync("git", args, {
|
|
627
|
+
cwd: root,
|
|
628
|
+
encoding: "utf8",
|
|
629
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
630
|
+
maxBuffer: 16 * 1024 * 1024
|
|
631
|
+
});
|
|
632
|
+
} catch {
|
|
633
|
+
return "";
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
function readBody(req) {
|
|
637
|
+
return new Promise((resolve, reject) => {
|
|
638
|
+
const chunks = [];
|
|
639
|
+
let size = 0;
|
|
640
|
+
req.on("data", (chunk) => {
|
|
641
|
+
size += chunk.length;
|
|
642
|
+
if (size > MAX_FILE_BYTES * 2 + 4096) {
|
|
643
|
+
reject(new HttpError(413, "Request too large."));
|
|
644
|
+
req.destroy();
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
chunks.push(chunk);
|
|
648
|
+
});
|
|
649
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
650
|
+
req.on("error", reject);
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
function send(res, status, body) {
|
|
654
|
+
const text = typeof body === "string" ? body : JSON.stringify(body);
|
|
655
|
+
res.writeHead(status, {
|
|
656
|
+
"Content-Type": typeof body === "string" ? "text/html; charset=utf-8" : "application/json",
|
|
657
|
+
"Cache-Control": "no-store",
|
|
658
|
+
"X-Content-Type-Options": "nosniff",
|
|
659
|
+
"Referrer-Policy": "no-referrer"
|
|
660
|
+
});
|
|
661
|
+
res.end(text);
|
|
662
|
+
}
|
|
663
|
+
function state(root, preview) {
|
|
664
|
+
const layout = hasLayout(root) ? readLayout(root) : null;
|
|
665
|
+
return {
|
|
666
|
+
root,
|
|
667
|
+
preview,
|
|
668
|
+
layout,
|
|
669
|
+
apps: layout ? listApps(root, layout).map(({ dir, ...app }) => app) : [],
|
|
670
|
+
plugins: layout ? listPlugins(root, layout).map(({ dir, ...plugin }) => plugin) : [],
|
|
671
|
+
branch: git(root, ["rev-parse", "--abbrev-ref", "HEAD"]).trim()
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
function startEditor(options = {}) {
|
|
675
|
+
const root = realRoot(findRootDir(options.root ?? process.cwd()));
|
|
676
|
+
const host = "127.0.0.1";
|
|
677
|
+
const token = options.token ?? crypto.randomBytes(24).toString("hex");
|
|
678
|
+
const preview = (options.preview ?? "").replace(/\/+$/, "");
|
|
679
|
+
const tokenBuffer = Buffer.from(token);
|
|
680
|
+
const server = http.createServer(async (req, res) => {
|
|
681
|
+
try {
|
|
682
|
+
const address = server.address();
|
|
683
|
+
const port = typeof address === "object" && address ? address.port : 0;
|
|
684
|
+
const allowedHosts = [`127.0.0.1:${port}`, `localhost:${port}`];
|
|
685
|
+
if (!allowedHosts.includes(String(req.headers.host ?? ""))) {
|
|
686
|
+
throw new HttpError(421, "Unknown host.");
|
|
687
|
+
}
|
|
688
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
|
|
689
|
+
if (url.pathname === "/" && req.method === "GET") {
|
|
690
|
+
send(res, 200, EDITOR_PAGE);
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
if (!url.pathname.startsWith("/api/")) {
|
|
694
|
+
throw new HttpError(404, "Not found.");
|
|
695
|
+
}
|
|
696
|
+
const given = Buffer.from(String(req.headers["x-wp-ide-token"] ?? ""));
|
|
697
|
+
if (given.length !== tokenBuffer.length || !crypto.timingSafeEqual(given, tokenBuffer)) {
|
|
698
|
+
throw new HttpError(401, "Missing or wrong token. Open the URL printed by wp-ide serve.");
|
|
699
|
+
}
|
|
700
|
+
const route = `${req.method} ${url.pathname}`;
|
|
701
|
+
switch (route) {
|
|
702
|
+
case "GET /api/state":
|
|
703
|
+
send(res, 200, state(root, preview));
|
|
704
|
+
return;
|
|
705
|
+
case "GET /api/tree":
|
|
706
|
+
send(res, 200, { files: listTree(root, url.searchParams.get("dir") ?? "") });
|
|
707
|
+
return;
|
|
708
|
+
case "GET /api/file": {
|
|
709
|
+
const rel = url.searchParams.get("path") ?? "";
|
|
710
|
+
const file = safePath(root, rel);
|
|
711
|
+
if (!fs4.existsSync(file) || !fs4.statSync(file).isFile()) {
|
|
712
|
+
throw new HttpError(404, `No such file: ${rel}`);
|
|
713
|
+
}
|
|
714
|
+
const buffer = fs4.readFileSync(file);
|
|
715
|
+
const binary = isBinary(buffer);
|
|
716
|
+
const tooLarge = buffer.length > MAX_FILE_BYTES;
|
|
717
|
+
send(res, 200, {
|
|
718
|
+
path: toRel(root, file),
|
|
719
|
+
size: buffer.length,
|
|
720
|
+
binary,
|
|
721
|
+
tooLarge,
|
|
722
|
+
content: binary || tooLarge ? "" : buffer.toString("utf8")
|
|
723
|
+
});
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
case "PUT /api/file": {
|
|
727
|
+
let input;
|
|
728
|
+
try {
|
|
729
|
+
input = JSON.parse(await readBody(req));
|
|
730
|
+
} catch {
|
|
731
|
+
throw new HttpError(400, 'Send JSON: {"path": "...", "content": "..."}');
|
|
732
|
+
}
|
|
733
|
+
if (typeof input?.path !== "string" || typeof input?.content !== "string") {
|
|
734
|
+
throw new HttpError(400, 'Send JSON: {"path": "...", "content": "..."}');
|
|
735
|
+
}
|
|
736
|
+
const file = safePath(root, input.path);
|
|
737
|
+
if (file === root) {
|
|
738
|
+
throw new HttpError(400, "Give a file path.");
|
|
739
|
+
}
|
|
740
|
+
if (Buffer.byteLength(input.content) > MAX_FILE_BYTES) {
|
|
741
|
+
throw new HttpError(413, `Files are limited to ${MAX_FILE_BYTES} bytes.`);
|
|
742
|
+
}
|
|
743
|
+
if (fs4.existsSync(file) && !fs4.statSync(file).isFile()) {
|
|
744
|
+
throw new HttpError(409, "That path is a folder.");
|
|
745
|
+
}
|
|
746
|
+
fs4.mkdirSync(path5.dirname(file), { recursive: true });
|
|
747
|
+
fs4.writeFileSync(file, input.content);
|
|
748
|
+
send(res, 200, { ok: true, path: toRel(root, file) });
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
case "GET /api/git":
|
|
752
|
+
send(res, 200, {
|
|
753
|
+
branch: git(root, ["rev-parse", "--abbrev-ref", "HEAD"]).trim(),
|
|
754
|
+
status: git(root, ["status", "--porcelain=v1"]).split("\n").filter(Boolean)
|
|
755
|
+
});
|
|
756
|
+
return;
|
|
757
|
+
case "GET /api/diff": {
|
|
758
|
+
const rel = url.searchParams.get("path") ?? "";
|
|
759
|
+
const args = ["diff", "--no-color", "HEAD"];
|
|
760
|
+
if (rel) args.push("--", toRel(root, safePath(root, rel)));
|
|
761
|
+
send(res, 200, { diff: git(root, args) });
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
default:
|
|
765
|
+
throw new HttpError(404, "Not found.");
|
|
766
|
+
}
|
|
767
|
+
} catch (error) {
|
|
768
|
+
const status = error instanceof HttpError ? error.status : 500;
|
|
769
|
+
send(res, status, { error: error.message });
|
|
770
|
+
}
|
|
771
|
+
});
|
|
772
|
+
return new Promise((resolve, reject) => {
|
|
773
|
+
server.once("error", reject);
|
|
774
|
+
server.listen(options.port ?? 4500, host, () => {
|
|
775
|
+
const address = server.address();
|
|
776
|
+
const port = typeof address === "object" && address ? address.port : 0;
|
|
777
|
+
resolve({
|
|
778
|
+
url: `http://${host}:${port}/#token=${token}`,
|
|
779
|
+
port,
|
|
780
|
+
token,
|
|
781
|
+
root,
|
|
782
|
+
close: () => new Promise((done) => {
|
|
783
|
+
server.closeAllConnections?.();
|
|
784
|
+
server.close(() => done());
|
|
785
|
+
})
|
|
786
|
+
});
|
|
787
|
+
});
|
|
788
|
+
});
|
|
789
|
+
}
|
|
136
790
|
export {
|
|
791
|
+
APP_TYPE,
|
|
792
|
+
COMPOSER_ACTIONS,
|
|
137
793
|
CONFIG_FILENAME,
|
|
794
|
+
DEFAULT_KINDS,
|
|
795
|
+
LAYOUT_FILE,
|
|
138
796
|
LOCAL_DIR,
|
|
797
|
+
MAX_FILE_BYTES,
|
|
798
|
+
PACKAGE_NAME,
|
|
799
|
+
PLUGIN_TYPE,
|
|
139
800
|
ROOT_MARKERS,
|
|
140
801
|
appServerOptions,
|
|
802
|
+
editComposer,
|
|
803
|
+
encodeJson,
|
|
141
804
|
ensureLocalDir,
|
|
805
|
+
findKind,
|
|
142
806
|
findRootDir,
|
|
807
|
+
folder,
|
|
808
|
+
hasLayout,
|
|
809
|
+
layoutJson,
|
|
810
|
+
listApps,
|
|
811
|
+
listPlugins,
|
|
143
812
|
localPath,
|
|
813
|
+
normalizeLayout,
|
|
814
|
+
readJson,
|
|
815
|
+
readLayout,
|
|
816
|
+
readManifest,
|
|
817
|
+
relativePath,
|
|
144
818
|
resolveProject,
|
|
145
819
|
runBlueprint,
|
|
146
|
-
|
|
820
|
+
safePath,
|
|
821
|
+
slug,
|
|
822
|
+
startEditor,
|
|
823
|
+
useLocalData,
|
|
824
|
+
writeJson,
|
|
825
|
+
writeManifest
|
|
147
826
|
};
|