echidnae-javascript 0.3.0__py3-none-any.whl

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,117 @@
1
+ import {createModule} from './app.mjs';
2
+ import {Peer,DEFAULT_LIMITS,MAX_ID,application,grants,limits,exact,id,tagText,tagged,handle,failure,errorInfo,validError} from './browser-protocol.mjs';
3
+
4
+ const REQUIRED_CAPABILITIES=/*CAPABILITIES*/[];
5
+ let peer=null,state='created',budget=null,controller=null,requestCounter=0,callbackCounter=0,lastHandle=0,outputCount=0,eventCount=0;
6
+ const pending=new Map(),callbacks=new Map(),subscriptions=new Map();
7
+ let output=Promise.resolve(),events=Promise.resolve();
8
+ function close(reason='stop') {
9
+ if(state==='closed')return;
10
+ state='closed';controller?.abort();
11
+ for(const entry of pending.values()){clearTimeout(entry.timer);entry.reject(failure('CANCELLED','Worker closed.','AbortError'));}
12
+ pending.clear();callbacks.clear();subscriptions.clear();
13
+ try{peer?.send('closed');}catch{}
14
+ self.close();
15
+ }
16
+ function fatal(error) {
17
+ if(state==='closed')return;
18
+ try{peer?.send('fatal',{error:errorInfo(error)});}catch{}
19
+ close('error');
20
+ }
21
+ function request(operation,args) {
22
+ if(state!=='ready')return Promise.reject(failure('PROTOCOL','No host requests before ready.','ProtocolError','protocol'));
23
+ if(pending.size>=budget.pending_requests||requestCounter>=MAX_ID)return Promise.reject(failure('QUOTA','Pending host request limit exceeded.'));
24
+ const requestId='w'+(++requestCounter);
25
+ return new Promise((resolve,reject)=>{
26
+ const entry={resolve,reject,operation,args,done:false,timer:null};
27
+ entry.timer=setTimeout(()=>{
28
+ if(!pending.has(requestId)||entry.done)return;
29
+ entry.done=true;reject(failure('TIMEOUT','Host request timed out.'));
30
+ try{peer.send('cancel',{reply_to:requestId});}catch(error){fatal(error);}
31
+ // Retain the slot until the peer's terminal reply or teardown.
32
+ },budget.deadline_ms);
33
+ pending.set(requestId,entry);
34
+ try{peer.send('request',{id:requestId,operation,arguments:args,timeout_ms:budget.deadline_ms});}
35
+ catch(error){clearTimeout(entry.timer);pending.delete(requestId);reject(error);}
36
+ });
37
+ }
38
+ const host={request,
39
+ registerCallback(fn) {
40
+ if(typeof fn!=='function'||callbacks.size>=budget.subscriptions||callbackCounter>=MAX_ID)throw failure('QUOTA','Callback limit exceeded.');
41
+ const wire={type:'handle',owner:'worker',kind:'callback',id:'w'+(++callbackCounter)};
42
+ callbacks.set(wire.id,fn);return wire;
43
+ },
44
+ releaseCallback(wire){handle(wire,'worker','callback');callbacks.delete(wire.id);}
45
+ };
46
+ function write(value) {
47
+ if(typeof value!=='string')throw failure('BAD_VALUE','Output requires text.');
48
+ const taggedText=tagText(value);
49
+ if(outputCount+taggedText.codepoints.length>budget.output_codepoints)throw failure('QUOTA','Output limit exceeded.');
50
+ outputCount+=taggedText.codepoints.length;
51
+ output=output.then(()=>request('output.write',{stream:'stdout',text:taggedText}));
52
+ output.catch(fatal);
53
+ }
54
+ function result(message) {
55
+ if(!id(message.reply_to,'w')||!pending.has(message.reply_to))throw failure('PROTOCOL','Duplicate or unknown host reply.','ProtocolError','protocol');
56
+ const entry=pending.get(message.reply_to);
57
+ if(Object.hasOwn(message,'error'))validError(message.error);else tagged(message.value,0,budget.value_depth);
58
+ clearTimeout(entry.timer);pending.delete(message.reply_to);
59
+ if(Object.hasOwn(message,'error')){if(!entry.done)entry.reject(message.error);return;}
60
+ if(entry.operation==='events.subscribe') {
61
+ handle(message.value,'main','event.subscription');
62
+ const number=Number(message.value.id.slice(1));
63
+ if(number<=lastHandle)throw failure('PROTOCOL','Reused main resource ID.','ProtocolError','protocol');
64
+ lastHandle=number;
65
+ if(entry.done){request('handles.release',{handles:[message.value]}).catch(fatal);return;}
66
+ subscriptions.set(message.value.id,entry.args.callback.id);
67
+ }
68
+ if(entry.operation==='events.unsubscribe')subscriptions.delete(entry.args.subscription.id);
69
+ if(entry.operation==='handles.release')for(const wire of entry.args.handles)subscriptions.delete(wire.id);
70
+ if(!entry.done)entry.resolve(message.value);
71
+ }
72
+ function event(message) {
73
+ handle(message.subscription,'main','event.subscription');handle(message.callback,'worker','callback');
74
+ tagged(message.value,0,budget.value_depth);
75
+ const expected=subscriptions.get(message.subscription.id);
76
+ if(!expected){
77
+ if(Number(message.subscription.id.slice(1))<=lastHandle)return;
78
+ throw failure('PROTOCOL','Event references an unknown subscription.','ProtocolError','protocol');
79
+ }
80
+ if(expected!==message.callback.id)throw failure('PROTOCOL','Event callback does not own its subscription.','ProtocolError','protocol');
81
+ if(!callbacks.has(expected))return;
82
+ if(eventCount>=budget.pending_requests)throw failure('QUOTA','Event queue overflow.');
83
+ eventCount++;
84
+ events=events.then(async()=>{
85
+ if(state!=='ready'||subscriptions.get(message.subscription.id)!==expected||!callbacks.has(expected))return;
86
+ await callbacks.get(expected)(message.value);await output;
87
+ }).finally(()=>{eventCount--;});
88
+ events.catch(fatal);
89
+ }
90
+ async function initialize(message) {
91
+ if(state!=='created')throw failure('PROTOCOL','Duplicate initialization.','ProtocolError','protocol');
92
+ peer=new Peer(message.session,value=>self.postMessage(value));
93
+ const init=peer.receive(message);if(!init||init.kind!=='init')throw failure('PROTOCOL','Worker requires init first.','ProtocolError','protocol');
94
+ if(!exact(init.limits,Object.keys(DEFAULT_LIMITS)))throw failure('PROTOCOL','Init must declare every limit.','ProtocolError','protocol');
95
+ state='initializing';const app=application(init.application),capabilities=grants(init.capabilities);budget=limits(init.limits);peer.budget=budget.message_bytes;
96
+ if(REQUIRED_CAPABILITIES.some(name=>!capabilities.some(value=>value.id===name)))throw failure('UNAVAILABLE','A compiled application capability is missing.');
97
+ controller=new AbortController();
98
+ const module=createModule({write,signal:controller.signal,host});
99
+ if(typeof module.main!=='function')throw failure('BAD_VALUE','Browser entry requires main().');
100
+ state='ready';peer.send('ready',{application:app,capabilities:capabilities.map(value=>value.id),limits:budget});
101
+ await module.main();await output;
102
+ }
103
+ self.onmessage=eventMessage=>{
104
+ if(state==='closed')return;
105
+ if(state==='created'){initialize(eventMessage.data).catch(fatal);return;}
106
+ try{
107
+ const message=peer.receive(eventMessage.data);if(!message)return;
108
+ if(message.kind==='close'){
109
+ if(!['stop','restart','completed','error'].includes(message.reason))throw failure('PROTOCOL','Invalid close reason.','ProtocolError','protocol');
110
+ close(message.reason);return;
111
+ }
112
+ if(state!=='ready')throw failure('PROTOCOL','Host message before ready.','ProtocolError','protocol');
113
+ if(message.kind==='result'){result(message);return;}
114
+ if(message.kind==='event'){event(message);return;}
115
+ throw failure('PROTOCOL','Unexpected host message.','ProtocolError','protocol');
116
+ }catch(error){fatal(error);}
117
+ };
@@ -0,0 +1,466 @@
1
+ """Original, dependency-selected ECMAScript helpers for python-browser/1."""
2
+
3
+ from functools import lru_cache
4
+ import json
5
+
6
+
7
+ HELPERS = {
8
+ 'error': ((), r'''
9
+ class $PyError extends Error {
10
+ constructor(name, message, location) { super(message); this.name = name; this.location = location; }
11
+ }
12
+ const $raisedErrors = new WeakSet();
13
+ function $markRaised(error, location) {
14
+ if (!$raisedErrors.has(error)) { error.location = {...location}; $raisedErrors.add(error); }
15
+ return error;
16
+ }
17
+ function $raise(error, location) {
18
+ if (!(error instanceof $PyError)) $fail('TypeError', 'raise requires an adopted exception.', location);
19
+ error.location = {...location}; $raisedErrors.add(error);
20
+ if (typeof Error.captureStackTrace === 'function') Error.captureStackTrace(error, $raise);
21
+ throw error;
22
+ }
23
+ function $fail(name, message, location) { $raise(new $PyError(name, message, location), location); }
24
+ '''),
25
+ 'binding': (('error',), r'''
26
+ const $UNBOUND = Symbol('unbound');
27
+ function $get(value, name, local, location) {
28
+ if (value === $UNBOUND) $fail(local ? 'UnboundLocalError' : 'NameError',
29
+ local ? `cannot access local variable '${name}' where it is not associated with a value` : `name '${name}' is not defined`, location);
30
+ return value;
31
+ }
32
+ '''),
33
+ 'str': ((), r'''
34
+ class $Str {
35
+ constructor(codepoints) { this.type = 'str'; this.codepoints = Object.freeze(codepoints); Object.freeze(this); }
36
+ }
37
+ function $str(points) { return new $Str(points); }
38
+ function $text(value) { return value.codepoints.map(point => String.fromCodePoint(point)).join(''); }
39
+ '''),
40
+ 'tuple': ((), r'''
41
+ class $Tuple {
42
+ constructor(items) { this.type = 'tuple'; this.items = Object.freeze(items); Object.freeze(this); }
43
+ }
44
+ const $EMPTY = new $Tuple([]);
45
+ function $tuple(items) { return items.length ? new $Tuple(items) : $EMPTY; }
46
+ '''),
47
+ 'numeric': (('error',), r'''
48
+ function $number(value, location) {
49
+ if (typeof value === 'bigint') return value;
50
+ if (typeof value === 'boolean') return value ? 1n : 0n;
51
+ $fail('TypeError', 'Operation requires an adopted Python integer.', location);
52
+ }
53
+ '''),
54
+ 'truth': (('error', 'str', 'tuple'), r'''
55
+ function $truth(value, location) {
56
+ if (value === null || typeof value === 'boolean' || typeof value === 'bigint') return Boolean(value);
57
+ if (value instanceof $Str) return value.codepoints.length !== 0;
58
+ if (value instanceof $Tuple) return value.items.length !== 0;
59
+ $fail('TypeError', 'Truth testing this value is outside python-browser/1.', location);
60
+ }
61
+ '''),
62
+ 'binary': (('numeric', 'str'), r'''
63
+ function $binary(operator, left, right, location) {
64
+ if (operator === '+' && left instanceof $Str && right instanceof $Str) return $str([...left.codepoints, ...right.codepoints]);
65
+ left = $number(left, location); right = $number(right, location);
66
+ if (operator === '+') return left + right;
67
+ if (operator === '-') return left - right;
68
+ if (operator === '*') return left * right;
69
+ if (right === 0n) $fail('ZeroDivisionError', operator === '//' ? 'division by zero' : 'integer modulo by zero', location);
70
+ let quotient = left / right;
71
+ if (left % right !== 0n && (left < 0n) !== (right < 0n)) quotient -= 1n;
72
+ return operator === '//' ? quotient : left - quotient * right;
73
+ }
74
+ '''),
75
+ 'unary': (('numeric', 'truth'), r'''
76
+ function $unary(operator, value, location) {
77
+ if (operator === 'not') return !$truth(value, location);
78
+ value = $number(value, location); return operator === '-' ? -value : value;
79
+ }
80
+ '''),
81
+ 'equal': (('numeric', 'str', 'tuple'), r'''
82
+ function $equal(left, right, location) {
83
+ if (left === right) return true;
84
+ if (['bigint', 'boolean'].includes(typeof left) && ['bigint', 'boolean'].includes(typeof right)) return $number(left, location) === $number(right, location);
85
+ if (left instanceof $Str && right instanceof $Str) return left.codepoints.length === right.codepoints.length && left.codepoints.every((point, index) => point === right.codepoints[index]);
86
+ if (left instanceof $Tuple && right instanceof $Tuple) return left.items.length === right.items.length && left.items.every((value, index) => $equal(value, right.items[index], location));
87
+ return false;
88
+ }
89
+ function $order(left, right, location) {
90
+ if (['bigint', 'boolean'].includes(typeof left) && ['bigint', 'boolean'].includes(typeof right)) {
91
+ left = $number(left, location); right = $number(right, location); return left < right ? -1 : left > right ? 1 : 0;
92
+ }
93
+ const strings = left instanceof $Str && right instanceof $Str;
94
+ const tuples = left instanceof $Tuple && right instanceof $Tuple;
95
+ if (!strings && !tuples) $fail('TypeError', 'Ordering requires matching adopted sequence or numeric values.', location);
96
+ const a = strings ? left.codepoints : left.items, b = strings ? right.codepoints : right.items;
97
+ for (let index = 0; index < Math.min(a.length, b.length); index++) {
98
+ if (strings ? a[index] !== b[index] : !$equal(a[index], b[index], location)) return strings ? (a[index] < b[index] ? -1 : 1) : $order(a[index], b[index], location);
99
+ }
100
+ return a.length < b.length ? -1 : a.length > b.length ? 1 : 0;
101
+ }
102
+ '''),
103
+ 'compare': (('equal',), r'''
104
+ function $compare(operator, left, right, location) {
105
+ if (operator === '==' || operator === '!=') return $equal(left, right, location) === (operator === '==');
106
+ if (operator === 'is' || operator === 'is not') {
107
+ if (left !== null && right !== null && typeof left !== 'boolean' && typeof right !== 'boolean' &&
108
+ (typeof left === 'bigint' || typeof right === 'bigint' || left instanceof $Str || right instanceof $Str || typeof left === 'number' || typeof right === 'number')) {
109
+ $fail('TypeError', 'Integer/string interning identity is outside python-browser/1.', location);
110
+ }
111
+ return (left === right) === (operator === 'is');
112
+ }
113
+ if (operator === 'in' || operator === 'not in') {
114
+ let found = false;
115
+ if (right instanceof $Tuple) found = right.items.some(value => $equal(left, value, location));
116
+ else if (right instanceof $Str && left instanceof $Str) {
117
+ outer: for (let start = 0; start <= right.codepoints.length - left.codepoints.length; start++) {
118
+ for (let offset = 0; offset < left.codepoints.length; offset++) if (left.codepoints[offset] !== right.codepoints[start + offset]) continue outer;
119
+ found = true; break;
120
+ }
121
+ } else $fail('TypeError', 'Membership requires adopted string/tuple values.', location);
122
+ return found === (operator === 'in');
123
+ }
124
+ const order = $order(left, right, location);
125
+ return operator === '<' ? order < 0 : operator === '<=' ? order <= 0 : operator === '>' ? order > 0 : order >= 0;
126
+ }
127
+ '''),
128
+ 'index': (('numeric', 'str', 'tuple'), r'''
129
+ function $index(value, index, location) {
130
+ const string = value instanceof $Str;
131
+ if (!string && !(value instanceof $Tuple)) $fail('TypeError', 'Indexing requires a Python str or tuple.', location);
132
+ const items = string ? value.codepoints : value.items;
133
+ index = $number(index, location); if (index < 0n) index += BigInt(items.length);
134
+ if (index < 0n || index >= BigInt(items.length)) $fail('IndexError', string ? 'string index out of range' : 'tuple index out of range', location);
135
+ return string ? $str([items[Number(index)]]) : items[Number(index)];
136
+ }
137
+ '''),
138
+ 'iterate': (('error', 'str', 'tuple'), r'''
139
+ function $iterate(value, location) {
140
+ if (value instanceof $Str) return value.codepoints.map(point => $str([point]));
141
+ if (value instanceof $Tuple) return value.items;
142
+ $fail('TypeError', 'Iteration requires a Python str or tuple.', location);
143
+ }
144
+ '''),
145
+ 'call': (('error',), r'''
146
+ class $Callable {
147
+ constructor(name, count, defaults, body) { Object.assign(this, {name, count, defaults, body}); Object.freeze(this); }
148
+ }
149
+ let $depth = 0;
150
+ function $fn(name, count, defaults, body) { return new $Callable(name, count, defaults, body); }
151
+ function $call(fn, args, location) {
152
+ if (!(fn instanceof $Callable)) $fail('TypeError', 'Value is not an adopted callable.', location);
153
+ if (fn.count !== null) {
154
+ if (args.length < fn.count - fn.defaults.length || args.length > fn.count) $fail('TypeError', `${fn.name}() received an unsupported argument count`, location);
155
+ for (let index = args.length; index < fn.count; index++) args.push(fn.defaults[index - (fn.count - fn.defaults.length)]);
156
+ }
157
+ if ($depth >= 128) $fail('RecursionError', 'Maximum compiled call depth (128) exceeded.', location);
158
+ $depth++;
159
+ try { return fn.body(args, location); } finally { $depth--; }
160
+ }
161
+ '''),
162
+ 'len': (('call', 'str', 'tuple'), r'''
163
+ const $len = $fn('len', 1, [], (args, location) => {
164
+ const value = args[0];
165
+ if (value instanceof $Str) return BigInt(value.codepoints.length);
166
+ if (value instanceof $Tuple) return BigInt(value.items.length);
167
+ $fail('TypeError', 'len() requires an adopted Python str or tuple.', location);
168
+ });
169
+ '''),
170
+ 'types': (('call', 'str', 'tuple'), r'''
171
+ const $types = Object.freeze({str: Symbol('str'), int: Symbol('int'), bool: Symbol('bool'), tuple: Symbol('tuple')});
172
+ const $isinstance = $fn('isinstance', 2, [], (args, location) => {
173
+ const [value, type] = args;
174
+ if (type === $types.str) return value instanceof $Str;
175
+ if (type === $types.tuple) return value instanceof $Tuple;
176
+ if (type === $types.int) return typeof value === 'bigint' || typeof value === 'boolean';
177
+ if (type === $types.bool) return typeof value === 'boolean';
178
+ $fail('TypeError', 'isinstance() requires an adopted builtin type.', location);
179
+ });
180
+ '''),
181
+ 'exception': (('call', 'str'), r'''
182
+ const $TypeError = $fn('TypeError', 1, [], (args, location) => {
183
+ if (!(args[0] instanceof $Str)) $fail('TypeError', 'TypeError() requires a str message in this profile.', location);
184
+ return new $PyError('TypeError', $text(args[0]), location);
185
+ });
186
+ '''),
187
+ 'repr': (('error', 'str', 'tuple'), r'''
188
+ const $nonprintable = __NONPRINTABLE__;
189
+ function $printable(point) {
190
+ let low = 0, high = $nonprintable.length;
191
+ while (low < high) { const mid = (low + high) >> 1; if ($nonprintable[mid][1] < point) low = mid + 1; else high = mid; }
192
+ return low === $nonprintable.length || point < $nonprintable[low][0];
193
+ }
194
+ function $repr(value, location, quoteString = false) {
195
+ if (value === null) return 'None';
196
+ if (typeof value === 'boolean') return value ? 'True' : 'False';
197
+ if (typeof value === 'bigint' || typeof value === 'number') return value.toString();
198
+ if (value instanceof $Str) {
199
+ if (!quoteString) {
200
+ if (value.codepoints.some(point => point >= 0xd800 && point <= 0xdfff)) $fail('TypeError', 'Surrogate text output requires a separately adopted sink.', location);
201
+ return $text(value);
202
+ }
203
+ const quote = !value.codepoints.includes(39) || value.codepoints.includes(34) ? "'" : '"';
204
+ return quote + value.codepoints.map(point => {
205
+ if (point === 92 || point === quote.codePointAt(0)) return '\\' + String.fromCodePoint(point);
206
+ if (point === 9) return '\\t'; if (point === 10) return '\\n'; if (point === 13) return '\\r';
207
+ if (!$printable(point)) return (point < 256 ? '\\x' : point < 65536 ? '\\u' : '\\U') + point.toString(16).padStart(point < 256 ? 2 : point < 65536 ? 4 : 8, '0');
208
+ return String.fromCodePoint(point);
209
+ }).join('') + quote;
210
+ }
211
+ if (value instanceof $Tuple) return '(' + value.items.map(item => $repr(item, location, true)).join(', ') + (value.items.length === 1 ? ',' : '') + ')';
212
+ if (value instanceof $PyError) return value.message;
213
+ $fail('TypeError', 'Printing this value is outside python-browser/1.', location);
214
+ }
215
+ '''),
216
+ 'print': (('call', 'repr'), r'''
217
+ const $print = $fn('print', null, [], (args, location) => { write(args.map(value => $repr(value, location)).join(' ') + '\n'); return null; });
218
+ '''),
219
+ 'javascript': (('call',), r'''
220
+ class $JSArray { constructor(values) { this.values = values; } }
221
+ const $of = $fn('Array.of', null, [], args => new $JSArray(args));
222
+ const $JArray = Object.freeze({of: $of});
223
+ const $JS = Object.freeze({Array: $JArray});
224
+ const $Echidnae = Object.freeze({javascript: $JS});
225
+ function $attribute(value, name, location) {
226
+ if (value === $Echidnae && name === 'javascript') return $JS;
227
+ if (value === $JS && name === 'Array') return $JArray;
228
+ if (value === $JArray && name === 'of') return $of;
229
+ if (value instanceof $JSArray && name === 'length') return value.values.length;
230
+ $fail('TypeError', 'Attribute is outside the approved echidnae.javascript registry.', location);
231
+ }
232
+ '''),
233
+ 'async': (('call', 'javascript'), r'''
234
+ if (signal !== null && (typeof signal !== 'object' || typeof signal.aborted !== 'boolean' ||
235
+ typeof signal.addEventListener !== 'function' || typeof signal.removeEventListener !== 'function')) {
236
+ throw new TypeError('signal must be an AbortSignal or null');
237
+ }
238
+ function $cancelled(location) {
239
+ const error = new $PyError('AbortError', 'Compiled operation cancelled.', location);
240
+ error.code = 'CANCELLED'; return error;
241
+ }
242
+ function $checkpoint(location) { if (signal?.aborted) $raise($cancelled(location), location); }
243
+ class $Coroutine {
244
+ constructor(start) { this.start = start; this.started = false; }
245
+ }
246
+ class $PromiseValue {
247
+ constructor(promise) { this.promise = promise; promise.catch(() => {}); Object.freeze(this); }
248
+ }
249
+ const $asyncFunctions = new WeakSet();
250
+ let $activeAsync = 0;
251
+ function $cfn(name, count, defaults, body) {
252
+ const fn = $fn(name, count, defaults, (args, location) => new $Coroutine(() => body(args, location)));
253
+ $asyncFunctions.add(fn); return fn;
254
+ }
255
+ function $wait(promise, location) {
256
+ $checkpoint(location);
257
+ return new Promise((resolve, reject) => {
258
+ let finished = false;
259
+ const cleanup = () => signal?.removeEventListener('abort', abort);
260
+ const abort = () => { if (!finished) { finished = true; cleanup(); reject($markRaised($cancelled(location), location)); } };
261
+ signal?.addEventListener('abort', abort, {once: true});
262
+ if (signal?.aborted) { abort(); return; }
263
+ promise.then(value => {
264
+ if (finished) return; finished = true; cleanup();
265
+ try { $checkpoint(location); resolve(value); } catch (error) { reject(error); }
266
+ }, error => {
267
+ if (finished) return; finished = true; cleanup();
268
+ reject($markRaised(error instanceof $PyError ? error : new $PyError('RuntimeError', 'Unhandled Promise rejection.', location), location));
269
+ });
270
+ });
271
+ }
272
+ function $await(value, location) {
273
+ $checkpoint(location);
274
+ if (value instanceof $PromiseValue) return $wait(value.promise, location);
275
+ if (!(value instanceof $Coroutine)) $fail('TypeError', 'await requires an adopted coroutine or Promise.', location);
276
+ if (value.started) $fail('RuntimeError', 'cannot reuse already awaited coroutine', location);
277
+ value.started = true;
278
+ if ($activeAsync >= 128) $fail('RecursionError', 'Maximum active async calls (128) exceeded.', location);
279
+ $activeAsync++;
280
+ let promise;
281
+ try { promise = Promise.resolve(value.start()); } catch (error) { promise = Promise.reject(error); }
282
+ const pending = promise.finally(() => { $activeAsync--; });
283
+ pending.catch(() => {});
284
+ return $wait(pending, location);
285
+ }
286
+ const $PromiseRegistry = Object.freeze({
287
+ resolve: $fn('Promise.resolve', 1, [], (args, location) => {
288
+ if (args[0] instanceof $Coroutine) $fail('TypeError', 'Await a coroutine before Promise conversion.', location);
289
+ return args[0] instanceof $PromiseValue ? args[0] : new $PromiseValue(Promise.resolve(args[0]));
290
+ }),
291
+ reject: $fn('Promise.reject', 1, [], (args, location) => {
292
+ if (!(args[0] instanceof $PyError)) $fail('TypeError', 'Promise.reject requires an adopted exception.', location);
293
+ return new $PromiseValue(Promise.reject(args[0]));
294
+ })
295
+ });
296
+ function $asyncAttribute(value, name, location) {
297
+ if (value === $JS && name === 'Promise') return $PromiseRegistry;
298
+ if (value === $PromiseRegistry && (name === 'resolve' || name === 'reject')) return value[name];
299
+ if (value instanceof $PromiseValue && name === 'then') return $fn('Promise.then', null, [], (args, where) => {
300
+ if (args.length > 2 || args.some(fn => fn !== null && (!(fn instanceof $Callable) || $asyncFunctions.has(fn)))) {
301
+ $fail('TypeError', 'then requires up to two synchronous Python callbacks or None.', where);
302
+ }
303
+ const callback = fn => fn == null ? undefined : result => {
304
+ $checkpoint(where);
305
+ const returned = $call(fn, [result], where);
306
+ if (returned instanceof $Coroutine) $fail('TypeError', 'Async Promise callbacks are outside this profile.', where);
307
+ return returned instanceof $PromiseValue ? returned.promise : returned;
308
+ };
309
+ return new $PromiseValue(value.promise.then(callback(args[0]), callback(args[1])));
310
+ });
311
+ $fail('TypeError', 'Attribute is outside the adopted async registry.', location);
312
+ }
313
+ '''),
314
+ 'browser': (('async', 'str', 'tuple'), r'''
315
+ if (!host || !['request','registerCallback','releaseCallback'].every(name => typeof host[name] === 'function')) {
316
+ throw new TypeError('The browser profile requires its explicit worker host bridge.');
317
+ }
318
+ class $HostHandle { constructor(wire) { this.wire=Object.freeze({...wire}); Object.freeze(this); } }
319
+ const $subscriptions = new Map();
320
+ function $hostText(value, location) {
321
+ if (!(value instanceof $Str)) $fail('TypeError', 'Browser text/control/URL arguments require Python str.', location);
322
+ return $text(value);
323
+ }
324
+ function $hostDecode(value, location, depth=0) {
325
+ if (depth > 64 || !value || typeof value !== 'object') $fail('TypeError', 'Invalid host value.', location);
326
+ if (value.type === 'none') return null;
327
+ if (value.type === 'bool' && typeof value.value === 'boolean') return value.value;
328
+ if (value.type === 'int' && typeof value.value === 'string' && value.value.length <= 4097 && /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/.test(value.value)) return BigInt(value.value);
329
+ if (value.type === 'str' && Array.isArray(value.codepoints) && value.codepoints.length <= 1048576 && value.codepoints.every(point => Number.isInteger(point) && point>=0 && point<=0x10ffff)) return $str(value.codepoints);
330
+ if (value.type === 'tuple' && Array.isArray(value.items) && value.items.length <= 1024) return $tuple(value.items.map(item=>$hostDecode(item,location,depth+1)));
331
+ if (value.type === 'handle' && value.owner === 'main' && value.kind === 'event.subscription' && /^m[1-9][0-9]*$/.test(value.id)) return new $HostHandle(value);
332
+ $fail('TypeError', 'Host result is outside the adopted browser values.', location);
333
+ }
334
+ function $hostFailure(error, location) {
335
+ if (error instanceof $PyError) return error;
336
+ const result = new $PyError(typeof error?.type==='string' ? error.type : 'HostError',
337
+ typeof error?.message==='string' ? error.message.slice(0,4096) : 'Host operation failed.', location);
338
+ result.code = typeof error?.code==='string' ? error.code : 'IO'; return result;
339
+ }
340
+ function $request(operation, args, location, decode=value=>$hostDecode(value,location)) {
341
+ $checkpoint(location);
342
+ return new $PromiseValue(Promise.resolve().then(()=>host.request(operation,args)).then(decode).catch(error=>{throw $hostFailure(error,location);}));
343
+ }
344
+ const $browser = Object.freeze({
345
+ read_text: $fn('read_text',1,[],(args,where)=>$request('dom.read',{control:$hostText(args[0],where)},where)),
346
+ write_text: $fn('write_text',2,[],(args,where)=>{
347
+ $hostText(args[1],where);
348
+ return $request('dom.write',{control:$hostText(args[0],where),text:{type:'str',codepoints:[...args[1].codepoints]}},where);
349
+ }),
350
+ on_click: $fn('on_click',2,[],(args,where)=>{
351
+ if (!(args[1] instanceof $Callable)) $fail('TypeError','on_click requires a compiled Python callback.',where);
352
+ const control=$hostText(args[0],where), callback=host.registerCallback(async value=>{
353
+ $checkpoint(where);
354
+ const result=$call(args[1],[$hostDecode(value,where)],where);
355
+ if (result instanceof $Coroutine || result instanceof $PromiseValue) await $await(result,where);
356
+ });
357
+ const pending=$request('events.subscribe',{control,event:'click',callback},where,value=>{
358
+ const handle=$hostDecode(value,where);$subscriptions.set(handle,callback);return handle;
359
+ });
360
+ return new $PromiseValue(pending.promise.catch(error=>{host.releaseCallback(callback);throw error;}));
361
+ }),
362
+ unsubscribe: $fn('unsubscribe',1,[],(args,where)=>{
363
+ const handle=args[0];
364
+ if (!(handle instanceof $HostHandle) || !$subscriptions.has(handle)) {
365
+ const error=new $PyError('HostError','Subscription handle is stale.',where);error.code='STALE_HANDLE';$raise(error,where);
366
+ }
367
+ return $request('events.unsubscribe',{subscription:handle.wire},where,value=>{
368
+ host.releaseCallback($subscriptions.get(handle));$subscriptions.delete(handle);return $hostDecode(value,where);
369
+ });
370
+ }),
371
+ fetch_text: $fn('fetch_text',1,[],(args,where)=>$request('fetch.text',{url:$hostText(args[0],where),method:'GET'},where,value=>{
372
+ if (value?.type!=='dict' || !Array.isArray(value.entries) || value.entries.length!==3) $fail('TypeError','Malformed Fetch result.',where);
373
+ const entries=new Map(value.entries.map(pair=>[$hostText($hostDecode(pair[0],where),where),$hostDecode(pair[1],where)]));
374
+ if (!['status','url','text'].every(key=>entries.has(key)) || typeof entries.get('status')!=='bigint' || !(entries.get('url') instanceof $Str) || !(entries.get('text') instanceof $Str)) $fail('TypeError','Malformed Fetch fields.',where);
375
+ return $tuple(['status','url','text'].map(key=>entries.get(key)));
376
+ }))
377
+ });
378
+ '''),
379
+ 'async-expose': (('async', 'input'), r'''
380
+ const $asyncExposed = new WeakMap();
381
+ function $asyncExpose(value, location) {
382
+ if (!(value instanceof $Callable)) return value;
383
+ if (!$asyncExposed.has(value)) {
384
+ const invoke = args => {
385
+ $checkpoint(location);
386
+ return $call(value, args.map(argument => $input(argument, location)), location);
387
+ };
388
+ $asyncExposed.set(value, $asyncFunctions.has(value) ?
389
+ (...args) => Promise.resolve().then(() => $await(invoke(args), location)) : (...args) => {
390
+ const result = invoke(args);
391
+ return result instanceof $PromiseValue ? $await(result, location) : result;
392
+ });
393
+ }
394
+ return $asyncExposed.get(value);
395
+ }
396
+ '''),
397
+ 'input': (('call', 'str', 'tuple'), r'''
398
+ function $input(value, location, depth = 0, seen = new Set()) {
399
+ if (depth > 64) $fail('TypeError', 'Input nesting exceeds 64.', location);
400
+ if (value === null || ['boolean', 'bigint'].includes(typeof value) || value instanceof $Str || value instanceof $Tuple) return value;
401
+ if (typeof value === 'string') return $str(Array.from(value, character => character.codePointAt(0)));
402
+ if (typeof value !== 'object' || seen.has(value)) $fail('TypeError', 'Input requires an adopted Python value.', location);
403
+ if (value.type === 'str' && Array.isArray(value.codepoints) && value.codepoints.length <= 1048576 && Array.from(value.codepoints).every(point => Number.isInteger(point) && point >= 0 && point <= 0x10ffff)) return $str([...value.codepoints]);
404
+ if (value.type === 'tuple' && Array.isArray(value.items)) {
405
+ seen.add(value); const items = Array.from(value.items, item => $input(item, location, depth + 1, seen)); seen.delete(value); return $tuple(items);
406
+ }
407
+ $fail('TypeError', 'Use BigInt, string, bool, null or explicit str/tuple input; echidnae.javascript Number/Array is not Python int/tuple.', location);
408
+ }
409
+ function $expose(value, location) {
410
+ if (!(value instanceof $Callable)) return value;
411
+ if (!$exposed.has(value)) $exposed.set(value, (...args) => $call(value, args.map(argument => $input(argument, location)), location));
412
+ return $exposed.get(value);
413
+ }
414
+ const $exposed = new WeakMap();
415
+ '''),
416
+ }
417
+
418
+
419
+ HELPER_BINDINGS = {
420
+ 'error': ('$PyError', '$fail', '$raise'), 'binding': ('$UNBOUND', '$get'),
421
+ 'str': ('$str',), 'tuple': ('$tuple',), 'numeric': ('$number',),
422
+ 'truth': ('$truth',), 'binary': ('$binary',), 'unary': ('$unary',),
423
+ 'equal': ('$equal', '$order'), 'compare': ('$compare',), 'index': ('$index',),
424
+ 'iterate': ('$iterate',), 'call': ('$fn', '$call'), 'len': ('$len',),
425
+ 'types': ('$types', '$isinstance'), 'exception': ('$TypeError',),
426
+ 'repr': ('$repr',), 'print': ('$print',),
427
+ 'javascript': ('$JS', '$Echidnae', '$JArray', '$attribute'), 'input': ('$input', '$expose'),
428
+ 'async': ('$checkpoint', '$await', '$cfn', '$PromiseRegistry', '$asyncAttribute'),
429
+ 'async-expose': ('$asyncExpose',),
430
+ 'browser': ('$browser',),
431
+ }
432
+
433
+
434
+ @lru_cache(maxsize=1)
435
+ def _nonprintable_ranges():
436
+ ranges, start = [], None
437
+ for point in range(0x110000):
438
+ if not chr(point).isprintable():
439
+ if start is None:
440
+ start = point
441
+ elif start is not None:
442
+ ranges.append([start, point - 1])
443
+ start = None
444
+ if start is not None:
445
+ ranges.append([start, 0x10ffff])
446
+ return json.dumps(ranges, separators=(',', ':'))
447
+
448
+
449
+ def helper_closure(required):
450
+ ordered = []
451
+ def visit(name):
452
+ if name in ordered:
453
+ return
454
+ for dependency in HELPERS[name][0]:
455
+ visit(dependency)
456
+ ordered.append(name)
457
+ for name in sorted(required):
458
+ visit(name)
459
+ return tuple(ordered)
460
+
461
+
462
+ def helper_source(name):
463
+ source = HELPERS[name][1].strip()
464
+ if name == 'repr':
465
+ source = source.replace('__NONPRINTABLE__', _nonprintable_ranges())
466
+ return source