@innovatorved/code-lab 0.1.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.
@@ -0,0 +1,54 @@
1
+ import {
2
+ GuidedLabExtensionOptions,
3
+ GuidedLabExtensionOptionsSchema,
4
+ GuidedStep
5
+ } from '../schemas';
6
+
7
+ /**
8
+ * Guided Lab Extension for CodeLab
9
+ *
10
+ * Provides TutorialKit / Codedamn-style interactive curriculum challenges:
11
+ * - Step-by-step instructions pane with architectural notes & hints
12
+ * - 'Guided Challenge' vs 'Reference Sandbox' mode switcher
13
+ * - 'Verify Step' test runner for targeted validation
14
+ * - Reference solution diff viewer
15
+ * - Multi-language (JS/TS) curriculum switching
16
+ */
17
+ export function guidedLabExtension(workbench: any, options: Partial<GuidedLabExtensionOptions> = {}) {
18
+ const parsed = GuidedLabExtensionOptionsSchema.partial().parse(options);
19
+
20
+ workbench.hasGuidedLab = true;
21
+ if (parsed.steps && parsed.steps.length > 0) {
22
+ workbench.steps = parsed.steps;
23
+ }
24
+ if (parsed.mode) {
25
+ workbench.mode = parsed.mode;
26
+ }
27
+ if (typeof parsed.stepIndex === 'number') {
28
+ workbench.activeStepIndex = parsed.stepIndex;
29
+ }
30
+
31
+ workbench.guidedConfig = {
32
+ ...workbench.guidedConfig,
33
+ ...parsed,
34
+ steps: workbench.steps
35
+ };
36
+
37
+ if (parsed.tsStarterFiles || parsed.tsSolutionFiles || parsed.tsFiles) {
38
+ workbench.hasMultipleLanguages = true;
39
+ }
40
+
41
+ if (typeof workbench._renderShell === 'function' && workbench.container) {
42
+ workbench._renderShell();
43
+ if (typeof workbench._bindEvents === 'function') {
44
+ workbench._bindEvents();
45
+ }
46
+ if (typeof workbench._renderFileLists === 'function') {
47
+ workbench._renderFileLists();
48
+ }
49
+ }
50
+
51
+ return workbench;
52
+ }
53
+
54
+ export default guidedLabExtension;
package/src/index.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @innovatorved/code-lab v2.0.0
3
+ * Browser-native IDE, POSIX Shell, Web Worker Node.js/Bun Runtime, and Git Engine.
4
+ */
5
+
6
+ export * from './schemas';
7
+ export * from './runtime';
8
+ export {
9
+ createPosixShell,
10
+ cloneGitHubRepository,
11
+ parseGitHubRepoUrl,
12
+ CodeLabShell
13
+ } from './shell';
14
+ export * from './terminal';
15
+ export { guidedLabExtension } from './extensions/guided-lab';
16
+
17
+ import { guidedLabExtension } from './extensions/guided-lab';
18
+
19
+ declare const globalThis: any;
20
+ const root = typeof window !== 'undefined' ? window : (typeof globalThis !== 'undefined' ? globalThis : {});
21
+
22
+ // Attach extensions to CodeLab SDK
23
+ if (root.CodeLab) {
24
+ root.CodeLab.extensions = root.CodeLab.extensions || {};
25
+ root.CodeLab.extensions.guidedLab = guidedLabExtension;
26
+ }
27
+
28
+ export default (root.CodeLab || {});
@@ -0,0 +1,149 @@
1
+ /**
2
+ * @innovatorved/code-lab — Web Preview Virtual Loopback Service Worker (Milestone 3)
3
+ * ============================================================================
4
+ * Intercepts same-origin requests to `/__preview/:port/*`, forwards them to the
5
+ * live CodeLab workbench window via a MessageChannel bridge, and streams the
6
+ * in-browser virtual runtime's response back to the requesting tab.
7
+ *
8
+ * This enables "pop out to tab" Web Preview for virtual HTTP / Bun servers that
9
+ * exist only inside the workbench's in-memory runtime (no real OS socket).
10
+ *
11
+ * Zero dependencies. Plain Service Worker script (no module imports) so it can
12
+ * be registered directly from any host origin.
13
+ */
14
+
15
+ 'use strict';
16
+
17
+ const PREVIEW_PREFIX = '/__preview/';
18
+ const DISPATCH_TIMEOUT_MS = 15000;
19
+
20
+ self.addEventListener('install', () => {
21
+ self.skipWaiting();
22
+ });
23
+
24
+ self.addEventListener('activate', (event) => {
25
+ event.waitUntil(self.clients.claim());
26
+ });
27
+
28
+ function parsePreviewPath(pathname) {
29
+ const match = pathname.match(/^\/__preview\/(\d+)(\/.*)?$/);
30
+ if (!match) return null;
31
+ return { port: Number(match[1]), path: match[2] || '/' };
32
+ }
33
+
34
+ function previewErrorResponse(status, title, message) {
35
+ const body = `<!doctype html><meta charset="utf-8"><title>${title}</title>` +
36
+ `<body style="font-family:system-ui,-apple-system,sans-serif;padding:32px;color:#666;background:#0a0a0a">` +
37
+ `<h1 style="color:#e5e5e5;font-size:18px">${title}</h1><p>${message}</p></body>`;
38
+ return new Response(body, {
39
+ status,
40
+ headers: { 'Content-Type': 'text/html; charset=utf-8' }
41
+ });
42
+ }
43
+
44
+ async function proxyVirtualRequest(event, port, targetPath) {
45
+ const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
46
+ if (!clients || !clients.length) {
47
+ return previewErrorResponse(
48
+ 503,
49
+ 'No active CodeLab workbench',
50
+ 'Return to the CodeLab IDE tab so the virtual runtime can serve this preview.'
51
+ );
52
+ }
53
+
54
+ const client = clients[0];
55
+ const channel = new MessageChannel();
56
+ const request = event.request;
57
+ const method = request.method || 'GET';
58
+
59
+ const headers = {};
60
+ try {
61
+ for (const [key, value] of request.headers.entries()) {
62
+ headers[key.toLowerCase()] = value;
63
+ }
64
+ } catch (_) {}
65
+
66
+ let body = null;
67
+ if (!['GET', 'HEAD'].includes(method)) {
68
+ try {
69
+ body = await request.arrayBuffer();
70
+ } catch (_) {}
71
+ }
72
+
73
+ const response = await new Promise((resolve) => {
74
+ const timer = setTimeout(() => {
75
+ resolve({
76
+ status: 504,
77
+ statusText: 'Gateway Timeout',
78
+ headers: { 'Content-Type': 'text/html' },
79
+ body: '<h1>504 Gateway Timeout</h1><p>The virtual workbench did not respond in time.</p>'
80
+ });
81
+ }, DISPATCH_TIMEOUT_MS);
82
+
83
+ channel.port1.onmessage = (messageEvent) => {
84
+ clearTimeout(timer);
85
+ resolve(messageEvent.data);
86
+ };
87
+
88
+ client.postMessage(
89
+ {
90
+ type: 'CODELAB_SW_DISPATCH',
91
+ port,
92
+ url: `http://127.0.0.1:${port}${targetPath}`,
93
+ method,
94
+ headers,
95
+ body
96
+ },
97
+ [channel.port2]
98
+ );
99
+ });
100
+
101
+ let responseBody = response && response.body;
102
+ const responseHeaders = new Headers((response && response.headers) || {});
103
+ const contentType = responseHeaders.get('content-type') || '';
104
+
105
+ // Inject a <base> so relative asset URLs in HTML responses resolve under the
106
+ // `/__preview/:port/` namespace rather than the host document root.
107
+ if (/text\/html/i.test(contentType) && typeof responseBody === 'string') {
108
+ const baseTag = `<base href="${PREVIEW_PREFIX}${port}/">`;
109
+ if (!/<base\b/i.test(responseBody) && /<head\b/i.test(responseBody)) {
110
+ responseBody = responseBody.replace(/<head\b[^>]*>/i, (match) => match + baseTag);
111
+ }
112
+ }
113
+
114
+ return new Response(responseBody, {
115
+ status: (response && response.status) || 200,
116
+ statusText: (response && response.statusText) || 'OK',
117
+ headers: responseHeaders
118
+ });
119
+ }
120
+
121
+ self.addEventListener('fetch', (event) => {
122
+ let url;
123
+ try {
124
+ url = new URL(event.request.url);
125
+ } catch (_) {
126
+ return;
127
+ }
128
+
129
+ // Only handle requests on this origin (never proxy third-party traffic).
130
+ if (url.origin !== self.location.origin) return;
131
+
132
+ const direct = parsePreviewPath(url.pathname);
133
+ if (direct) {
134
+ const targetPath = (direct.path || '/') + (url.search || '');
135
+ event.respondWith(proxyVirtualRequest(event, direct.port, targetPath));
136
+ return;
137
+ }
138
+
139
+ // Secondary route: root-relative sub-resources requested by a preview page
140
+ // (e.g. `/app.js` referenced from `/__preview/3000/`) are attributed to the
141
+ // originating preview tab via the request referrer.
142
+ const referrer = event.request.referrer || '';
143
+ const refMatch = referrer.match(/\/__preview\/(\d+)/);
144
+ if (refMatch) {
145
+ event.respondWith(
146
+ proxyVirtualRequest(event, Number(refMatch[1]), url.pathname + (url.search || ''))
147
+ );
148
+ }
149
+ });