@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/src/csp.ts
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @innovatorved/code-lab — Web Preview Content-Security-Policy builder
|
|
3
|
+
* ============================================================================
|
|
4
|
+
* One place that knows how a preview policy is assembled. Before this module
|
|
5
|
+
* existed the policy was copy-pasted into `preview-sw.js` and `workbench.ts`
|
|
6
|
+
* under a "keep both copies in sync" comment — the classic drift bug.
|
|
7
|
+
*
|
|
8
|
+
* Why the host origin appears literally instead of `'self'`:
|
|
9
|
+
* previews are served in a sandboxed iframe (`allow-scripts`, deliberately
|
|
10
|
+
* *without* `allow-same-origin`). A sandboxed document has an opaque origin, so
|
|
11
|
+
* `'self'` matches no URL at all and the app's own `/__preview/<port>/app.js`
|
|
12
|
+
* would be blocked. Naming the host origin keeps the app's assets loadable
|
|
13
|
+
* while the sandbox keeps it away from host DOM and storage.
|
|
14
|
+
*
|
|
15
|
+
* Bundled as a classic script (`globalName: CodeLabCsp`) so the Service Worker
|
|
16
|
+
* and the workbench can both consume it without a module loader.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export type PreviewCspMode = 'strict' | 'balanced' | 'custom';
|
|
20
|
+
|
|
21
|
+
/** Per-directive network allowlist. Values are origins or CSP source keywords. */
|
|
22
|
+
export interface PreviewCspSources {
|
|
23
|
+
scriptSrc?: string[];
|
|
24
|
+
styleSrc?: string[];
|
|
25
|
+
imgSrc?: string[];
|
|
26
|
+
fontSrc?: string[];
|
|
27
|
+
connectSrc?: string[];
|
|
28
|
+
mediaSrc?: string[];
|
|
29
|
+
workerSrc?: string[];
|
|
30
|
+
frameSrc?: string[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface PreviewCspConfig extends PreviewCspSources {
|
|
34
|
+
mode?: PreviewCspMode | string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface PreviewCspOptions extends PreviewCspConfig {
|
|
38
|
+
/** Origin that serves `/__preview/*` (the host page). Falls back to `'self'`. */
|
|
39
|
+
hostOrigin?: string;
|
|
40
|
+
/** Value for `frame-ancestors`; defaults to `'self'`. */
|
|
41
|
+
frameAncestors?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface NormalizedPreviewCsp {
|
|
45
|
+
mode: PreviewCspMode;
|
|
46
|
+
allow: PreviewCspSources;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** CDNs the built-in preview server itself resolves bare imports to. */
|
|
50
|
+
const IMPORT_MAP_CDNS = ['https://cdn.jsdelivr.net', 'https://esm.sh'];
|
|
51
|
+
|
|
52
|
+
/** Fonts commonly referenced by CDN-hosted CSS. */
|
|
53
|
+
const FONT_CDNS = ['https://cdn.jsdelivr.net', 'https://fonts.gstatic.com'];
|
|
54
|
+
|
|
55
|
+
const PRESETS: Record<'strict' | 'balanced', PreviewCspSources> = {
|
|
56
|
+
strict: {},
|
|
57
|
+
balanced: {
|
|
58
|
+
scriptSrc: IMPORT_MAP_CDNS.slice(),
|
|
59
|
+
styleSrc: ['https://cdn.jsdelivr.net', 'https://fonts.googleapis.com'],
|
|
60
|
+
fontSrc: FONT_CDNS.slice(),
|
|
61
|
+
connectSrc: IMPORT_MAP_CDNS.slice(),
|
|
62
|
+
imgSrc: ['https://cdn.jsdelivr.net']
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const SOURCE_KEYS: Array<keyof PreviewCspSources> = [
|
|
67
|
+
'scriptSrc',
|
|
68
|
+
'styleSrc',
|
|
69
|
+
'imgSrc',
|
|
70
|
+
'fontSrc',
|
|
71
|
+
'connectSrc',
|
|
72
|
+
'mediaSrc',
|
|
73
|
+
'workerSrc',
|
|
74
|
+
'frameSrc'
|
|
75
|
+
];
|
|
76
|
+
|
|
77
|
+
const MAX_SOURCES = 64;
|
|
78
|
+
const MAX_SOURCE_LENGTH = 512;
|
|
79
|
+
|
|
80
|
+
/** HTML marker so the shim block is injected exactly once. */
|
|
81
|
+
export const PREVIEW_SHIM_MARKER = 'data-codelab-preview-shims';
|
|
82
|
+
|
|
83
|
+
/** Accepts `"https://a.example"` and returns its origin; `null` otherwise. */
|
|
84
|
+
export function normalizeOrigin(raw: unknown): string | null {
|
|
85
|
+
if (raw === null || raw === undefined || raw === '') return null;
|
|
86
|
+
try {
|
|
87
|
+
const parsed = new URL(String(raw));
|
|
88
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
|
|
89
|
+
return parsed.origin;
|
|
90
|
+
} catch (_) {
|
|
91
|
+
// Not an absolute URL (e.g. "preview.example.com" or a relative path).
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function normalizeMode(raw: unknown): PreviewCspMode {
|
|
97
|
+
if (raw === 'strict' || raw === 'custom') return raw;
|
|
98
|
+
return 'balanced';
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* CSP source keywords an author may name explicitly. Everything else has to be
|
|
103
|
+
* a concrete http(s) URL, `data:` or `blob:`.
|
|
104
|
+
*/
|
|
105
|
+
const ALLOWED_KEYWORDS: ReadonlyArray<string> = [
|
|
106
|
+
"'self'",
|
|
107
|
+
"'none'",
|
|
108
|
+
"'unsafe-inline'",
|
|
109
|
+
"'unsafe-eval'",
|
|
110
|
+
"'wasm-unsafe-eval'",
|
|
111
|
+
"'strict-dynamic'",
|
|
112
|
+
"'unsafe-hashes'"
|
|
113
|
+
];
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* `*`, `https:` and friends would silently disable the allowlist, and a `;`
|
|
117
|
+
* would inject an extra directive. Only concrete sources survive.
|
|
118
|
+
*/
|
|
119
|
+
const SOURCE_PATTERN = /^(?:https?:\/\/[A-Za-z0-9._~%-]+(?::\d{1,5})?(?:\/[^\s;,'"]*)?|data:|blob:|filesystem:)$/;
|
|
120
|
+
|
|
121
|
+
function isSafeSource(source: string): boolean {
|
|
122
|
+
return ALLOWED_KEYWORDS.indexOf(source) !== -1 || SOURCE_PATTERN.test(source);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function cleanSources(raw: unknown): string[] {
|
|
126
|
+
if (!Array.isArray(raw)) return [];
|
|
127
|
+
const out: string[] = [];
|
|
128
|
+
for (const value of raw.slice(0, MAX_SOURCES)) {
|
|
129
|
+
if (typeof value !== 'string') continue;
|
|
130
|
+
const source = value.trim();
|
|
131
|
+
if (!source || source.length > MAX_SOURCE_LENGTH) continue;
|
|
132
|
+
if (!isSafeSource(source)) continue;
|
|
133
|
+
if (out.indexOf(source) === -1) out.push(source);
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function unique(...lists: Array<string[] | undefined>): string[] {
|
|
139
|
+
const out: string[] = [];
|
|
140
|
+
for (const list of lists) {
|
|
141
|
+
if (!list) continue;
|
|
142
|
+
for (const value of list) {
|
|
143
|
+
if (value && out.indexOf(value) === -1) out.push(value);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Validate an author-supplied `previewCsp` option. Unknown modes fall back to
|
|
151
|
+
* `balanced`; invalid source entries are dropped rather than shipped.
|
|
152
|
+
*/
|
|
153
|
+
export function normalizePreviewCspConfig(raw: unknown): NormalizedPreviewCsp {
|
|
154
|
+
if (typeof raw === 'string') return { mode: normalizeMode(raw), allow: {} };
|
|
155
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
156
|
+
return { mode: 'balanced', allow: {} };
|
|
157
|
+
}
|
|
158
|
+
const input = raw as PreviewCspConfig;
|
|
159
|
+
// Accept both the author-facing shape (`{ mode, scriptSrc }`) and the
|
|
160
|
+
// normalized shape (`{ mode, allow: { scriptSrc } }`) so callers can pass a
|
|
161
|
+
// stored `previewCsp` value straight back in.
|
|
162
|
+
const nested = (input as { allow?: unknown }).allow;
|
|
163
|
+
const sources = (nested && typeof nested === 'object' && !Array.isArray(nested))
|
|
164
|
+
? nested as PreviewCspSources
|
|
165
|
+
: input;
|
|
166
|
+
const allow: PreviewCspSources = {};
|
|
167
|
+
for (const key of SOURCE_KEYS) {
|
|
168
|
+
const list = cleanSources(sources[key]);
|
|
169
|
+
if (list.length) allow[key] = list;
|
|
170
|
+
}
|
|
171
|
+
return { mode: normalizeMode(input.mode), allow };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function sourcesFor(mode: PreviewCspMode, allow: PreviewCspSources, key: keyof PreviewCspSources): string[] {
|
|
175
|
+
const preset = mode === 'custom' ? {} : PRESETS[mode];
|
|
176
|
+
// Clean here too: buildPreviewPolicy is public and must not splice unvalidated
|
|
177
|
+
// strings into the policy even when the caller skipped normalization.
|
|
178
|
+
return unique(preset[key], cleanSources(allow[key]));
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Build the policy string for one preview document.
|
|
183
|
+
*
|
|
184
|
+
* `unsafe-inline`/`unsafe-eval` stay enabled on purpose: previews are arbitrary
|
|
185
|
+
* user code and inline import maps are part of how they run. Isolation comes
|
|
186
|
+
* from the iframe sandbox (opaque origin), not from the CSP.
|
|
187
|
+
*/
|
|
188
|
+
export function buildPreviewPolicy(options: PreviewCspOptions = {}): string {
|
|
189
|
+
const mode = normalizeMode(options.mode);
|
|
190
|
+
const allow = options as PreviewCspSources;
|
|
191
|
+
const host = normalizeOrigin(options.hostOrigin);
|
|
192
|
+
// A `file://` preview has no usable origin; `'self'` is the least surprising
|
|
193
|
+
// fallback and simply blocks remote assets.
|
|
194
|
+
const self = host || "'self'";
|
|
195
|
+
|
|
196
|
+
const directive = (name: string, parts: string[]): string => `${name} ${unique(parts).join(' ')}`;
|
|
197
|
+
|
|
198
|
+
const script = (): string[] => [self, 'blob:', "'unsafe-inline'", "'unsafe-eval'"].concat(sourcesFor(mode, allow, 'scriptSrc'));
|
|
199
|
+
const style = (): string[] => [self, "'unsafe-inline'"].concat(sourcesFor(mode, allow, 'styleSrc'));
|
|
200
|
+
const withData = (key: keyof PreviewCspSources): string[] => [self, 'data:', 'blob:'].concat(sourcesFor(mode, allow, key));
|
|
201
|
+
|
|
202
|
+
return [
|
|
203
|
+
directive('default-src', [self, 'data:', 'blob:']),
|
|
204
|
+
directive('base-uri', [self]),
|
|
205
|
+
"object-src 'none'",
|
|
206
|
+
directive('script-src', script()),
|
|
207
|
+
directive('style-src', style()),
|
|
208
|
+
directive('img-src', withData('imgSrc')),
|
|
209
|
+
directive('font-src', [self, 'data:'].concat(sourcesFor(mode, allow, 'fontSrc'))),
|
|
210
|
+
directive('connect-src', withData('connectSrc')),
|
|
211
|
+
directive('media-src', withData('mediaSrc')),
|
|
212
|
+
directive('worker-src', [self, 'blob:'].concat(sourcesFor(mode, allow, 'workerSrc'))),
|
|
213
|
+
directive('frame-src', withData('frameSrc')),
|
|
214
|
+
directive('form-action', [self]),
|
|
215
|
+
directive('frame-ancestors', [options.frameAncestors || "'self'"])
|
|
216
|
+
].join('; ');
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Network hosts a preview may reach, for display in the Web Preview toolbar.
|
|
221
|
+
* Returns remote origins only — the host origin and CSP keywords are omitted.
|
|
222
|
+
*/
|
|
223
|
+
export function describePreviewNetwork(config: unknown): string[] {
|
|
224
|
+
const normalized = normalizePreviewCspConfig(config);
|
|
225
|
+
if (normalized.mode === 'strict') return [];
|
|
226
|
+
const preset = normalized.mode === 'custom' ? {} : PRESETS[normalized.mode];
|
|
227
|
+
const hosts: string[] = [];
|
|
228
|
+
for (const key of ['scriptSrc', 'connectSrc', 'imgSrc', 'styleSrc', 'fontSrc'] as Array<keyof PreviewCspSources>) {
|
|
229
|
+
for (const source of unique(preset[key], normalized.allow[key])) {
|
|
230
|
+
if (!/^https?:\/\//i.test(source)) continue;
|
|
231
|
+
let host: string;
|
|
232
|
+
try {
|
|
233
|
+
host = new URL(source).host;
|
|
234
|
+
} catch (_) {
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
if (hosts.indexOf(host) === -1) hosts.push(host);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return hosts;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Scripts injected into every preview document:
|
|
245
|
+
*
|
|
246
|
+
* 1. In-memory `localStorage`/`sessionStorage` — a sandboxed (opaque origin)
|
|
247
|
+
* document throws `SecurityError` on access, which breaks any preview that
|
|
248
|
+
* touches storage at module top level. In-memory equivalents keep the app
|
|
249
|
+
* running; sub-resource loading is unaffected.
|
|
250
|
+
* 2. A `securitypolicyviolation` reporter that forwards to the host via
|
|
251
|
+
* `postMessage`. The host validates `event.source` (the document origin is
|
|
252
|
+
* opaque, so `event.origin` is the string `"null"` and is not usable).
|
|
253
|
+
*/
|
|
254
|
+
export function buildPreviewShims(): string {
|
|
255
|
+
return `<script ${PREVIEW_SHIM_MARKER}>
|
|
256
|
+
(function () {
|
|
257
|
+
'use strict';
|
|
258
|
+
function memoryStorage() {
|
|
259
|
+
var data = new Map();
|
|
260
|
+
return {
|
|
261
|
+
getItem: function (k) { k = String(k); return data.has(k) ? data.get(k) : null; },
|
|
262
|
+
setItem: function (k, v) { data.set(String(k), String(v)); },
|
|
263
|
+
removeItem: function (k) { data.delete(String(k)); },
|
|
264
|
+
clear: function () { data.clear(); },
|
|
265
|
+
key: function (i) { return Array.from(data.keys())[i] || null; },
|
|
266
|
+
get length() { return data.size; }
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
function shim(name) {
|
|
270
|
+
var blocked = false;
|
|
271
|
+
try {
|
|
272
|
+
var existing = window[name];
|
|
273
|
+
if (existing) { existing.getItem('__codelab_probe__'); return; }
|
|
274
|
+
} catch (err) {
|
|
275
|
+
// Expected on an opaque origin: the accessor itself throws.
|
|
276
|
+
blocked = Boolean(err);
|
|
277
|
+
}
|
|
278
|
+
void blocked;
|
|
279
|
+
try {
|
|
280
|
+
Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
|
|
281
|
+
} catch (err) {
|
|
282
|
+
console.warn('[code-lab] preview: unable to shim ' + name, err);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
shim('localStorage');
|
|
286
|
+
shim('sessionStorage');
|
|
287
|
+
document.addEventListener('securitypolicyviolation', function (event) {
|
|
288
|
+
try {
|
|
289
|
+
parent.postMessage({
|
|
290
|
+
type: 'codelab:preview-violation',
|
|
291
|
+
directive: event.effectiveDirective || event.violatedDirective || '',
|
|
292
|
+
blockedURI: event.blockedURI || '',
|
|
293
|
+
sourceFile: event.sourceFile || '',
|
|
294
|
+
line: event.lineNumber || 0
|
|
295
|
+
}, '*');
|
|
296
|
+
} catch (err) {
|
|
297
|
+
console.warn('[code-lab] preview: could not report CSP violation', err);
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
function serializeArg(arg) {
|
|
301
|
+
if (typeof arg !== 'object' || arg === null) return String(arg);
|
|
302
|
+
try {
|
|
303
|
+
return JSON.stringify(arg);
|
|
304
|
+
} catch (err) {
|
|
305
|
+
void err;
|
|
306
|
+
return '[Circular/Unserializable]';
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
['log', 'warn', 'error', 'info'].forEach(function (level) {
|
|
310
|
+
var orig = console[level];
|
|
311
|
+
if (typeof orig !== 'function') return;
|
|
312
|
+
console[level] = function () {
|
|
313
|
+
var args = Array.prototype.slice.call(arguments);
|
|
314
|
+
try {
|
|
315
|
+
parent.postMessage({
|
|
316
|
+
type: 'codelab:preview-console',
|
|
317
|
+
level: level,
|
|
318
|
+
args: args.map(serializeArg)
|
|
319
|
+
}, '*');
|
|
320
|
+
} catch (err) {
|
|
321
|
+
void err;
|
|
322
|
+
}
|
|
323
|
+
return orig.apply(console, args);
|
|
324
|
+
};
|
|
325
|
+
});
|
|
326
|
+
function showPreviewErrorOverlay(msg, stack) {
|
|
327
|
+
try {
|
|
328
|
+
if (!document || !document.body) return;
|
|
329
|
+
var existing = document.getElementById('codelab-preview-error-overlay');
|
|
330
|
+
if (!existing) {
|
|
331
|
+
existing = document.createElement('div');
|
|
332
|
+
existing.id = 'codelab-preview-error-overlay';
|
|
333
|
+
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;';
|
|
334
|
+
document.body.appendChild(existing);
|
|
335
|
+
}
|
|
336
|
+
existing.textContent = '';
|
|
337
|
+
var header = document.createElement('div');
|
|
338
|
+
header.style.cssText = 'color:#f87171;font-weight:700;font-size:15px;margin-bottom:12px;';
|
|
339
|
+
header.textContent = 'Runtime Error: ' + String(msg || 'Uncaught Error');
|
|
340
|
+
var pre = document.createElement('pre');
|
|
341
|
+
pre.style.cssText = 'white-space:pre-wrap;font-size:12px;color:#cbd5e1;margin:0;';
|
|
342
|
+
pre.textContent = String(stack || msg || '');
|
|
343
|
+
existing.appendChild(header);
|
|
344
|
+
existing.appendChild(pre);
|
|
345
|
+
} catch (err) {
|
|
346
|
+
void err;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
window.addEventListener('error', function (event) {
|
|
350
|
+
var msg = (event && event.message) ? event.message : 'Uncaught runtime error';
|
|
351
|
+
var stack = (event && event.error && event.error.stack) ? String(event.error.stack) : '';
|
|
352
|
+
showPreviewErrorOverlay(msg, stack);
|
|
353
|
+
try {
|
|
354
|
+
parent.postMessage({
|
|
355
|
+
type: 'codelab:preview-error',
|
|
356
|
+
message: msg,
|
|
357
|
+
file: (event && event.filename) || null,
|
|
358
|
+
line: (event && event.lineno) || null,
|
|
359
|
+
col: (event && event.colno) || null,
|
|
360
|
+
stack: stack || null
|
|
361
|
+
}, '*');
|
|
362
|
+
} catch (err) {
|
|
363
|
+
void err;
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
window.addEventListener('unhandledrejection', function (event) {
|
|
367
|
+
var reason = event ? event.reason : null;
|
|
368
|
+
var msg = reason && reason.message ? String(reason.message) : String(reason || 'Unhandled Promise Rejection');
|
|
369
|
+
var stack = reason && reason.stack ? String(reason.stack) : '';
|
|
370
|
+
showPreviewErrorOverlay(msg, stack);
|
|
371
|
+
try {
|
|
372
|
+
parent.postMessage({
|
|
373
|
+
type: 'codelab:preview-error',
|
|
374
|
+
message: msg,
|
|
375
|
+
file: null,
|
|
376
|
+
line: null,
|
|
377
|
+
col: null,
|
|
378
|
+
stack: stack || null
|
|
379
|
+
}, '*');
|
|
380
|
+
} catch (err) {
|
|
381
|
+
void err;
|
|
382
|
+
}
|
|
383
|
+
});
|
|
384
|
+
})();
|
|
385
|
+
</script>`;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Default export keeps the IIFE global (`CodeLabCsp`) shaped like the sources. */
|
|
389
|
+
export default {
|
|
390
|
+
buildPreviewPolicy,
|
|
391
|
+
buildPreviewShims,
|
|
392
|
+
describePreviewNetwork,
|
|
393
|
+
normalizePreviewCspConfig,
|
|
394
|
+
normalizeOrigin,
|
|
395
|
+
PREVIEW_SHIM_MARKER
|
|
396
|
+
};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @innovatorved/code-lab — Unified Diagnostics & Problems Aggregator Store
|
|
3
|
+
* ============================================================================
|
|
4
|
+
* Aggregates diagnostics from Monaco TypeScript/JavaScript workers, runtime
|
|
5
|
+
* execution exceptions, preview errors, and linters into a reactive store
|
|
6
|
+
* driving editor markers and the bottom drawer Problems panel.
|
|
7
|
+
*
|
|
8
|
+
* Strict leaf module: fully typed, zero explicit any, zero empty catches.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export type DiagnosticSeverity = 'error' | 'warning' | 'info' | 'hint';
|
|
12
|
+
|
|
13
|
+
export interface DiagnosticItem {
|
|
14
|
+
id: string;
|
|
15
|
+
file: string;
|
|
16
|
+
line: number;
|
|
17
|
+
col?: number;
|
|
18
|
+
column?: number;
|
|
19
|
+
endLine?: number;
|
|
20
|
+
endCol?: number;
|
|
21
|
+
endColumn?: number;
|
|
22
|
+
message: string;
|
|
23
|
+
severity: DiagnosticSeverity;
|
|
24
|
+
source?: string;
|
|
25
|
+
code?: string | number;
|
|
26
|
+
tags?: string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type DiagnosticListener = (items: DiagnosticItem[]) => void;
|
|
30
|
+
|
|
31
|
+
export class DiagnosticsStore {
|
|
32
|
+
private readonly items: Map<string, DiagnosticItem> = new Map();
|
|
33
|
+
private readonly listeners: Set<DiagnosticListener> = new Set();
|
|
34
|
+
|
|
35
|
+
public add(item: DiagnosticItem): void {
|
|
36
|
+
if (!item || typeof item.id !== 'string' || !item.id) return;
|
|
37
|
+
const normalized: DiagnosticItem = {
|
|
38
|
+
...item,
|
|
39
|
+
file: String(item.file || ''),
|
|
40
|
+
line: typeof item.line === 'number' && item.line > 0 ? Math.floor(item.line) : 1,
|
|
41
|
+
col: typeof item.col === 'number' && item.col > 0
|
|
42
|
+
? Math.floor(item.col)
|
|
43
|
+
: (typeof item.column === 'number' && item.column > 0 ? Math.floor(item.column) : 1),
|
|
44
|
+
message: String(item.message || ''),
|
|
45
|
+
severity: item.severity || 'error'
|
|
46
|
+
};
|
|
47
|
+
this.items.set(normalized.id, normalized);
|
|
48
|
+
this.notify();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
public remove(id: string): void {
|
|
52
|
+
if (this.items.delete(id)) {
|
|
53
|
+
this.notify();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
public clear(source?: string): void {
|
|
58
|
+
if (source !== undefined && source !== '') {
|
|
59
|
+
let changed = false;
|
|
60
|
+
for (const [id, item] of this.items.entries()) {
|
|
61
|
+
if (item.source === source) {
|
|
62
|
+
this.items.delete(id);
|
|
63
|
+
changed = true;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (changed) {
|
|
67
|
+
this.notify();
|
|
68
|
+
}
|
|
69
|
+
} else if (this.items.size > 0) {
|
|
70
|
+
this.items.clear();
|
|
71
|
+
this.notify();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
public getAll(): DiagnosticItem[] {
|
|
76
|
+
return Array.from(this.items.values());
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
public getByFile(file: string): DiagnosticItem[] {
|
|
80
|
+
const out: DiagnosticItem[] = [];
|
|
81
|
+
for (const item of this.items.values()) {
|
|
82
|
+
if (item.file === file) {
|
|
83
|
+
out.push(item);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
public subscribe(listener: DiagnosticListener): () => void {
|
|
90
|
+
this.listeners.add(listener);
|
|
91
|
+
return () => {
|
|
92
|
+
this.listeners.delete(listener);
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private notify(): void {
|
|
97
|
+
if (this.listeners.size === 0) return;
|
|
98
|
+
const snapshot = this.getAll();
|
|
99
|
+
for (const listener of this.listeners) {
|
|
100
|
+
try {
|
|
101
|
+
listener(snapshot);
|
|
102
|
+
} catch (err) {
|
|
103
|
+
console.warn('[code-lab] diagnostics subscriber error:', err);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function createDiagnosticsStore(): DiagnosticsStore {
|
|
110
|
+
return new DiagnosticsStore();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export default {
|
|
114
|
+
DiagnosticsStore,
|
|
115
|
+
createDiagnosticsStore
|
|
116
|
+
};
|
package/src/html.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @innovatorved/code-lab — Safe HTML Tagged Template & Escaping Primitives
|
|
3
|
+
* ============================================================================
|
|
4
|
+
* Strict TypeScript leaf module. Every interpolated value in `html\`...\`` is
|
|
5
|
+
* HTML-escaped by default unless explicitly wrapped with `raw(...)` or
|
|
6
|
+
* produced by nested `html\`...\`` calls.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const SAFE_HTML_BRAND = Symbol.for('codelab.SafeHtml');
|
|
10
|
+
|
|
11
|
+
export interface SafeHtml {
|
|
12
|
+
readonly [SAFE_HTML_BRAND]: true;
|
|
13
|
+
readonly __html: string;
|
|
14
|
+
toString(): string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
class SafeHtmlImpl implements SafeHtml {
|
|
18
|
+
readonly [SAFE_HTML_BRAND] = true as const;
|
|
19
|
+
readonly __html: string;
|
|
20
|
+
|
|
21
|
+
constructor(trusted: string) {
|
|
22
|
+
this.__html = String(trusted);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
toString(): string {
|
|
26
|
+
return this.__html;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function isSafeHtml(value: unknown): value is SafeHtml {
|
|
31
|
+
return Boolean(
|
|
32
|
+
value &&
|
|
33
|
+
typeof value === 'object' &&
|
|
34
|
+
(value as Record<symbol, unknown>)[SAFE_HTML_BRAND] === true &&
|
|
35
|
+
typeof (value as { __html?: unknown }).__html === 'string'
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function escapeHtml(value: unknown): string {
|
|
40
|
+
if (value === null || value === undefined) return '';
|
|
41
|
+
if (isSafeHtml(value)) return value.__html;
|
|
42
|
+
return String(value)
|
|
43
|
+
.replace(/&/g, '&')
|
|
44
|
+
.replace(/</g, '<')
|
|
45
|
+
.replace(/>/g, '>')
|
|
46
|
+
.replace(/"/g, '"')
|
|
47
|
+
.replace(/'/g, ''');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function raw(trustedHtml: string): SafeHtml {
|
|
51
|
+
return new SafeHtmlImpl(trustedHtml);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function renderInterpolation(value: unknown): string {
|
|
55
|
+
if (value === null || value === undefined || value === false) return '';
|
|
56
|
+
if (isSafeHtml(value)) return value.__html;
|
|
57
|
+
if (Array.isArray(value)) {
|
|
58
|
+
let out = '';
|
|
59
|
+
for (let i = 0; i < value.length; i++) {
|
|
60
|
+
out += renderInterpolation(value[i]);
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
return escapeHtml(value);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function html(strings: TemplateStringsArray, ...values: unknown[]): SafeHtml {
|
|
68
|
+
let out = strings[0] ?? '';
|
|
69
|
+
for (let i = 0; i < values.length; i++) {
|
|
70
|
+
out += renderInterpolation(values[i]);
|
|
71
|
+
out += strings[i + 1] ?? '';
|
|
72
|
+
}
|
|
73
|
+
return new SafeHtmlImpl(out);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const _htmlNamespace = {
|
|
77
|
+
escapeHtml,
|
|
78
|
+
raw,
|
|
79
|
+
isSafeHtml,
|
|
80
|
+
html
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const _globalRoot = typeof globalThis !== 'undefined' ? (globalThis as Record<string, unknown>) : null;
|
|
84
|
+
if (_globalRoot && !_globalRoot.CodeLabHtml) {
|
|
85
|
+
_globalRoot.CodeLabHtml = _htmlNamespace;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export default _htmlNamespace;
|
package/src/index.ts
CHANGED
|
@@ -1,9 +1,47 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @innovatorved/code-lab
|
|
2
|
+
* @innovatorved/code-lab v0.1.8
|
|
3
3
|
* Browser-native IDE, POSIX Shell, Web Worker Node.js/Bun Runtime, and Git Engine.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
export * from './schemas';
|
|
7
|
+
export * from './logger';
|
|
8
|
+
export { SafeHtml, isSafeHtml, raw, html } from './html';
|
|
9
|
+
export * from './csp';
|
|
10
|
+
export * from './zip';
|
|
11
|
+
export {
|
|
12
|
+
type StorageBackendType,
|
|
13
|
+
type ProjectSummary,
|
|
14
|
+
type WorkspaceStorageOptions,
|
|
15
|
+
WorkspaceStorage,
|
|
16
|
+
createWorkspaceStorage
|
|
17
|
+
} from './storage';
|
|
18
|
+
export {
|
|
19
|
+
type SearchMatchItem,
|
|
20
|
+
type SearchMatchGroup,
|
|
21
|
+
type SearchResult,
|
|
22
|
+
type ReplaceResult,
|
|
23
|
+
escapeRegex,
|
|
24
|
+
normalizeSearchPath,
|
|
25
|
+
matchesGlob,
|
|
26
|
+
searchInFiles,
|
|
27
|
+
replaceInFiles
|
|
28
|
+
} from './search';
|
|
29
|
+
export {
|
|
30
|
+
type DiagnosticListener,
|
|
31
|
+
DiagnosticsStore,
|
|
32
|
+
createDiagnosticsStore
|
|
33
|
+
} from './diagnostics';
|
|
34
|
+
export {
|
|
35
|
+
type GitCommitRecord,
|
|
36
|
+
type GitState,
|
|
37
|
+
type GitStatusResult,
|
|
38
|
+
computeShortCommitHash,
|
|
39
|
+
createGitState,
|
|
40
|
+
computeGitStatus,
|
|
41
|
+
stageFile,
|
|
42
|
+
unstageFile,
|
|
43
|
+
commitChanges
|
|
44
|
+
} from './scm';
|
|
7
45
|
export * from './runtime';
|
|
8
46
|
export {
|
|
9
47
|
createPosixShell,
|