Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion integrations/python-adapter/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "capsule-run-adapter"
version = "0.3.4"
version = "0.3.5"
description = "Capsule adapter for Python applications — execute Python and JavaScript code in isolated WebAssembly sandboxes"
license = { text = "Apache-2.0" }
readme = "README.md"
Expand Down
45 changes: 44 additions & 1 deletion integrations/python-adapter/src/js_sandbox/execution.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { fs, path, os, process } from "@capsule-run/sdk";

const fsPromises = fs.promises;

function hoistDeclarations(code: string): string {
let depth = 0;
let i = 0;
Expand Down Expand Up @@ -126,8 +130,41 @@ function hoistDeclarations(code: string): string {
return out;
}

/**
* Maps module names user code can import to their sandbox equivalents.
* These are the WASI polyfills from the capsule SDK.
*/
export const MODULE_REGISTRY: Record<string, unknown> = {
"fs": fs,
"fs/promises": fsPromises,
"node:fs": fs,
"node:fs/promises": fsPromises,
"path": path,
"node:path": path,
"os": os,
"node:os": os,
"process": process,
"node:process": process,
};

export const MODULE_VALUES: Set<unknown> = new Set(Object.values(MODULE_REGISTRY));
export const TRANSIENT_KEYS: Set<string> = new Set(["__require__", "require"]);


function rewriteImports(code: string): string {
return code.replace(
/^[ \t]*import\s+(?:(\*\s+as\s+\w+|\{[^}]*\}|\w+)\s+from\s+)?['"]([^'"]+)['"]\s*;?/gm,
(_, binding: string | undefined, mod: string) => {
if (!binding) return `__require__('${mod}');`;
const normalized = binding.replace(/^\*\s+as\s+/, "");
return `var ${normalized} = __require__('${mod}');`;
}
);
}

export function _executeCode(code: string, env: Record<string, unknown>): unknown {
code = hoistDeclarations(code);
code = rewriteImports(hoistDeclarations(code));

const capturedOutput: string[] = [];
const originalLog = console.log;

Expand All @@ -136,6 +173,12 @@ export function _executeCode(code: string, env: Record<string, unknown>): unknow
};

try {
env.__require__ = (mod: string): unknown => {
if (mod in MODULE_REGISTRY) return MODULE_REGISTRY[mod];
throw new Error(`Cannot import '${mod}': module is not available in the sandbox`);
};
env.require = env.__require__;

const proxy = new Proxy(env, {
has(_t, _k) { return true; },
get(t, k) {
Expand Down
18 changes: 18 additions & 0 deletions integrations/python-adapter/src/js_sandbox/serialization.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { MODULE_VALUES, TRANSIENT_KEYS, MODULE_REGISTRY } from "./execution";

export type SerializedValue =
| { __type__: "primitive"; value: string | number | boolean | null }
| { __type__: "undefined" }
Expand All @@ -13,6 +15,7 @@ export type SerializedValue =
| { __type__: "classdef"; __source__: string }
| { __type__: "function"; __source__: string }
| { __type__: "instance"; __class__: string; __source__: string; __dict__: Record<string, SerializedValue> }
| { __type__: "module"; name: string } // use for import/require() modules
| null;

export function serializeValue(val: unknown): SerializedValue {
Expand Down Expand Up @@ -96,16 +99,29 @@ export function serializeValue(val: unknown): SerializedValue {
return null;
}

const MODULE_VALUE_TO_NAME: Map<unknown, string> = new Map(
Object.entries(MODULE_REGISTRY)
.filter(([name]) => !name.startsWith("node:"))
.map(([name, val]) => [val, name])
);

export function serializeEnv(env: Record<string, unknown>): Record<string, SerializedValue> {
const out: Record<string, SerializedValue> = {};
for (const [key, val] of Object.entries(env)) {
if (key.startsWith("__")) continue;
if (TRANSIENT_KEYS.has(key)) continue;
if (MODULE_VALUES.has(val)) {
const name = MODULE_VALUE_TO_NAME.get(val);
if (name) out[key] = { __type__: "module", name };
continue;
}
const s = serializeValue(val);
if (s !== null) out[key] = s;
}
return out;
}


export function deserializeValue(
entry: SerializedValue,
classes: Record<string, new (...args: unknown[]) => unknown>
Expand Down Expand Up @@ -153,6 +169,8 @@ export function deserializeValue(
}
return instance;
}
case "module":
return MODULE_REGISTRY[entry.name];
default:
return undefined;
}
Expand Down
4 changes: 2 additions & 2 deletions integrations/typescript-adapter/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion integrations/typescript-adapter/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@capsule-run/adapter",
"version": "0.3.4",
"version": "0.3.5",
"description": "Capsule adapter for typescript applications",
"license": "Apache-2.0",
"author": "",
Expand Down
45 changes: 44 additions & 1 deletion integrations/typescript-adapter/src/js_sandbox/execution.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { fs, path, os, process } from "@capsule-run/sdk";

const fsPromises = fs.promises;

function hoistDeclarations(code: string): string {
let depth = 0;
let i = 0;
Expand Down Expand Up @@ -126,8 +130,41 @@ function hoistDeclarations(code: string): string {
return out;
}

/**
* Maps module names user code can import to their sandbox equivalents.
* These are the WASI polyfills from the capsule SDK.
*/
export const MODULE_REGISTRY: Record<string, unknown> = {
"fs": fs,
"fs/promises": fsPromises,
"node:fs": fs,
"node:fs/promises": fsPromises,
"path": path,
"node:path": path,
"os": os,
"node:os": os,
"process": process,
"node:process": process,
};

export const MODULE_VALUES: Set<unknown> = new Set(Object.values(MODULE_REGISTRY));
export const TRANSIENT_KEYS: Set<string> = new Set(["__require__", "require"]);


function rewriteImports(code: string): string {
return code.replace(
/^[ \t]*import\s+(?:(\*\s+as\s+\w+|\{[^}]*\}|\w+)\s+from\s+)?['"]([^'"]+)['"]\s*;?/gm,
(_, binding: string | undefined, mod: string) => {
if (!binding) return `__require__('${mod}');`;
const normalized = binding.replace(/^\*\s+as\s+/, "");
return `var ${normalized} = __require__('${mod}');`;
}
);
}

export function _executeCode(code: string, env: Record<string, unknown>): unknown {
code = hoistDeclarations(code);
code = rewriteImports(hoistDeclarations(code));

const capturedOutput: string[] = [];
const originalLog = console.log;

Expand All @@ -136,6 +173,12 @@ export function _executeCode(code: string, env: Record<string, unknown>): unknow
};

try {
env.__require__ = (mod: string): unknown => {
if (mod in MODULE_REGISTRY) return MODULE_REGISTRY[mod];
throw new Error(`Cannot import '${mod}': module is not available in the sandbox`);
};
env.require = env.__require__;

const proxy = new Proxy(env, {
has(_t, _k) { return true; },
get(t, k) {
Expand Down
18 changes: 18 additions & 0 deletions integrations/typescript-adapter/src/js_sandbox/serialization.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { MODULE_VALUES, TRANSIENT_KEYS, MODULE_REGISTRY } from "./execution";

export type SerializedValue =
| { __type__: "primitive"; value: string | number | boolean | null }
| { __type__: "undefined" }
Expand All @@ -13,6 +15,7 @@ export type SerializedValue =
| { __type__: "classdef"; __source__: string }
| { __type__: "function"; __source__: string }
| { __type__: "instance"; __class__: string; __source__: string; __dict__: Record<string, SerializedValue> }
| { __type__: "module"; name: string } // use for import/require() modules
| null;

export function serializeValue(val: unknown): SerializedValue {
Expand Down Expand Up @@ -96,16 +99,29 @@ export function serializeValue(val: unknown): SerializedValue {
return null;
}

const MODULE_VALUE_TO_NAME: Map<unknown, string> = new Map(
Object.entries(MODULE_REGISTRY)
.filter(([name]) => !name.startsWith("node:"))
.map(([name, val]) => [val, name])
);

export function serializeEnv(env: Record<string, unknown>): Record<string, SerializedValue> {
const out: Record<string, SerializedValue> = {};
for (const [key, val] of Object.entries(env)) {
if (key.startsWith("__")) continue;
if (TRANSIENT_KEYS.has(key)) continue;
if (MODULE_VALUES.has(val)) {
const name = MODULE_VALUE_TO_NAME.get(val);
if (name) out[key] = { __type__: "module", name };
continue;
}
const s = serializeValue(val);
if (s !== null) out[key] = s;
}
return out;
}


export function deserializeValue(
entry: SerializedValue,
classes: Record<string, new (...args: unknown[]) => unknown>
Expand Down Expand Up @@ -153,6 +169,8 @@ export function deserializeValue(
}
return instance;
}
case "module":
return MODULE_REGISTRY[entry.name];
default:
return undefined;
}
Expand Down
Loading