@innovatorved/code-lab 0.1.6 → 0.1.8
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/ARCHITECTURE.md +34 -16
- package/README.md +17 -7
- package/dist/code-lab.css +26 -0
- package/dist/code-lab.d.ts +271 -1
- package/dist/code-lab.esm.js +2909 -166
- package/dist/code-lab.js +2869 -164
- package/dist/csp.d.ts +86 -0
- package/dist/diagnostics.d.ts +43 -0
- package/dist/extensions/guided-lab.esm.js +66 -0
- package/dist/extensions/guided-lab.js +66 -0
- package/dist/html.d.ts +24 -0
- package/dist/index.d.ts +9 -1
- package/dist/logger.d.ts +60 -0
- package/dist/preview-sw.js +425 -11
- package/dist/runtime.d.ts +6 -27
- package/dist/runtime.esm.js +171 -31
- package/dist/runtime.js +171 -31
- package/dist/schemas.d.ts +366 -25
- package/dist/schemas.esm.js +73 -0
- package/dist/schemas.js +73 -0
- package/dist/scm.d.ts +77 -0
- package/dist/search.d.ts +75 -0
- package/dist/shell.d.ts +18 -47
- package/dist/shell.esm.js +236 -37
- package/dist/shell.js +236 -37
- package/dist/storage.d.ts +57 -0
- package/dist/terminal.d.ts +11 -87
- package/dist/terminal.esm.js +124 -7
- package/dist/terminal.js +124 -7
- package/dist/zip.d.ts +42 -0
- package/package.json +11 -3
- package/src/code-lab.css +26 -0
- package/src/csp.ts +396 -0
- package/src/diagnostics.ts +116 -0
- package/src/html.ts +88 -0
- package/src/index.ts +39 -1
- package/src/logger.ts +139 -0
- package/src/preview-sw.js +97 -11
- package/src/runtime.ts +132 -105
- package/src/schemas.ts +94 -1
- package/src/scm.ts +268 -0
- package/src/search.ts +389 -0
- package/src/shell.ts +410 -369
- package/src/storage.ts +377 -0
- package/src/terminal.ts +898 -918
- package/src/workbench.ts +926 -89
- package/src/zip.ts +326 -0
- package/src/runtime.js +0 -8229
- package/src/shell.js +0 -7257
- package/src/terminal.js +0 -1046
- package/src/workbench.js +0 -7353
package/dist/preview-sw.js
CHANGED
|
@@ -1,3 +1,331 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ============================================================
|
|
3
|
+
* @innovatorved/code-lab v0.1.8 — Standalone Browser Code IDE & Virtual Runtime
|
|
4
|
+
* ============================================================
|
|
5
|
+
* Features:
|
|
6
|
+
* - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
|
|
7
|
+
* - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
|
|
8
|
+
* - Full POSIX Shell AST & 55+ UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
|
|
9
|
+
* - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
|
|
10
|
+
* - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
|
|
11
|
+
* - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
|
|
12
|
+
* - Modular Opt-In Guided Lab Extension (stepper, hints, solution diff, JS/TS switcher)
|
|
13
|
+
* - Zero-Auth Public GitHub Repository Cloning (git clone, workbench.cloneRepo, <code-lab repo="...">)
|
|
14
|
+
* - Third-Party Imperative SDK (getFiles, setFiles, getFile, setFile, cloneRepo, on, off, use, exportWorkspace)
|
|
15
|
+
* ============================================================
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
var CodeLabCsp = (() => {
|
|
19
|
+
var __defProp = Object.defineProperty;
|
|
20
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
21
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
22
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
23
|
+
var __export = (target, all) => {
|
|
24
|
+
for (var name in all)
|
|
25
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
26
|
+
};
|
|
27
|
+
var __copyProps = (to, from, except, desc) => {
|
|
28
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
29
|
+
for (let key of __getOwnPropNames(from))
|
|
30
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
31
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
32
|
+
}
|
|
33
|
+
return to;
|
|
34
|
+
};
|
|
35
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
36
|
+
|
|
37
|
+
// src/csp.ts
|
|
38
|
+
var csp_exports = {};
|
|
39
|
+
__export(csp_exports, {
|
|
40
|
+
PREVIEW_SHIM_MARKER: () => PREVIEW_SHIM_MARKER,
|
|
41
|
+
buildPreviewPolicy: () => buildPreviewPolicy,
|
|
42
|
+
buildPreviewShims: () => buildPreviewShims,
|
|
43
|
+
default: () => csp_default,
|
|
44
|
+
describePreviewNetwork: () => describePreviewNetwork,
|
|
45
|
+
normalizeOrigin: () => normalizeOrigin,
|
|
46
|
+
normalizePreviewCspConfig: () => normalizePreviewCspConfig
|
|
47
|
+
});
|
|
48
|
+
var IMPORT_MAP_CDNS = ["https://cdn.jsdelivr.net", "https://esm.sh"];
|
|
49
|
+
var FONT_CDNS = ["https://cdn.jsdelivr.net", "https://fonts.gstatic.com"];
|
|
50
|
+
var PRESETS = {
|
|
51
|
+
strict: {},
|
|
52
|
+
balanced: {
|
|
53
|
+
scriptSrc: IMPORT_MAP_CDNS.slice(),
|
|
54
|
+
styleSrc: ["https://cdn.jsdelivr.net", "https://fonts.googleapis.com"],
|
|
55
|
+
fontSrc: FONT_CDNS.slice(),
|
|
56
|
+
connectSrc: IMPORT_MAP_CDNS.slice(),
|
|
57
|
+
imgSrc: ["https://cdn.jsdelivr.net"]
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
var SOURCE_KEYS = [
|
|
61
|
+
"scriptSrc",
|
|
62
|
+
"styleSrc",
|
|
63
|
+
"imgSrc",
|
|
64
|
+
"fontSrc",
|
|
65
|
+
"connectSrc",
|
|
66
|
+
"mediaSrc",
|
|
67
|
+
"workerSrc",
|
|
68
|
+
"frameSrc"
|
|
69
|
+
];
|
|
70
|
+
var MAX_SOURCES = 64;
|
|
71
|
+
var MAX_SOURCE_LENGTH = 512;
|
|
72
|
+
var PREVIEW_SHIM_MARKER = "data-codelab-preview-shims";
|
|
73
|
+
function normalizeOrigin(raw) {
|
|
74
|
+
if (raw === null || raw === void 0 || raw === "") return null;
|
|
75
|
+
try {
|
|
76
|
+
const parsed = new URL(String(raw));
|
|
77
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
|
|
78
|
+
return parsed.origin;
|
|
79
|
+
} catch (_) {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function normalizeMode(raw) {
|
|
84
|
+
if (raw === "strict" || raw === "custom") return raw;
|
|
85
|
+
return "balanced";
|
|
86
|
+
}
|
|
87
|
+
var ALLOWED_KEYWORDS = [
|
|
88
|
+
"'self'",
|
|
89
|
+
"'none'",
|
|
90
|
+
"'unsafe-inline'",
|
|
91
|
+
"'unsafe-eval'",
|
|
92
|
+
"'wasm-unsafe-eval'",
|
|
93
|
+
"'strict-dynamic'",
|
|
94
|
+
"'unsafe-hashes'"
|
|
95
|
+
];
|
|
96
|
+
var SOURCE_PATTERN = /^(?:https?:\/\/[A-Za-z0-9._~%-]+(?::\d{1,5})?(?:\/[^\s;,'"]*)?|data:|blob:|filesystem:)$/;
|
|
97
|
+
function isSafeSource(source) {
|
|
98
|
+
return ALLOWED_KEYWORDS.indexOf(source) !== -1 || SOURCE_PATTERN.test(source);
|
|
99
|
+
}
|
|
100
|
+
function cleanSources(raw) {
|
|
101
|
+
if (!Array.isArray(raw)) return [];
|
|
102
|
+
const out = [];
|
|
103
|
+
for (const value of raw.slice(0, MAX_SOURCES)) {
|
|
104
|
+
if (typeof value !== "string") continue;
|
|
105
|
+
const source = value.trim();
|
|
106
|
+
if (!source || source.length > MAX_SOURCE_LENGTH) continue;
|
|
107
|
+
if (!isSafeSource(source)) continue;
|
|
108
|
+
if (out.indexOf(source) === -1) out.push(source);
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
function unique(...lists) {
|
|
113
|
+
const out = [];
|
|
114
|
+
for (const list of lists) {
|
|
115
|
+
if (!list) continue;
|
|
116
|
+
for (const value of list) {
|
|
117
|
+
if (value && out.indexOf(value) === -1) out.push(value);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
function normalizePreviewCspConfig(raw) {
|
|
123
|
+
if (typeof raw === "string") return { mode: normalizeMode(raw), allow: {} };
|
|
124
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
125
|
+
return { mode: "balanced", allow: {} };
|
|
126
|
+
}
|
|
127
|
+
const input = raw;
|
|
128
|
+
const nested = input.allow;
|
|
129
|
+
const sources = nested && typeof nested === "object" && !Array.isArray(nested) ? nested : input;
|
|
130
|
+
const allow = {};
|
|
131
|
+
for (const key of SOURCE_KEYS) {
|
|
132
|
+
const list = cleanSources(sources[key]);
|
|
133
|
+
if (list.length) allow[key] = list;
|
|
134
|
+
}
|
|
135
|
+
return { mode: normalizeMode(input.mode), allow };
|
|
136
|
+
}
|
|
137
|
+
function sourcesFor(mode, allow, key) {
|
|
138
|
+
const preset = mode === "custom" ? {} : PRESETS[mode];
|
|
139
|
+
return unique(preset[key], cleanSources(allow[key]));
|
|
140
|
+
}
|
|
141
|
+
function buildPreviewPolicy(options = {}) {
|
|
142
|
+
const mode = normalizeMode(options.mode);
|
|
143
|
+
const allow = options;
|
|
144
|
+
const host = normalizeOrigin(options.hostOrigin);
|
|
145
|
+
const self = host || "'self'";
|
|
146
|
+
const directive = (name, parts) => `${name} ${unique(parts).join(" ")}`;
|
|
147
|
+
const script = () => [self, "blob:", "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, "scriptSrc"));
|
|
148
|
+
const style = () => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, "styleSrc"));
|
|
149
|
+
const withData = (key) => [self, "data:", "blob:"].concat(sourcesFor(mode, allow, key));
|
|
150
|
+
return [
|
|
151
|
+
directive("default-src", [self, "data:", "blob:"]),
|
|
152
|
+
directive("base-uri", [self]),
|
|
153
|
+
"object-src 'none'",
|
|
154
|
+
directive("script-src", script()),
|
|
155
|
+
directive("style-src", style()),
|
|
156
|
+
directive("img-src", withData("imgSrc")),
|
|
157
|
+
directive("font-src", [self, "data:"].concat(sourcesFor(mode, allow, "fontSrc"))),
|
|
158
|
+
directive("connect-src", withData("connectSrc")),
|
|
159
|
+
directive("media-src", withData("mediaSrc")),
|
|
160
|
+
directive("worker-src", [self, "blob:"].concat(sourcesFor(mode, allow, "workerSrc"))),
|
|
161
|
+
directive("frame-src", withData("frameSrc")),
|
|
162
|
+
directive("form-action", [self]),
|
|
163
|
+
directive("frame-ancestors", [options.frameAncestors || "'self'"])
|
|
164
|
+
].join("; ");
|
|
165
|
+
}
|
|
166
|
+
function describePreviewNetwork(config) {
|
|
167
|
+
const normalized = normalizePreviewCspConfig(config);
|
|
168
|
+
if (normalized.mode === "strict") return [];
|
|
169
|
+
const preset = normalized.mode === "custom" ? {} : PRESETS[normalized.mode];
|
|
170
|
+
const hosts = [];
|
|
171
|
+
for (const key of ["scriptSrc", "connectSrc", "imgSrc", "styleSrc", "fontSrc"]) {
|
|
172
|
+
for (const source of unique(preset[key], normalized.allow[key])) {
|
|
173
|
+
if (!/^https?:\/\//i.test(source)) continue;
|
|
174
|
+
let host;
|
|
175
|
+
try {
|
|
176
|
+
host = new URL(source).host;
|
|
177
|
+
} catch (_) {
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (hosts.indexOf(host) === -1) hosts.push(host);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return hosts;
|
|
184
|
+
}
|
|
185
|
+
function buildPreviewShims() {
|
|
186
|
+
return `<script ${PREVIEW_SHIM_MARKER}>
|
|
187
|
+
(function () {
|
|
188
|
+
'use strict';
|
|
189
|
+
function memoryStorage() {
|
|
190
|
+
var data = new Map();
|
|
191
|
+
return {
|
|
192
|
+
getItem: function (k) { k = String(k); return data.has(k) ? data.get(k) : null; },
|
|
193
|
+
setItem: function (k, v) { data.set(String(k), String(v)); },
|
|
194
|
+
removeItem: function (k) { data.delete(String(k)); },
|
|
195
|
+
clear: function () { data.clear(); },
|
|
196
|
+
key: function (i) { return Array.from(data.keys())[i] || null; },
|
|
197
|
+
get length() { return data.size; }
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
function shim(name) {
|
|
201
|
+
var blocked = false;
|
|
202
|
+
try {
|
|
203
|
+
var existing = window[name];
|
|
204
|
+
if (existing) { existing.getItem('__codelab_probe__'); return; }
|
|
205
|
+
} catch (err) {
|
|
206
|
+
// Expected on an opaque origin: the accessor itself throws.
|
|
207
|
+
blocked = Boolean(err);
|
|
208
|
+
}
|
|
209
|
+
void blocked;
|
|
210
|
+
try {
|
|
211
|
+
Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
|
|
212
|
+
} catch (err) {
|
|
213
|
+
console.warn('[code-lab] preview: unable to shim ' + name, err);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
shim('localStorage');
|
|
217
|
+
shim('sessionStorage');
|
|
218
|
+
document.addEventListener('securitypolicyviolation', function (event) {
|
|
219
|
+
try {
|
|
220
|
+
parent.postMessage({
|
|
221
|
+
type: 'codelab:preview-violation',
|
|
222
|
+
directive: event.effectiveDirective || event.violatedDirective || '',
|
|
223
|
+
blockedURI: event.blockedURI || '',
|
|
224
|
+
sourceFile: event.sourceFile || '',
|
|
225
|
+
line: event.lineNumber || 0
|
|
226
|
+
}, '*');
|
|
227
|
+
} catch (err) {
|
|
228
|
+
console.warn('[code-lab] preview: could not report CSP violation', err);
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
function serializeArg(arg) {
|
|
232
|
+
if (typeof arg !== 'object' || arg === null) return String(arg);
|
|
233
|
+
try {
|
|
234
|
+
return JSON.stringify(arg);
|
|
235
|
+
} catch (err) {
|
|
236
|
+
void err;
|
|
237
|
+
return '[Circular/Unserializable]';
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
['log', 'warn', 'error', 'info'].forEach(function (level) {
|
|
241
|
+
var orig = console[level];
|
|
242
|
+
if (typeof orig !== 'function') return;
|
|
243
|
+
console[level] = function () {
|
|
244
|
+
var args = Array.prototype.slice.call(arguments);
|
|
245
|
+
try {
|
|
246
|
+
parent.postMessage({
|
|
247
|
+
type: 'codelab:preview-console',
|
|
248
|
+
level: level,
|
|
249
|
+
args: args.map(serializeArg)
|
|
250
|
+
}, '*');
|
|
251
|
+
} catch (err) {
|
|
252
|
+
void err;
|
|
253
|
+
}
|
|
254
|
+
return orig.apply(console, args);
|
|
255
|
+
};
|
|
256
|
+
});
|
|
257
|
+
function showPreviewErrorOverlay(msg, stack) {
|
|
258
|
+
try {
|
|
259
|
+
if (!document || !document.body) return;
|
|
260
|
+
var existing = document.getElementById('codelab-preview-error-overlay');
|
|
261
|
+
if (!existing) {
|
|
262
|
+
existing = document.createElement('div');
|
|
263
|
+
existing.id = 'codelab-preview-error-overlay';
|
|
264
|
+
existing.style.cssText = 'position:fixed;inset:0;z-index:2147483647;background:rgba(15,23,42,0.94);color:#f8fafc;font-family:ui-monospace,monospace;padding:24px;overflow:auto;';
|
|
265
|
+
document.body.appendChild(existing);
|
|
266
|
+
}
|
|
267
|
+
existing.textContent = '';
|
|
268
|
+
var header = document.createElement('div');
|
|
269
|
+
header.style.cssText = 'color:#f87171;font-weight:700;font-size:15px;margin-bottom:12px;';
|
|
270
|
+
header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
|
|
271
|
+
var pre = document.createElement('pre');
|
|
272
|
+
pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
|
|
273
|
+
pre.textContent = String(stack || msg || '');
|
|
274
|
+
existing.appendChild(header);
|
|
275
|
+
existing.appendChild(pre);
|
|
276
|
+
} catch (err) {
|
|
277
|
+
void err;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
window.addEventListener('error', function (event) {
|
|
281
|
+
var msg = (event && event.message) ? event.message : 'Uncaught runtime error';
|
|
282
|
+
var stack = (event && event.error && event.error.stack) ? String(event.error.stack) : '';
|
|
283
|
+
showPreviewErrorOverlay(msg, stack);
|
|
284
|
+
try {
|
|
285
|
+
parent.postMessage({
|
|
286
|
+
type: 'codelab:preview-error',
|
|
287
|
+
message: msg,
|
|
288
|
+
file: (event && event.filename) || null,
|
|
289
|
+
line: (event && event.lineno) || null,
|
|
290
|
+
col: (event && event.colno) || null,
|
|
291
|
+
stack: stack || null
|
|
292
|
+
}, '*');
|
|
293
|
+
} catch (err) {
|
|
294
|
+
void err;
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
window.addEventListener('unhandledrejection', function (event) {
|
|
298
|
+
var reason = event ? event.reason : null;
|
|
299
|
+
var msg = reason && reason.message ? String(reason.message) : String(reason || 'Unhandled Promise Rejection');
|
|
300
|
+
var stack = reason && reason.stack ? String(reason.stack) : '';
|
|
301
|
+
showPreviewErrorOverlay(msg, stack);
|
|
302
|
+
try {
|
|
303
|
+
parent.postMessage({
|
|
304
|
+
type: 'codelab:preview-error',
|
|
305
|
+
message: msg,
|
|
306
|
+
file: null,
|
|
307
|
+
line: null,
|
|
308
|
+
col: null,
|
|
309
|
+
stack: stack || null
|
|
310
|
+
}, '*');
|
|
311
|
+
} catch (err) {
|
|
312
|
+
void err;
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
})();
|
|
316
|
+
<\/script>`;
|
|
317
|
+
}
|
|
318
|
+
var csp_default = {
|
|
319
|
+
buildPreviewPolicy,
|
|
320
|
+
buildPreviewShims,
|
|
321
|
+
describePreviewNetwork,
|
|
322
|
+
normalizePreviewCspConfig,
|
|
323
|
+
normalizeOrigin,
|
|
324
|
+
PREVIEW_SHIM_MARKER
|
|
325
|
+
};
|
|
326
|
+
return __toCommonJS(csp_exports);
|
|
327
|
+
})();
|
|
328
|
+
|
|
1
329
|
/**
|
|
2
330
|
* @innovatorved/code-lab — Web Preview Virtual Loopback Service Worker (Milestone 3)
|
|
3
331
|
* ============================================================================
|
|
@@ -8,6 +336,10 @@
|
|
|
8
336
|
* This enables "pop out to tab" Web Preview for virtual HTTP / Bun servers that
|
|
9
337
|
* exist only inside the workbench's in-memory runtime (no real OS socket).
|
|
10
338
|
*
|
|
339
|
+
* The Content-Security-Policy, the storage shims and the violation reporter all
|
|
340
|
+
* come from `src/csp.ts`, which the build prepends to this file. The workbench
|
|
341
|
+
* embeds the same module, so the two can never drift.
|
|
342
|
+
*
|
|
11
343
|
* Zero dependencies. Plain Service Worker script (no module imports) so it can
|
|
12
344
|
* be registered directly from any host origin.
|
|
13
345
|
*/
|
|
@@ -16,6 +348,32 @@
|
|
|
16
348
|
|
|
17
349
|
const PREVIEW_PREFIX = '/__preview/';
|
|
18
350
|
const DISPATCH_TIMEOUT_MS = 15000;
|
|
351
|
+
const MAX_CONFIG_LENGTH = 8192;
|
|
352
|
+
|
|
353
|
+
// Policy configured by the workbench via postMessage. The worker cannot read the
|
|
354
|
+
// host's options, so the host pushes the resolved policy after registering.
|
|
355
|
+
let configuredCsp = null;
|
|
356
|
+
|
|
357
|
+
function cspModule() {
|
|
358
|
+
// `CodeLabCsp` is declared by the prepended csp bundle (src/csp.ts).
|
|
359
|
+
return typeof CodeLabCsp !== 'undefined' ? CodeLabCsp : null;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function previewPolicy() {
|
|
363
|
+
if (configuredCsp) return configuredCsp;
|
|
364
|
+
const csp = cspModule();
|
|
365
|
+
if (!csp) return "default-src 'self'; object-src 'none'";
|
|
366
|
+
// The workbench pushes its resolved policy on registration, so this branch
|
|
367
|
+
// only runs in the brief window before that message arrives. Use the
|
|
368
|
+
// documented default (`balanced`) rather than a stricter one, otherwise the
|
|
369
|
+
// very first preview of a CDN-based app can be blocked by a race.
|
|
370
|
+
return csp.buildPreviewPolicy({ hostOrigin: self.location.origin, mode: 'balanced' });
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function previewShims() {
|
|
374
|
+
const csp = cspModule();
|
|
375
|
+
return csp ? csp.buildPreviewShims() : '';
|
|
376
|
+
}
|
|
19
377
|
|
|
20
378
|
self.addEventListener('install', () => {
|
|
21
379
|
self.skipWaiting();
|
|
@@ -25,6 +383,25 @@ self.addEventListener('activate', (event) => {
|
|
|
25
383
|
event.waitUntil(self.clients.claim());
|
|
26
384
|
});
|
|
27
385
|
|
|
386
|
+
self.addEventListener('message', (event) => {
|
|
387
|
+
const data = event && event.data;
|
|
388
|
+
if (!data || data.type !== 'codelab:config') return;
|
|
389
|
+
const csp = typeof data.csp === 'string' ? data.csp.trim() : '';
|
|
390
|
+
if (!csp || csp.length > MAX_CONFIG_LENGTH) return;
|
|
391
|
+
configuredCsp = csp;
|
|
392
|
+
// Acknowledge so the host can wait for confirmation before loading a frame.
|
|
393
|
+
try {
|
|
394
|
+
if (event.ports && event.ports[0]) {
|
|
395
|
+
event.ports[0].postMessage({ type: 'codelab:config-ready' });
|
|
396
|
+
} else if (event.source && typeof event.source.postMessage === 'function') {
|
|
397
|
+
event.source.postMessage({ type: 'codelab:config-ready' });
|
|
398
|
+
}
|
|
399
|
+
} catch (err) {
|
|
400
|
+
// The client may have navigated away between postMessage and reply.
|
|
401
|
+
console.warn('[code-lab] preview-sw: config acknowledgement failed', err);
|
|
402
|
+
}
|
|
403
|
+
});
|
|
404
|
+
|
|
28
405
|
function parsePreviewPath(pathname) {
|
|
29
406
|
const match = pathname.match(/^\/__preview\/(\d+)(\/.*)?$/);
|
|
30
407
|
if (!match) return null;
|
|
@@ -32,15 +409,46 @@ function parsePreviewPath(pathname) {
|
|
|
32
409
|
}
|
|
33
410
|
|
|
34
411
|
function previewErrorResponse(status, title, message) {
|
|
35
|
-
const
|
|
412
|
+
const csp = previewPolicy();
|
|
413
|
+
const body = `<!doctype html><meta charset="utf-8">` +
|
|
414
|
+
`<meta http-equiv="Content-Security-Policy" content="${csp}">` +
|
|
415
|
+
`<title>${title}</title>` +
|
|
36
416
|
`<body style="font-family:system-ui,-apple-system,sans-serif;padding:32px;color:#666;background:#0a0a0a">` +
|
|
37
417
|
`<h1 style="color:#e5e5e5;font-size:18px">${title}</h1><p>${message}</p></body>`;
|
|
38
418
|
return new Response(body, {
|
|
39
419
|
status,
|
|
40
|
-
headers: {
|
|
420
|
+
headers: {
|
|
421
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
422
|
+
'Content-Security-Policy': csp,
|
|
423
|
+
'X-Content-Type-Options': 'nosniff'
|
|
424
|
+
}
|
|
41
425
|
});
|
|
42
426
|
}
|
|
43
427
|
|
|
428
|
+
/** Inject the policy, a base URL and the sandbox shims into an HTML response. */
|
|
429
|
+
function injectPreviewHead(html, port) {
|
|
430
|
+
const csp = previewPolicy();
|
|
431
|
+
const shims = previewShims();
|
|
432
|
+
const tags = [];
|
|
433
|
+
const hasCsp = /<meta[^>]+http-equiv=["']?content-security-policy/i.test(html);
|
|
434
|
+
const hasBase = /<base\b/i.test(html);
|
|
435
|
+
const hasShims = html.indexOf('data-codelab-preview-shims') !== -1;
|
|
436
|
+
|
|
437
|
+
if (!hasCsp) tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
|
|
438
|
+
if (!hasBase) tags.push(`<base href="${PREVIEW_PREFIX}${port}/">`);
|
|
439
|
+
if (!hasShims && shims) tags.push(shims);
|
|
440
|
+
if (tags.length === 0) return html;
|
|
441
|
+
|
|
442
|
+
const injection = tags.join('');
|
|
443
|
+
if (/<head\b[^>]*>/i.test(html)) {
|
|
444
|
+
return html.replace(/<head\b[^>]*>/i, (match) => match + injection);
|
|
445
|
+
}
|
|
446
|
+
if (/<html\b[^>]*>/i.test(html)) {
|
|
447
|
+
return html.replace(/<html\b[^>]*>/i, (match) => `${match}<head>${injection}</head>`);
|
|
448
|
+
}
|
|
449
|
+
return `<head>${injection}</head>${html}`;
|
|
450
|
+
}
|
|
451
|
+
|
|
44
452
|
async function proxyVirtualRequest(event, port, targetPath) {
|
|
45
453
|
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
|
|
46
454
|
if (!clients || !clients.length) {
|
|
@@ -61,13 +469,18 @@ async function proxyVirtualRequest(event, port, targetPath) {
|
|
|
61
469
|
for (const [key, value] of request.headers.entries()) {
|
|
62
470
|
headers[key.toLowerCase()] = value;
|
|
63
471
|
}
|
|
64
|
-
} catch (
|
|
472
|
+
} catch (err) {
|
|
473
|
+
// Opaque or unsupported header collection; forward without request headers.
|
|
474
|
+
console.warn('[code-lab] preview-sw: could not read request headers', err);
|
|
475
|
+
}
|
|
65
476
|
|
|
66
477
|
let body = null;
|
|
67
478
|
if (!['GET', 'HEAD'].includes(method)) {
|
|
68
479
|
try {
|
|
69
480
|
body = await request.arrayBuffer();
|
|
70
|
-
} catch (
|
|
481
|
+
} catch (err) {
|
|
482
|
+
console.warn('[code-lab] preview-sw: could not read request body', err);
|
|
483
|
+
}
|
|
71
484
|
}
|
|
72
485
|
|
|
73
486
|
const response = await new Promise((resolve) => {
|
|
@@ -102,13 +515,12 @@ async function proxyVirtualRequest(event, port, targetPath) {
|
|
|
102
515
|
const responseHeaders = new Headers((response && response.headers) || {});
|
|
103
516
|
const contentType = responseHeaders.get('content-type') || '';
|
|
104
517
|
|
|
105
|
-
// Inject a <base> so relative asset URLs in HTML responses
|
|
106
|
-
// `/__preview/:port/` namespace rather than the host
|
|
518
|
+
// Inject the policy and a <base> so relative asset URLs in HTML responses
|
|
519
|
+
// resolve under the `/__preview/:port/` namespace rather than the host root.
|
|
107
520
|
if (/text\/html/i.test(contentType) && typeof responseBody === 'string') {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
}
|
|
521
|
+
responseBody = injectPreviewHead(responseBody, port);
|
|
522
|
+
responseHeaders.set('Content-Security-Policy', previewPolicy());
|
|
523
|
+
responseHeaders.set('X-Content-Type-Options', 'nosniff');
|
|
112
524
|
}
|
|
113
525
|
|
|
114
526
|
return new Response(responseBody, {
|
|
@@ -122,7 +534,9 @@ self.addEventListener('fetch', (event) => {
|
|
|
122
534
|
let url;
|
|
123
535
|
try {
|
|
124
536
|
url = new URL(event.request.url);
|
|
125
|
-
} catch (
|
|
537
|
+
} catch (err) {
|
|
538
|
+
// Non-standard request URL; let the network handle it.
|
|
539
|
+
console.warn('[code-lab] preview-sw: unparsable request URL', err);
|
|
126
540
|
return;
|
|
127
541
|
}
|
|
128
542
|
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,26 +1,4 @@
|
|
|
1
|
-
declare const
|
|
2
|
-
export interface RuntimeExecutionResult {
|
|
3
|
-
ok: boolean;
|
|
4
|
-
exitCode: number;
|
|
5
|
-
durationMs: number;
|
|
6
|
-
stdout: string;
|
|
7
|
-
stderr: string;
|
|
8
|
-
testResults: any[];
|
|
9
|
-
fsSnapshot: any[];
|
|
10
|
-
httpTrace: any[];
|
|
11
|
-
error?: {
|
|
12
|
-
message: string;
|
|
13
|
-
stack?: string;
|
|
14
|
-
};
|
|
15
|
-
outputTruncated?: boolean;
|
|
16
|
-
replValue?: any;
|
|
17
|
-
cancelled?: boolean;
|
|
18
|
-
testSummary?: {
|
|
19
|
-
total: number;
|
|
20
|
-
passed: number;
|
|
21
|
-
failed: number;
|
|
22
|
-
};
|
|
23
|
-
}
|
|
1
|
+
declare const _runtimeApi: any;
|
|
24
2
|
export declare const VirtualBuffer: any;
|
|
25
3
|
export declare const VirtualCrypto: any;
|
|
26
4
|
export declare const VirtualZlib: any;
|
|
@@ -42,8 +20,9 @@ export declare const transpileTS: (code: string, filename?: string) => string;
|
|
|
42
20
|
export declare const transpileForBrowser: (source: string, filename?: string) => string;
|
|
43
21
|
export declare const preloadNpmPackages: (files?: Record<string, any>, onProgressOrCache?: ((pkg: string) => void) | Map<string, string>, onProgress?: (pkg: string) => void) => Promise<Record<string, string>>;
|
|
44
22
|
export declare const createVirtualPortTable: () => any;
|
|
45
|
-
export declare const executeInVirtualRuntime: (options?: any) => Promise<
|
|
46
|
-
|
|
23
|
+
export declare const executeInVirtualRuntime: (options?: any) => Promise<any>;
|
|
24
|
+
declare const createWorkerRuntimeSourceExport: () => string;
|
|
25
|
+
export { createWorkerRuntimeSourceExport as createWorkerRuntimeSource };
|
|
47
26
|
export declare const cancelWorkerExecution: (reason?: string, instanceId?: string) => boolean;
|
|
48
|
-
export declare const executeInWorker: (options?: any) => Promise<
|
|
49
|
-
export default
|
|
27
|
+
export declare const executeInWorker: (options?: any) => Promise<any>;
|
|
28
|
+
export default _runtimeApi;
|