Skip to content

Commit

Permalink
feat: console forwarding (#22)
Browse files Browse the repository at this point in the history
* forwarr

* use more explicit import

* update yarn.lock
  • Loading branch information
DeMoorJasper authored May 22, 2022
1 parent 9f901f6 commit e16847d
Show file tree
Hide file tree
Showing 4 changed files with 300 additions and 8 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"@swc/helpers": "^0.3.8",
"@types/babel__standalone": "7.1.4",
"babel-preset-solid": "^1.3.13",
"console-feed": "3.3.0",
"gensync": "^1.0.0-beta.2",
"micromatch": "^4.0.5",
"p-queue": "^6.6.2",
Expand Down
14 changes: 14 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ErrorRecord, listenToRuntimeErrors } from './error-listener';
import { BundlerError } from './errors/BundlerError';
import { CompilationError } from './errors/CompilationError';
import { errorMessage } from './errors/util';
import { handleEvaluate, hookConsole } from './integrations/console';
import { Integrations } from './integrations/integrations';
import { IFrameParentMessageBus } from './protocol/iframe';
import { ICompileRequest } from './protocol/message-types';
Expand Down Expand Up @@ -48,6 +49,19 @@ class SandpackInstance {
payload: { frames: runtimeError.stackFrames },
});
});

// Console logic
hookConsole((log) => {
this.messageBus.sendMessage('console', { log });
});
this.messageBus.onMessage((data: any) => {
if (typeof data === 'object' && data.type === 'evaluate') {
const result = handleEvaluate(data.command);
if (result) {
this.messageBus.sendMessage('console', result);
}
}
});
}

handleParentMessage(message: any) {
Expand Down
44 changes: 44 additions & 0 deletions src/integrations/console.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import Hook from 'console-feed/lib/Hook';
import { Encode } from 'console-feed/lib/Transform';

export function hookConsole(output: (log: any) => void) {
Hook(window.console, async (log) => {
output(log);
});
}

export function handleEvaluate(command: string): { error: boolean; result: any } | undefined {
let result = null;
let error = false;

try {
// Attempt to wrap command in parentheses, fixing issues
// where directly returning objects results in unexpected
// behaviour.
if (command && command.charAt(0) === '{') {
try {
const wrapped = `(${command})`;
// `new Function` is used to validate Javascript syntax
// eslint-disable-next-line
const validate = new Function(wrapped);
command = wrapped;
} catch (e) {
// We shouldn't wrap the expression
}
}

result = (0, eval)(command); // eslint-disable-line no-eval
} catch (e) {
result = e;
error = true;
}

try {
return {
error,
result: Encode(result),
};
} catch (e) {
console.error(e);
}
}
Loading

0 comments on commit e16847d

Please sign in to comment.