wasm-idle 1.2.0 → 1.3.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,49 @@
1
+ import { type ExecutionLimits, type RuntimeAssetCacheOptions } from '@wasm-idle/core';
2
+ import type { SandboxProgress, SandboxRuntimeAssets } from './sandbox';
3
+ export interface PythonCompileOptions {
4
+ /** Relative source path used in tracebacks. Defaults to main.py. */
5
+ fileName?: string;
6
+ /** 0 preserves assertions and docstrings; 1 removes assertions; 2 also removes docstrings. */
7
+ optimize?: 0 | 1 | 2;
8
+ /** Cache invalidation format. Defaults to reproducible checked-hash bytecode without a timestamp. */
9
+ invalidationMode?: 'checked-hash' | 'unchecked-hash' | 'timestamp';
10
+ /** Source mtime in integer Unix seconds (0–4294967295). Only valid in timestamp mode; defaults to 0. */
11
+ timestamp?: number;
12
+ runtimeAssets?: SandboxRuntimeAssets;
13
+ persistentCache?: RuntimeAssetCacheOptions;
14
+ signal?: AbortSignal;
15
+ progress?: SandboxProgress;
16
+ /** maxWorkspaceBytes bounds the source; maxOutputBytes bounds the returned .pyc. */
17
+ limits?: Partial<Pick<ExecutionLimits, 'assetTimeoutMs' | 'startupTimeoutMs' | 'compileTimeoutMs' | 'maxWorkspaceBytes' | 'maxOutputBytes' | 'maxAssetBytes'>>;
18
+ }
19
+ export interface PythonCompileResult {
20
+ /** Relative output path, e.g. pkg/main.pyc. */
21
+ path: string;
22
+ data: Uint8Array;
23
+ pythonVersion: string;
24
+ cacheTag: string;
25
+ /** Four-byte CPython magic number encoded as eight hexadecimal digits. */
26
+ magicNumber: string;
27
+ }
28
+ /** Share header-option validation between the host and the actual compiler boundary. */
29
+ export declare function resolvePythonBytecodeOptions(options: Pick<PythonCompileOptions, 'invalidationMode' | 'timestamp'>): {
30
+ invalidationMode: "checked-hash" | "unchecked-hash";
31
+ timestamp: undefined;
32
+ } | {
33
+ invalidationMode: "timestamp";
34
+ timestamp: number;
35
+ };
36
+ /** Validate before starting a runtime, and again at the direct adapter boundary. */
37
+ export declare function resolvePythonCompileRequest(code: string, options: PythonCompileOptions): {
38
+ invalidationMode: "checked-hash" | "unchecked-hash";
39
+ timestamp: undefined;
40
+ fileName: string;
41
+ optimize: 0 | 1 | 2;
42
+ limits: ExecutionLimits;
43
+ } | {
44
+ invalidationMode: "timestamp";
45
+ timestamp: number;
46
+ fileName: string;
47
+ optimize: 0 | 1 | 2;
48
+ limits: ExecutionLimits;
49
+ };
@@ -0,0 +1,40 @@
1
+ import { RuntimeConfigurationError, resolveExecutionLimits, validateExecutionWorkspace } from '@wasm-idle/core';
2
+ /** Share header-option validation between the host and the actual compiler boundary. */
3
+ export function resolvePythonBytecodeOptions(options) {
4
+ const invalidationMode = options.invalidationMode === undefined ? 'checked-hash' : options.invalidationMode;
5
+ if (!['checked-hash', 'unchecked-hash', 'timestamp'].includes(invalidationMode)) {
6
+ throw new RuntimeConfigurationError('Python invalidationMode must be checked-hash, unchecked-hash, or timestamp');
7
+ }
8
+ if (invalidationMode !== 'timestamp') {
9
+ if (options.timestamp !== undefined) {
10
+ throw new RuntimeConfigurationError('Python timestamp requires timestamp invalidation mode');
11
+ }
12
+ return { invalidationMode, timestamp: undefined };
13
+ }
14
+ const timestamp = options.timestamp === undefined ? 0 : options.timestamp;
15
+ if (!Number.isInteger(timestamp) || timestamp < 0 || timestamp > 0xffffffff) {
16
+ throw new RuntimeConfigurationError('Python timestamp must be an integer Unix time from 0 to 4294967295 seconds');
17
+ }
18
+ return { invalidationMode, timestamp };
19
+ }
20
+ /** Validate before starting a runtime, and again at the direct adapter boundary. */
21
+ export function resolvePythonCompileRequest(code, options) {
22
+ if (typeof code !== 'string') {
23
+ throw new RuntimeConfigurationError('Python source must be a string');
24
+ }
25
+ const limits = resolveExecutionLimits(options.limits);
26
+ const optimize = options.optimize ?? 0;
27
+ if (![0, 1, 2].includes(optimize)) {
28
+ throw new RuntimeConfigurationError('Python optimize must be 0, 1, or 2');
29
+ }
30
+ const bytecodeOptions = resolvePythonBytecodeOptions(options);
31
+ const workspace = validateExecutionWorkspace(code, [], options.fileName ?? 'main.py', {
32
+ maxFileBytes: limits.maxWorkspaceBytes,
33
+ maxTotalBytes: limits.maxWorkspaceBytes
34
+ });
35
+ const fileName = workspace.activePath;
36
+ if (!/\.py$/i.test(fileName)) {
37
+ throw new RuntimeConfigurationError('Python compilation requires a .py file name');
38
+ }
39
+ return { fileName, optimize, limits, ...bytecodeOptions };
40
+ }
@@ -1 +1 @@
1
- export declare const STATIC_RUNTIME_MODULE_VERSION = "b29a54a528d2f8aa";
1
+ export declare const STATIC_RUNTIME_MODULE_VERSION = "6b508364c7ec4127";
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/build-static-runtime-modules.mjs.
2
- export const STATIC_RUNTIME_MODULE_VERSION = 'b29a54a528d2f8aa';
2
+ export const STATIC_RUNTIME_MODULE_VERSION = '6b508364c7ec4127';
@@ -1,6 +1,6 @@
1
1
  export declare const WASM_DEBUG_RUNTIME_PROFILE: Readonly<{
2
2
  manifestReceipt: Readonly<{
3
3
  bytes: 2853;
4
- sha256: "d4b08c91cd9bc810d0862ea2a5ef5a092e52f6b22a6f3121499ec5d3df2086b5";
4
+ sha256: "78e65afcf84ed709c6d166f4ef55bf34e5e3b10c61155a3484547cb8b27bd3a1";
5
5
  }>;
6
6
  }>;
@@ -1,6 +1,6 @@
1
1
  export const WASM_DEBUG_RUNTIME_PROFILE = Object.freeze({
2
2
  manifestReceipt: Object.freeze({
3
3
  bytes: 2853,
4
- sha256: 'd4b08c91cd9bc810d0862ea2a5ef5a092e52f6b22a6f3121499ec5d3df2086b5'
4
+ sha256: '78e65afcf84ed709c6d166f4ef55bf34e5e3b10c61155a3484547cb8b27bd3a1'
5
5
  })
6
6
  });
@@ -1,31 +1,31 @@
1
1
  export declare const WASM_PROLOG_RUNTIME_PROFILE: {
2
- readonly profileId: "swipl-wasm-8.2.1-swipl-10.1.15";
3
- readonly packageRevision: "85167290994ede92eab1aa5e399007c031e6cb82";
4
- readonly swiplRevision: "5db27168f89b15186745ea401fbb99a017413788";
5
- readonly manifestFingerprint: "c97f050d36f55558811d27021580338dd01e37016c70e1ef2daaaad0a29618b3";
2
+ readonly profileId: "swipl-wasm-8.2.5-swipl-10.1.19";
3
+ readonly packageRevision: "a633668fc459e0fd4ec5f993443d07b0c933aa2a";
4
+ readonly swiplRevision: "724df2b54cf1dda6fb3327d9167db2ae750c460e";
5
+ readonly manifestFingerprint: "f1cfa59be0be8ff815e056b53f6c59bd270dbdabc62f09bcd42e40122185d95a";
6
6
  readonly manifestReceipt: {
7
7
  readonly bytes: 2576;
8
- readonly sha256: "b67d6f6ff9115bd886d2992b0ad97e7d726aa66cc2a3e288ce7f99a3249d6d47";
8
+ readonly sha256: "aae0a74de3c773a5b7da1cbd14e1e55e95f3f8a52cb2435c9fcad4e6684279f7";
9
9
  };
10
10
  readonly javascriptReceipt: {
11
- readonly bytes: 193421;
12
- readonly sha256: "635da02ac0eb18e51303e4a0398b220d17cabfc0e4b7a2acbc7af9e949e4a9c7";
11
+ readonly bytes: 191369;
12
+ readonly sha256: "b71b671c5396c0d3ab4e04ee0376bfb47319cdfcf4b00b202ba3fdb671de6e7d";
13
13
  };
14
14
  readonly wasmReceipt: {
15
- readonly bytes: 820495;
16
- readonly sha256: "da8461e22b4513c5020d7eef7f8e62b2086003125381d18fed08f3656eecd793";
17
- readonly uncompressedBytes: 2275324;
18
- readonly uncompressedSha256: "c8831c0ac6a021b6bc67fa1b86e8826d1ea92a1a81b932cfb88fea235361c355";
15
+ readonly bytes: 835909;
16
+ readonly sha256: "fb3d7bb440083b48d383a178dcab0325f4a61c9e470d42bf12e0431f39f0f54e";
17
+ readonly uncompressedBytes: 2311472;
18
+ readonly uncompressedSha256: "80674a1223edc60629460fca12e322f9c27fdeb20ef72fc0f755edea1906a3b2";
19
19
  };
20
20
  readonly dataReceipt: {
21
- readonly bytes: 1192600;
22
- readonly sha256: "ea735ff89940eaed405a4a9b2be8606141d821016f3fc7671983b2203e88e86f";
23
- readonly uncompressedBytes: 1659074;
24
- readonly uncompressedSha256: "91e9d9c1d184f1a291c870e96bf6a1bc502ce8787946c966526a663a725ba932";
21
+ readonly bytes: 1195673;
22
+ readonly sha256: "432ea3836adabf3fd034494b74c8e5c7748108a9977cf3b5efa2310c4eea373d";
23
+ readonly uncompressedBytes: 1662393;
24
+ readonly uncompressedSha256: "a980ac3f2ecb5a5d670b8470ab77c780768c0c6421ed51ef063f606d736c55a4";
25
25
  };
26
26
  };
27
- export declare const WASM_PROLOG_ASSET_VERSION: "c97f050d36f55558811d27021580338dd01e37016c70e1ef2daaaad0a29618b3";
27
+ export declare const WASM_PROLOG_ASSET_VERSION: "f1cfa59be0be8ff815e056b53f6c59bd270dbdabc62f09bcd42e40122185d95a";
28
28
  export declare const WASM_PROLOG_RUNNER_RECEIPT: {
29
29
  readonly bytes: 25728;
30
- readonly sha256: "f7b90043b2fc7cbcac475264841705633f433604adb2e61ac4f6dbc505f5c2b4";
30
+ readonly sha256: "3f30582ec19cf430e6d2f7e9d544cc0f766accc7361f0a3fbb427bcdb7d0298b";
31
31
  };
@@ -1,31 +1,31 @@
1
1
  export const WASM_PROLOG_RUNTIME_PROFILE = {
2
- profileId: 'swipl-wasm-8.2.1-swipl-10.1.15',
3
- packageRevision: '85167290994ede92eab1aa5e399007c031e6cb82',
4
- swiplRevision: '5db27168f89b15186745ea401fbb99a017413788',
5
- manifestFingerprint: 'c97f050d36f55558811d27021580338dd01e37016c70e1ef2daaaad0a29618b3',
2
+ profileId: 'swipl-wasm-8.2.5-swipl-10.1.19',
3
+ packageRevision: 'a633668fc459e0fd4ec5f993443d07b0c933aa2a',
4
+ swiplRevision: '724df2b54cf1dda6fb3327d9167db2ae750c460e',
5
+ manifestFingerprint: 'f1cfa59be0be8ff815e056b53f6c59bd270dbdabc62f09bcd42e40122185d95a',
6
6
  manifestReceipt: {
7
7
  bytes: 2576,
8
- sha256: 'b67d6f6ff9115bd886d2992b0ad97e7d726aa66cc2a3e288ce7f99a3249d6d47'
8
+ sha256: 'aae0a74de3c773a5b7da1cbd14e1e55e95f3f8a52cb2435c9fcad4e6684279f7'
9
9
  },
10
10
  javascriptReceipt: {
11
- bytes: 193421,
12
- sha256: '635da02ac0eb18e51303e4a0398b220d17cabfc0e4b7a2acbc7af9e949e4a9c7'
11
+ bytes: 191369,
12
+ sha256: 'b71b671c5396c0d3ab4e04ee0376bfb47319cdfcf4b00b202ba3fdb671de6e7d'
13
13
  },
14
14
  wasmReceipt: {
15
- bytes: 820495,
16
- sha256: 'da8461e22b4513c5020d7eef7f8e62b2086003125381d18fed08f3656eecd793',
17
- uncompressedBytes: 2275324,
18
- uncompressedSha256: 'c8831c0ac6a021b6bc67fa1b86e8826d1ea92a1a81b932cfb88fea235361c355'
15
+ bytes: 835909,
16
+ sha256: 'fb3d7bb440083b48d383a178dcab0325f4a61c9e470d42bf12e0431f39f0f54e',
17
+ uncompressedBytes: 2311472,
18
+ uncompressedSha256: '80674a1223edc60629460fca12e322f9c27fdeb20ef72fc0f755edea1906a3b2'
19
19
  },
20
20
  dataReceipt: {
21
- bytes: 1192600,
22
- sha256: 'ea735ff89940eaed405a4a9b2be8606141d821016f3fc7671983b2203e88e86f',
23
- uncompressedBytes: 1659074,
24
- uncompressedSha256: '91e9d9c1d184f1a291c870e96bf6a1bc502ce8787946c966526a663a725ba932'
21
+ bytes: 1195673,
22
+ sha256: '432ea3836adabf3fd034494b74c8e5c7748108a9977cf3b5efa2310c4eea373d',
23
+ uncompressedBytes: 1662393,
24
+ uncompressedSha256: 'a980ac3f2ecb5a5d670b8470ab77c780768c0c6421ed51ef063f606d736c55a4'
25
25
  }
26
26
  };
27
27
  export const WASM_PROLOG_ASSET_VERSION = WASM_PROLOG_RUNTIME_PROFILE.manifestFingerprint;
28
28
  export const WASM_PROLOG_RUNNER_RECEIPT = {
29
29
  bytes: 25728,
30
- sha256: 'f7b90043b2fc7cbcac475264841705633f433604adb2e61ac4f6dbc505f5c2b4'
30
+ sha256: '3f30582ec19cf430e6d2f7e9d544cc0f766accc7361f0a3fbb427bcdb7d0298b'
31
31
  };
@@ -1,7 +1,7 @@
1
- export declare const WASM_TYPESCRIPT_ASSET_VERSION = "e48868a1d3851320";
1
+ export declare const WASM_TYPESCRIPT_ASSET_VERSION = "ddfaeea8f8b111b0";
2
2
  export declare const WASM_TYPESCRIPT_MODULE_RECEIPT: Readonly<{
3
- bytes: 3882154;
4
- sha256: "df071064e3d1e8ce1c5bae87853db00021681d069b3ef046a884b95fa58eadfe";
3
+ bytes: 3892294;
4
+ sha256: "2af0cb095c0b02689e6676a576202b71ea87dd6d3e14e4c1e54c21a848eb33b7";
5
5
  }>;
6
6
  export declare const WASM_JAVASCRIPT_MODULE_RECEIPT: Readonly<{
7
7
  bytes: 158899;
@@ -1,7 +1,7 @@
1
- export const WASM_TYPESCRIPT_ASSET_VERSION = 'e48868a1d3851320';
1
+ export const WASM_TYPESCRIPT_ASSET_VERSION = 'ddfaeea8f8b111b0';
2
2
  export const WASM_TYPESCRIPT_MODULE_RECEIPT = Object.freeze({
3
- bytes: 3882154,
4
- sha256: 'df071064e3d1e8ce1c5bae87853db00021681d069b3ef046a884b95fa58eadfe'
3
+ bytes: 3892294,
4
+ sha256: '2af0cb095c0b02689e6676a576202b71ea87dd6d3e14e4c1e54c21a848eb33b7'
5
5
  });
6
6
  export const WASM_JAVASCRIPT_MODULE_RECEIPT = Object.freeze({
7
7
  bytes: 158899,
@@ -1,5 +1,5 @@
1
1
  // Third-party license texts: java-debug-notices.txt beside the shared parser.
2
- import{a as m,b as y}from"../java-debug-FMHDKUN6.js";var N=new Set(["boolean","byte","short","char","int","long","float","double"]),j=new Set(["length","isEmpty","isBlank","charAt","codePointAt","codePointBefore","codePointCount","compareTo","compareToIgnoreCase","equals","equalsIgnoreCase","contains","startsWith","endsWith","indexOf","lastIndexOf","substring","subSequence","trim","strip","stripLeading","stripTrailing","concat","hashCode","toString","regionMatches"]),x=new Set(["substring","subSequence","trim","strip","stripLeading","stripTrailing","concat","toString","valueOf","toHexString","toOctalString","toBinaryString","toUnsignedString"]),T={Math:new Set(["abs","min","max","round","ceil","floor","sqrt","cbrt","pow","sin","cos","tan","asin","acos","atan","atan2","exp","expm1","log","log10","log1p","hypot","signum","copySign","scalb","ulp","nextUp","nextDown","nextAfter","toRadians","toDegrees","addExact","subtractExact","multiplyExact","toIntExact","floorDiv","floorMod","IEEEremainder"]),String:new Set(["valueOf"]),Integer:new Set(["parseInt","parseUnsignedInt","toString","toHexString","toOctalString","toBinaryString","toUnsignedString","compare","compareUnsigned","sum","min","max","bitCount","signum","numberOfLeadingZeros","numberOfTrailingZeros","reverse","reverseBytes","rotateLeft","rotateRight","highestOneBit","lowestOneBit","toUnsignedLong"]),Long:new Set(["parseLong","parseUnsignedLong","toString","toHexString","toOctalString","toBinaryString","toUnsignedString","compare","compareUnsigned","sum","min","max","bitCount","signum","numberOfLeadingZeros","numberOfTrailingZeros","reverse","reverseBytes","rotateLeft","rotateRight","highestOneBit","lowestOneBit"]),Double:new Set(["parseDouble","toString","isNaN","isInfinite","isFinite","compare","sum","min","max"]),Float:new Set(["parseFloat","toString","isNaN","isInfinite","isFinite","compare","sum","min","max"]),Boolean:new Set(["parseBoolean","toString","logicalAnd","logicalOr","logicalXor"]),Character:new Set(["isDigit","isLetter","isLetterOrDigit","isWhitespace","isUpperCase","isLowerCase","toUpperCase","toLowerCase","toTitleCase","getNumericValue","digit","toString"])},A={Math:new Set(["PI","E"]),Integer:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Long:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Short:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Byte:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Character:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Double:new Set(["MIN_VALUE","MIN_NORMAL","MAX_VALUE","NaN","POSITIVE_INFINITY","NEGATIVE_INFINITY"]),Float:new Set(["MIN_VALUE","MIN_NORMAL","MAX_VALUE","NaN","POSITIVE_INFINITY","NEGATIVE_INFINITY"])},b=m((t,i)=>(t.children[i]??[]).flatMap(s=>"children"in s?[s]:[]),"nodes"),L=m((t,i)=>(t.children[i]??[]).filter(s=>!("children"in s)),"tokens");function E(t){return Object.entries(t.children).flatMap(([i,s])=>s.flatMap(f=>"children"in f?E(f):i==="Identifier"?[f]:[])).sort((i,s)=>i.startOffset-s.startOffset)}m(E,"identifiers");function M(t,i){let s=new Set;if(/\\u+[0-9a-fA-F]{4}/.test(t))throw new Error("Java evaluation does not support Unicode preprocessing escapes.");let{cst:f,tokens:o}=y(t,"expression"),S=new Set(["PlusPlus","MinusMinus","New","This","Super","Arrow","DoubleColon","LSquare","LCurly","Class","Instanceof","At"]);if(o.some(a=>S.has(a.tokenType.name)))throw new Error("Java evaluation supports read-only scalar/String expressions; mutation, objects, arrays and closures are unsupported.");let d=new Map,h=m(a=>{if(d.has(a))return d.get(a);if(a.children.AssignmentOperator)throw new Error("Java evaluation does not allow assignment or mutation.");if(a.name==="conditionalExpression"&&a.children.QuestionMark)throw new Error("Java snapshot evaluation does not support conditional expressions because compile-time constant narrowing is unavailable.");if(a.name==="typeArguments")throw new Error("Java evaluation does not support generic or user-type expressions.");let e=Object.values(a.children).flat().flatMap(p=>"children"in p?[p]:[]).map(h),n=e.includes("string")?"string":e.includes("null")?"null":"scalar";if(a.name==="literal")n=a.children.StringLiteral||a.children.TextBlock?"string":a.children.Null?"null":"scalar";else if(a.name==="referenceTypeCastExpression"){if(E(b(a,"referenceType")[0]).map(v=>v.image).join(".")!=="java.lang.String")throw new Error("Java evaluation supports only primitive and fully qualified java.lang.String casts.");n="string"}else if(a.name==="primitiveCastExpression")n="scalar";else if(a.name==="primary"){let p=b(a,"primaryPrefix")[0],v=b(p,"fqnOrRefType")[0],g=b(a,"primarySuffix"),I=0;if(v){let r=E(v).map(c=>c.image),l=!!g[0]?.children.methodInvocationSuffix,u=i.get(r[0]);if(u){if(u.unavailable!==void 0)throw new Error(`Java evaluation cannot use ${u.name}: ${u.unavailable}`);if(!N.has(u.type)&&u.type!=="String"&&u.type!=="java.lang.String")throw new Error(`Java evaluation cannot use ${u.name} (${u.type}); inspect this target reference in Variables.`);if(s.add(u.name),n=N.has(u.type)?"scalar":"string",r.length!==1||l){if(r.length!==2||!l||n!=="string"||!j.has(r[1]))throw new Error("Java evaluation cannot call target methods or access target fields.");n=x.has(r[1])?"string":"scalar",I=1}}else{let c=r.slice(2);if(r[0]!=="java"||r[1]!=="lang"||c.length!==2||(l?!Object.hasOwn(T,c[0])||!T[c[0]].has(c[1]):!Object.hasOwn(A,c[0])||!A[c[0]].has(c[1])))throw new Error(`Java evaluation cannot resolve ${r.join(".")}; use scalar/String locals or fully qualified java.lang library calls/constants.`);n=l&&x.has(c[1])?"string":"scalar",I=l?1:0}}for(let r=I;r<g.length;r+=2){let l=L(g[r],"Identifier")[0]?.image;if(n!=="string"||!l||!j.has(l)||!g[r+1]?.children.methodInvocationSuffix)throw new Error("Java evaluation supports only approved String methods on expression results.");n=x.has(l)?"string":"scalar"}}else if(a.name==="binaryExpression"){let p=b(a,"unaryExpression").map(h),v=L(a,"BinaryOperator");for(let[g,I]of v.entries()){let r=[g,g+1].some(l=>p[l]==="null"&&v[l-1]?.image!=="+"&&v[l]?.image!=="+");if(["==","!="].includes(I.image)&&(p[g]==="string"||p[g+1]==="string")&&!r)throw new Error("Java snapshot evaluation cannot compare String reference identity; use equals() for String contents.")}v.some(g=>["==","!=","<",">","<=",">=","&&","||"].includes(g.image))&&(n="scalar")}return d.set(a,n),n},"visit");return h(f),s}m(M,"validateExpression");function $(t){if(typeof t.expression!="string"||!t.expression.trim()||new TextEncoder().encode(t.expression).length>4096)throw new Error("Java expressions must contain 1\u20134096 UTF-8 bytes.");if(!Array.isArray(t.bindings)||t.bindings.length>1024)throw new Error("Java evaluation supports at most 1024 local bindings.");let i=new Map;for(let e of t.bindings){if(!e||typeof e.name!="string"||typeof e.type!="string"||e.value!==null&&typeof e.value!="string"||e.unavailable!==void 0&&typeof e.unavailable!="string")throw new Error("Invalid Java evaluation binding.");let n=y(e.name,"expression");if(n.tokens.length!==1||E(n.cst)[0]?.image!==e.name||i.has(e.name)||/\\/.test(e.name))throw new Error(`Invalid or duplicate Java local name: ${e.name}`);i.set(e.name,{...e})}let s=M(t.expression,i),f=0,o="WasmIdleEval";for(;t.expression.includes(o)||[...i.keys()].some(e=>e.includes(o));)o=`WasmIdleEval_${++f}`;let S=`${o}_args`,d=[],h=[],a={byte:"java.lang.Byte.parseByte(value)",short:"java.lang.Short.parseShort(value)",int:"java.lang.Integer.parseInt(value)",long:"java.lang.Long.parseLong(value)",float:'value.equals("NaN") ? java.lang.Float.NaN : value.equals("Infinity") ? java.lang.Float.POSITIVE_INFINITY : value.equals("-Infinity") ? java.lang.Float.NEGATIVE_INFINITY : value.equals("-0.0") ? java.lang.Float.intBitsToFloat(java.lang.Integer.MIN_VALUE) : java.lang.Float.parseFloat(value)',double:'value.equals("NaN") ? java.lang.Double.NaN : value.equals("Infinity") ? java.lang.Double.POSITIVE_INFINITY : value.equals("-Infinity") ? java.lang.Double.NEGATIVE_INFINITY : value.equals("-0.0") ? java.lang.Double.longBitsToDouble(java.lang.Long.MIN_VALUE) : java.lang.Double.parseDouble(value)',boolean:"java.lang.Boolean.parseBoolean(value)",char:"(char) java.lang.Integer.parseInt(value)"},w=0;for(let e of i.values()){if(!s.has(e.name))continue;if(w+=new TextEncoder().encode(e.value??"").length,w>65536)throw new Error("Java evaluation binding values exceed 65536 UTF-8 bytes.");let n=d.length;if(N.has(e.type)){if(e.value===null||e.type==="char"&&(!/^\d{1,5}$/.test(e.value)||Number(e.value)>65535)||e.type==="boolean"&&!["true","false"].includes(e.value))throw new Error(`Invalid ${e.type} value for Java local ${e.name}.`);d.push(e.value),h.push(`final ${e.type} ${e.name} = ${o}_${e.type}(${S}[${n}]);`)}else(e.type==="String"||e.type==="java.lang.String")&&(d.push(e.value===null?"1":"0",e.value??""),h.push(`final java.lang.String ${e.name} = ${S}[${n}].equals("1") ? null : ${S}[${n+1}];`))}return{args:d,code:`public final class ${o} {
2
+ import{a as m,b as y}from"../java-debug-HUZVAK4F.js";var N=new Set(["boolean","byte","short","char","int","long","float","double"]),j=new Set(["length","isEmpty","isBlank","charAt","codePointAt","codePointBefore","codePointCount","compareTo","compareToIgnoreCase","equals","equalsIgnoreCase","contains","startsWith","endsWith","indexOf","lastIndexOf","substring","subSequence","trim","strip","stripLeading","stripTrailing","concat","hashCode","toString","regionMatches"]),x=new Set(["substring","subSequence","trim","strip","stripLeading","stripTrailing","concat","toString","valueOf","toHexString","toOctalString","toBinaryString","toUnsignedString"]),T={Math:new Set(["abs","min","max","round","ceil","floor","sqrt","cbrt","pow","sin","cos","tan","asin","acos","atan","atan2","exp","expm1","log","log10","log1p","hypot","signum","copySign","scalb","ulp","nextUp","nextDown","nextAfter","toRadians","toDegrees","addExact","subtractExact","multiplyExact","toIntExact","floorDiv","floorMod","IEEEremainder"]),String:new Set(["valueOf"]),Integer:new Set(["parseInt","parseUnsignedInt","toString","toHexString","toOctalString","toBinaryString","toUnsignedString","compare","compareUnsigned","sum","min","max","bitCount","signum","numberOfLeadingZeros","numberOfTrailingZeros","reverse","reverseBytes","rotateLeft","rotateRight","highestOneBit","lowestOneBit","toUnsignedLong"]),Long:new Set(["parseLong","parseUnsignedLong","toString","toHexString","toOctalString","toBinaryString","toUnsignedString","compare","compareUnsigned","sum","min","max","bitCount","signum","numberOfLeadingZeros","numberOfTrailingZeros","reverse","reverseBytes","rotateLeft","rotateRight","highestOneBit","lowestOneBit"]),Double:new Set(["parseDouble","toString","isNaN","isInfinite","isFinite","compare","sum","min","max"]),Float:new Set(["parseFloat","toString","isNaN","isInfinite","isFinite","compare","sum","min","max"]),Boolean:new Set(["parseBoolean","toString","logicalAnd","logicalOr","logicalXor"]),Character:new Set(["isDigit","isLetter","isLetterOrDigit","isWhitespace","isUpperCase","isLowerCase","toUpperCase","toLowerCase","toTitleCase","getNumericValue","digit","toString"])},A={Math:new Set(["PI","E"]),Integer:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Long:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Short:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Byte:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Character:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Double:new Set(["MIN_VALUE","MIN_NORMAL","MAX_VALUE","NaN","POSITIVE_INFINITY","NEGATIVE_INFINITY"]),Float:new Set(["MIN_VALUE","MIN_NORMAL","MAX_VALUE","NaN","POSITIVE_INFINITY","NEGATIVE_INFINITY"])},b=m((t,i)=>(t.children[i]??[]).flatMap(s=>"children"in s?[s]:[]),"nodes"),L=m((t,i)=>(t.children[i]??[]).filter(s=>!("children"in s)),"tokens");function E(t){return Object.entries(t.children).flatMap(([i,s])=>s.flatMap(f=>"children"in f?E(f):i==="Identifier"?[f]:[])).sort((i,s)=>i.startOffset-s.startOffset)}m(E,"identifiers");function M(t,i){let s=new Set;if(/\\u+[0-9a-fA-F]{4}/.test(t))throw new Error("Java evaluation does not support Unicode preprocessing escapes.");let{cst:f,tokens:o}=y(t,"expression"),S=new Set(["PlusPlus","MinusMinus","New","This","Super","Arrow","DoubleColon","LSquare","LCurly","Class","Instanceof","At"]);if(o.some(a=>S.has(a.tokenType.name)))throw new Error("Java evaluation supports read-only scalar/String expressions; mutation, objects, arrays and closures are unsupported.");let d=new Map,h=m(a=>{if(d.has(a))return d.get(a);if(a.children.AssignmentOperator)throw new Error("Java evaluation does not allow assignment or mutation.");if(a.name==="conditionalExpression"&&a.children.QuestionMark)throw new Error("Java snapshot evaluation does not support conditional expressions because compile-time constant narrowing is unavailable.");if(a.name==="typeArguments")throw new Error("Java evaluation does not support generic or user-type expressions.");let e=Object.values(a.children).flat().flatMap(p=>"children"in p?[p]:[]).map(h),n=e.includes("string")?"string":e.includes("null")?"null":"scalar";if(a.name==="literal")n=a.children.StringLiteral||a.children.TextBlock?"string":a.children.Null?"null":"scalar";else if(a.name==="referenceTypeCastExpression"){if(E(b(a,"referenceType")[0]).map(v=>v.image).join(".")!=="java.lang.String")throw new Error("Java evaluation supports only primitive and fully qualified java.lang.String casts.");n="string"}else if(a.name==="primitiveCastExpression")n="scalar";else if(a.name==="primary"){let p=b(a,"primaryPrefix")[0],v=b(p,"fqnOrRefType")[0],g=b(a,"primarySuffix"),I=0;if(v){let r=E(v).map(c=>c.image),l=!!g[0]?.children.methodInvocationSuffix,u=i.get(r[0]);if(u){if(u.unavailable!==void 0)throw new Error(`Java evaluation cannot use ${u.name}: ${u.unavailable}`);if(!N.has(u.type)&&u.type!=="String"&&u.type!=="java.lang.String")throw new Error(`Java evaluation cannot use ${u.name} (${u.type}); inspect this target reference in Variables.`);if(s.add(u.name),n=N.has(u.type)?"scalar":"string",r.length!==1||l){if(r.length!==2||!l||n!=="string"||!j.has(r[1]))throw new Error("Java evaluation cannot call target methods or access target fields.");n=x.has(r[1])?"string":"scalar",I=1}}else{let c=r.slice(2);if(r[0]!=="java"||r[1]!=="lang"||c.length!==2||(l?!Object.hasOwn(T,c[0])||!T[c[0]].has(c[1]):!Object.hasOwn(A,c[0])||!A[c[0]].has(c[1])))throw new Error(`Java evaluation cannot resolve ${r.join(".")}; use scalar/String locals or fully qualified java.lang library calls/constants.`);n=l&&x.has(c[1])?"string":"scalar",I=l?1:0}}for(let r=I;r<g.length;r+=2){let l=L(g[r],"Identifier")[0]?.image;if(n!=="string"||!l||!j.has(l)||!g[r+1]?.children.methodInvocationSuffix)throw new Error("Java evaluation supports only approved String methods on expression results.");n=x.has(l)?"string":"scalar"}}else if(a.name==="binaryExpression"){let p=b(a,"unaryExpression").map(h),v=L(a,"BinaryOperator");for(let[g,I]of v.entries()){let r=[g,g+1].some(l=>p[l]==="null"&&v[l-1]?.image!=="+"&&v[l]?.image!=="+");if(["==","!="].includes(I.image)&&(p[g]==="string"||p[g+1]==="string")&&!r)throw new Error("Java snapshot evaluation cannot compare String reference identity; use equals() for String contents.")}v.some(g=>["==","!=","<",">","<=",">=","&&","||"].includes(g.image))&&(n="scalar")}return d.set(a,n),n},"visit");return h(f),s}m(M,"validateExpression");function $(t){if(typeof t.expression!="string"||!t.expression.trim()||new TextEncoder().encode(t.expression).length>4096)throw new Error("Java expressions must contain 1\u20134096 UTF-8 bytes.");if(!Array.isArray(t.bindings)||t.bindings.length>1024)throw new Error("Java evaluation supports at most 1024 local bindings.");let i=new Map;for(let e of t.bindings){if(!e||typeof e.name!="string"||typeof e.type!="string"||e.value!==null&&typeof e.value!="string"||e.unavailable!==void 0&&typeof e.unavailable!="string")throw new Error("Invalid Java evaluation binding.");let n=y(e.name,"expression");if(n.tokens.length!==1||E(n.cst)[0]?.image!==e.name||i.has(e.name)||/\\/.test(e.name))throw new Error(`Invalid or duplicate Java local name: ${e.name}`);i.set(e.name,{...e})}let s=M(t.expression,i),f=0,o="WasmIdleEval";for(;t.expression.includes(o)||[...i.keys()].some(e=>e.includes(o));)o=`WasmIdleEval_${++f}`;let S=`${o}_args`,d=[],h=[],a={byte:"java.lang.Byte.parseByte(value)",short:"java.lang.Short.parseShort(value)",int:"java.lang.Integer.parseInt(value)",long:"java.lang.Long.parseLong(value)",float:'value.equals("NaN") ? java.lang.Float.NaN : value.equals("Infinity") ? java.lang.Float.POSITIVE_INFINITY : value.equals("-Infinity") ? java.lang.Float.NEGATIVE_INFINITY : value.equals("-0.0") ? java.lang.Float.intBitsToFloat(java.lang.Integer.MIN_VALUE) : java.lang.Float.parseFloat(value)',double:'value.equals("NaN") ? java.lang.Double.NaN : value.equals("Infinity") ? java.lang.Double.POSITIVE_INFINITY : value.equals("-Infinity") ? java.lang.Double.NEGATIVE_INFINITY : value.equals("-0.0") ? java.lang.Double.longBitsToDouble(java.lang.Long.MIN_VALUE) : java.lang.Double.parseDouble(value)',boolean:"java.lang.Boolean.parseBoolean(value)",char:"(char) java.lang.Integer.parseInt(value)"},w=0;for(let e of i.values()){if(!s.has(e.name))continue;if(w+=new TextEncoder().encode(e.value??"").length,w>65536)throw new Error("Java evaluation binding values exceed 65536 UTF-8 bytes.");let n=d.length;if(N.has(e.type)){if(e.value===null||e.type==="char"&&(!/^\d{1,5}$/.test(e.value)||Number(e.value)>65535)||e.type==="boolean"&&!["true","false"].includes(e.value))throw new Error(`Invalid ${e.type} value for Java local ${e.name}.`);d.push(e.value),h.push(`final ${e.type} ${e.name} = ${o}_${e.type}(${S}[${n}]);`)}else(e.type==="String"||e.type==="java.lang.String")&&(d.push(e.value===null?"1":"0",e.value??""),h.push(`final java.lang.String ${e.name} = ${S}[${n}].equals("1") ? null : ${S}[${n+1}];`))}return{args:d,code:`public final class ${o} {
3
3
  ${Object.entries(a).map(([e,n])=>` private static ${e} ${o}_${e}(java.lang.String value) { return ${n}; }`).join(`
4
4
  `)}
5
5
  ${String.raw` private static java.lang.String ${o}_quote(java.lang.String value) {
@@ -4,6 +4,7 @@ import { parsePythonPackageLock } from '../pythonPackageLock';
4
4
  import { WASM_APECODE_VERSION, WASM_APECODE_WHEELS } from '../wasmApecodeVersion';
5
5
  import { withCachedPyodideModule } from './runtimeModule';
6
6
  import { createPythonExecutionHelpers } from './pythonExecution';
7
+ import { compilePythonBytecode } from './pythonCompile';
7
8
  import { createPythonWorkspaceImports } from './pythonWorkspaceImports';
8
9
  import { createPythonWorkspaceFiles } from './pythonWorkspaceFiles';
9
10
  import { PYTHON_DEBUG_PREVIEW } from './pythonDebugPreview';
@@ -491,7 +492,7 @@ None
491
492
  self.onmessage = async (event) => {
492
493
  if (handleWorkerAssetMessage(event.data))
493
494
  return;
494
- const { code, buffer, debugBuffer, watchBuffer, watchResultBuffer, load, interrupt, assets, prepare, stdin, debug = false, breakpoints = [], pauseOnEntry = false, activePath, debugPath, workspaceFiles, language = 'python', extension } = event.data;
495
+ const { code, buffer, debugBuffer, watchBuffer, watchResultBuffer, load, interrupt, assets, compile, fileName, optimize, invalidationMode, timestamp, maxArtifactBytes, prepare, stdin, debug = false, breakpoints = [], pauseOnEntry = false, activePath, debugPath, workspaceFiles, language = 'python', extension } = event.data;
495
496
  const isHy = language === 'hy';
496
497
  const isAheui = language === 'aheui';
497
498
  const isApecode = language === 'apecode';
@@ -522,6 +523,28 @@ self.onmessage = async (event) => {
522
523
  self.postMessage({ error: e.message || 'Unknown error' });
523
524
  }
524
525
  }
526
+ else if (compile) {
527
+ try {
528
+ if (language !== 'python')
529
+ throw new Error('Bytecode compilation is supported only for Python');
530
+ await loadPyodide(baseUrl);
531
+ postProgress(10, 'Compiling Python bytecode');
532
+ const compiled = compilePythonBytecode(pyodide, code, fileName, optimize, maxArtifactBytes, {
533
+ invalidationMode,
534
+ timestamp
535
+ });
536
+ postProgress(100, 'Python bytecode ready');
537
+ self.postMessage({ compiled }, [compiled.data.buffer]);
538
+ }
539
+ catch (e) {
540
+ self.postMessage({
541
+ error: e.message || 'Unknown error',
542
+ ...(e.code === 'output-limit'
543
+ ? { outputLimit: { actual: e.actual, limit: e.limit } }
544
+ : {})
545
+ });
546
+ }
547
+ }
525
548
  else if (prepare) {
526
549
  preparedPackagesKey = undefined;
527
550
  try {
@@ -0,0 +1,4 @@
1
+ import type { PyodideInterface } from 'pyodide';
2
+ import { type PythonCompileOptions, type PythonCompileResult } from '../pythonCompileOptions';
3
+ /** Compile with CPython without executing source or resolving its imports. */
4
+ export declare function compilePythonBytecode(runtime: PyodideInterface, code: string, fileName: string, optimize: 0 | 1 | 2, maxArtifactBytes: number, options?: Pick<PythonCompileOptions, 'invalidationMode' | 'timestamp'>): PythonCompileResult;
@@ -0,0 +1,122 @@
1
+ import { OutputLimitError } from '@wasm-idle/core';
2
+ import { resolvePythonBytecodeOptions } from '../pythonCompileOptions';
3
+ const PYTHON_COMPILE = String.raw `
4
+ def compile_bytecode(source, filename, optimization, byte_limit, invalidation_mode, timestamp):
5
+ import codecs
6
+ import importlib.util
7
+ import io
8
+ import os
9
+ import platform
10
+ import py_compile
11
+ import sys
12
+ import tempfile
13
+ import tokenize
14
+
15
+ source_text = source.removeprefix("\ufeff")
16
+ encoding = "utf-8"
17
+ # Read only the coding-cookie metadata. detect_encoding also validates
18
+ # header bytes, which do not yet exist in the declared encoding.
19
+ # Universal newlines apply only to this scan, preserving the source hash.
20
+ with io.StringIO(source_text, newline=None) as lines:
21
+ for _ in range(2):
22
+ header = lines.readline().encode("ascii", "replace")
23
+ cookie = tokenize.cookie_re.match(header)
24
+ if cookie:
25
+ encoding = tokenize._get_normal_name(cookie.group(1).decode("ascii"))
26
+ try:
27
+ codecs.lookup(encoding)
28
+ except LookupError:
29
+ raise SyntaxError("unknown encoding: " + encoding) from None
30
+ break
31
+ if not tokenize.blank_re.match(header):
32
+ break
33
+ if source.startswith("\ufeff"):
34
+ if encoding != "utf-8":
35
+ raise SyntaxError("encoding problem: utf-8")
36
+ encoding = "utf-8-sig"
37
+ # Encode the original text; py_compile validates the actual source bytes.
38
+ encoded_source = source_text.encode(encoding)
39
+ mode = {
40
+ "checked-hash": py_compile.PycInvalidationMode.CHECKED_HASH,
41
+ "unchecked-hash": py_compile.PycInvalidationMode.UNCHECKED_HASH,
42
+ "timestamp": py_compile.PycInvalidationMode.TIMESTAMP,
43
+ }[invalidation_mode]
44
+
45
+ with tempfile.TemporaryDirectory(prefix="wasm-idle-pyc-") as directory:
46
+ source_path = os.path.join(directory, "main.py")
47
+ output_path = os.path.join(directory, "output.pyc")
48
+ with open(source_path, "wb") as source_file:
49
+ source_file.write(encoded_source)
50
+ if invalidation_mode == "timestamp":
51
+ os.utime(source_path, (timestamp, timestamp))
52
+ py_compile.compile(
53
+ source_path,
54
+ cfile=output_path,
55
+ dfile=filename,
56
+ doraise=True,
57
+ optimize=optimization,
58
+ invalidation_mode=mode,
59
+ )
60
+ size = os.path.getsize(output_path)
61
+ if size > byte_limit:
62
+ return {"byteLimitExceeded": size}
63
+ with open(output_path, "rb") as output_file:
64
+ data = output_file.read()
65
+ return {
66
+ "data": data,
67
+ "pythonVersion": platform.python_version(),
68
+ "cacheTag": sys.implementation.cache_tag,
69
+ "magicNumber": importlib.util.MAGIC_NUMBER.hex(),
70
+ }
71
+
72
+ compile_bytecode(source, filename, optimization, byte_limit, invalidation_mode, timestamp)
73
+ `;
74
+ /** Compile with CPython without executing source or resolving its imports. */
75
+ export function compilePythonBytecode(runtime, code, fileName, optimize, maxArtifactBytes, options = {}) {
76
+ if (typeof code !== 'string')
77
+ throw new TypeError('Python source must be a string');
78
+ if (typeof fileName !== 'string' || !/\.py$/i.test(fileName))
79
+ throw new TypeError('Python source file name must end in .py');
80
+ if (![0, 1, 2].includes(optimize))
81
+ throw new TypeError('Python optimization must be 0, 1, or 2');
82
+ if (!Number.isSafeInteger(maxArtifactBytes) || maxArtifactBytes <= 0)
83
+ throw new TypeError('Python artifact byte limit must be a positive safe integer');
84
+ const { invalidationMode, timestamp } = resolvePythonBytecodeOptions(options);
85
+ // A private namespace keeps source and filenames out of executable bridge text.
86
+ const globals = runtime.toPy({
87
+ source: code,
88
+ filename: fileName,
89
+ optimization: optimize,
90
+ byte_limit: maxArtifactBytes,
91
+ invalidation_mode: invalidationMode,
92
+ timestamp: timestamp ?? 0
93
+ });
94
+ try {
95
+ const result = runtime.runPython(PYTHON_COMPILE, { globals });
96
+ try {
97
+ const converted = result.toJs({
98
+ dict_converter: Object.fromEntries,
99
+ create_pyproxies: false
100
+ });
101
+ if ('byteLimitExceeded' in converted) {
102
+ throw new OutputLimitError(`Python bytecode is ${converted.byteLimitExceeded} bytes; limit is ${maxArtifactBytes}`, {
103
+ runtimeId: 'PYTHON3',
104
+ phase: 'compile',
105
+ actual: converted.byteLimitExceeded,
106
+ limit: maxArtifactBytes
107
+ });
108
+ }
109
+ return {
110
+ ...converted,
111
+ path: fileName.replace(/\.py$/i, '.pyc'),
112
+ data: Uint8Array.from(converted.data)
113
+ };
114
+ }
115
+ finally {
116
+ result.destroy();
117
+ }
118
+ }
119
+ finally {
120
+ globals.destroy();
121
+ }
122
+ }
@@ -0,0 +1,8 @@
1
+ import type { PythonCompileOptions, PythonCompileResult } from './playground/pythonCompileOptions';
2
+ export type { PythonCompileOptions, PythonCompileResult } from './playground/pythonCompileOptions';
3
+ /**
4
+ * Compile one source file without executing it or loading its imports.
5
+ * A dedicated worker keeps compilation independent of active playground sessions.
6
+ * Its runtime, temporary files, and proxies are disposed on every exit path.
7
+ */
8
+ export declare function compilePython(code: string, options?: PythonCompileOptions): Promise<PythonCompileResult>;
@@ -0,0 +1,52 @@
1
+ import { TimeoutError } from '@wasm-idle/core';
2
+ import { resolvePythonCompileRequest } from './playground/pythonCompileOptions';
3
+ /**
4
+ * Compile one source file without executing it or loading its imports.
5
+ * A dedicated worker keeps compilation independent of active playground sessions.
6
+ * Its runtime, temporary files, and proxies are disposed on every exit path.
7
+ */
8
+ export async function compilePython(code, options = {}) {
9
+ const request = { ...options, ...resolvePythonCompileRequest(code, options) };
10
+ request.signal?.throwIfAborted();
11
+ const importStartedAt = performance.now();
12
+ const { startupTimeoutMs } = request.limits;
13
+ const startupTimeout = new TimeoutError(`Python runtime startup timed out after ${startupTimeoutMs} ms`, { runtimeId: 'PYTHON3', phase: 'startup', timeoutMs: startupTimeoutMs });
14
+ let timeout;
15
+ let onAbort;
16
+ // Native imports cannot be cancelled, but callers must not wait for a stalled chunk.
17
+ // The race also handles late import failures without creating a compiler afterward.
18
+ const { default: Python } = await Promise.race([
19
+ import('./playground/python'),
20
+ new Promise((_resolve, reject) => {
21
+ timeout = setTimeout(() => reject(startupTimeout), startupTimeoutMs);
22
+ onAbort = () => reject(request.signal?.reason);
23
+ request.signal?.addEventListener('abort', onAbort, { once: true });
24
+ if (request.signal?.aborted)
25
+ onAbort();
26
+ })
27
+ ]).finally(() => {
28
+ if (timeout !== undefined)
29
+ clearTimeout(timeout);
30
+ if (onAbort)
31
+ request.signal?.removeEventListener('abort', onAbort);
32
+ });
33
+ request.signal?.throwIfAborted();
34
+ const remainingStartupMs = Math.ceil(startupTimeoutMs - (performance.now() - importStartedAt));
35
+ if (remainingStartupMs <= 0)
36
+ throw startupTimeout;
37
+ const compiler = new Python();
38
+ try {
39
+ await compiler.load(request.runtimeAssets, '', false, [], { ...request, limits: { ...request.limits, startupTimeoutMs: remainingStartupMs } }, request.progress);
40
+ return await compiler.compile(code, request);
41
+ }
42
+ catch (error) {
43
+ if (request.signal?.aborted && error === request.signal.reason)
44
+ throw error;
45
+ if (typeof error === 'string')
46
+ throw new Error(error);
47
+ throw error;
48
+ }
49
+ finally {
50
+ await compiler.dispose();
51
+ }
52
+ }