@geastack/geatsc-plugin-gea 0.1.14 → 0.1.15

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,9 @@
1
+ // These declarations identify package-local CommonJS wrapper cells to geatsc.
2
+ // Static package loading is implemented by the compiler's module records.
3
+ export {};
4
+
5
+ declare global {
6
+ var require: (specifier: string) => any;
7
+ var exports: any;
8
+ var module: { exports: any };
9
+ }
@@ -1,5 +1,6 @@
1
1
  import ts from 'typescript';
2
2
  export declare function sourceLiteralResolver(files: Map<string, string>, initiallyOpaque: boolean): ((node: ts.Expression) => string[] | undefined) & {
3
+ isString(node: ts.Expression): boolean;
3
4
  isNumeric(node: ts.Expression): boolean;
4
5
  isSourceMethod(node: ts.Expression): boolean;
5
6
  };
@@ -278,6 +278,18 @@ export function sourceLiteralResolver(files, initiallyOpaque) {
278
278
  index(source);
279
279
  const original = (node) => expressions.get(`${node.getSourceFile().fileName}:${node.pos}:${node.end}`);
280
280
  return Object.assign((node) => resolve(original(node)), {
281
+ // String operations do not mutate stylesheets. Use the receiver's type
282
+ // rather than the finite-literal proof: parameters, mutable variables and
283
+ // imported return values can be strings without having known contents.
284
+ // Mixed string/object unions and unresolved any/unknown retain support.
285
+ isString(node) {
286
+ const at = original(node);
287
+ if (!at || initiallyOpaque)
288
+ return false;
289
+ const type = typeChecker().getTypeAtLocation(at);
290
+ const alternatives = type.isUnion() ? type.types : [type];
291
+ return alternatives.every(value => !!(value.flags & ts.TypeFlags.StringLike));
292
+ },
281
293
  // In a statically lowered numeric slot no value can contain a CSS '%'.
282
294
  // Ambiguous imports, assertions and any/unknown retain storage. A typed
283
295
  // native number remains numeric when unrelated literal objects escape;
@@ -294,6 +306,33 @@ export function sourceLiteralResolver(files, initiallyOpaque) {
294
306
  if (!at || initiallyOpaque)
295
307
  return false;
296
308
  const parent = at.parent;
309
+ // A locally declared frame callback may also be named animate. Resolve
310
+ // its binding instead of confusing the name with Element.animate.
311
+ if (ts.isIdentifier(at)) {
312
+ let symbol = typeChecker().getSymbolAtLocation(at);
313
+ if (symbol && (symbol.flags & ts.SymbolFlags.Alias))
314
+ symbol = typeChecker().getAliasedSymbol(symbol);
315
+ const declarations = symbol?.declarations;
316
+ if (declarations?.length && declarations.every(declaration => sources.has(declaration.getSourceFile().fileName) && ts.isFunctionDeclaration(declaration) && !!declaration.body)) {
317
+ let reassigned = false;
318
+ const checkWrites = (child) => {
319
+ if (ts.isBinaryExpression(child) && child.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
320
+ child.operatorToken.kind <= ts.SyntaxKind.LastAssignment) {
321
+ const checkTarget = (target) => {
322
+ if (ts.isIdentifier(target) && typeChecker().getSymbolAtLocation(target) === symbol)
323
+ reassigned = true;
324
+ ts.forEachChild(target, checkTarget);
325
+ };
326
+ checkTarget(child.left);
327
+ }
328
+ ts.forEachChild(child, checkWrites);
329
+ };
330
+ for (const source of sources.values())
331
+ checkWrites(source);
332
+ if (!reassigned)
333
+ return true;
334
+ }
335
+ }
297
336
  if (ts.isMethodDeclaration(parent) && parent.name === at && parent.body)
298
337
  return true;
299
338
  const access = ts.isPropertyAccessExpression(at) || ts.isElementAccessExpression(at) ? at
@@ -4,6 +4,7 @@ export declare const rendererOcclusionAnalysisVersion = "renderer-occlusion-v1";
4
4
  export declare function addUnknownRendererFeatures(features: Set<string>): void;
5
5
  export interface StyleUsageObserver {
6
6
  isSourceMethod?(node: ts.Expression): boolean;
7
+ isString?(node: ts.Expression): boolean;
7
8
  selector?(css: string): void;
8
9
  property(name: string | undefined, value: string | undefined, expression?: ts.Expression): void;
9
10
  unknown(): void;
@@ -426,7 +426,13 @@ export function addRendererFeatures(file, text, features, observer, variables) {
426
426
  for (const arg of node.arguments.slice(1))
427
427
  styleObject(arg);
428
428
  }
429
- if (name === 'insertRule' || name === 'replaceSync' || name === 'replace') {
429
+ // Classify the receiver, not the shared method name. A primitive string
430
+ // cannot be a stylesheet, even when its contents are not statically known.
431
+ // Continue visiting arguments so callbacks that mutate CSS remain visible.
432
+ const stringReplace = name === 'replace' &&
433
+ (ts.isPropertyAccessExpression(node.expression) || ts.isElementAccessExpression(node.expression)) &&
434
+ (ts.isStringLiteralLike(unwrap(node.expression.expression)) || observer?.isString?.(node.expression.expression));
435
+ if (name === 'insertRule' || name === 'replaceSync' || (name === 'replace' && !stringReplace)) {
430
436
  if (node.arguments[0])
431
437
  styleObject(node.arguments[0]);
432
438
  }
@@ -0,0 +1,7 @@
1
+ export interface WorkerModuleAnalysis {
2
+ realms: boolean;
3
+ modules: string[];
4
+ unknown: boolean;
5
+ }
6
+ /** Standard module-worker/worklet entry points are executable dependencies. */
7
+ export declare function analyzeWorkerModules(file: string, text: string): WorkerModuleAnalysis;
@@ -0,0 +1,112 @@
1
+ import ts from 'typescript';
2
+ /** Standard module-worker/worklet entry points are executable dependencies. */
3
+ export function analyzeWorkerModules(file, text) {
4
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, /\.[jt]sx$/i.test(file) ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
5
+ const result = { realms: false, modules: [], unknown: false };
6
+ const scopes = lexicalBindings(source);
7
+ const name = (expression) => {
8
+ if (ts.isIdentifier(expression))
9
+ return scopes.shadows(expression, expression.text) ? undefined : expression.text;
10
+ if (ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression) &&
11
+ ['globalThis', 'window', 'self'].includes(expression.expression.text) &&
12
+ !scopes.shadows(expression, expression.expression.text))
13
+ return expression.name.text;
14
+ return undefined;
15
+ };
16
+ const module = (expression) => {
17
+ result.realms = true;
18
+ if (expression && ts.isNewExpression(expression) && name(expression.expression) === 'URL') {
19
+ const [path, base] = expression.arguments ?? [];
20
+ if (path && ts.isStringLiteralLike(path) && base && ts.isPropertyAccessExpression(base) &&
21
+ base.name.text === 'url' && ts.isMetaProperty(base.expression) && base.expression.keywordToken === ts.SyntaxKind.ImportKeyword) {
22
+ result.modules.push(path.text);
23
+ return;
24
+ }
25
+ }
26
+ if (expression && ts.isStringLiteralLike(expression))
27
+ result.modules.push(expression.text);
28
+ else
29
+ result.unknown = true;
30
+ };
31
+ const visit = (node) => {
32
+ if (ts.isNewExpression(node)) {
33
+ const constructor = name(node.expression);
34
+ if (constructor === 'Worker')
35
+ module(node.arguments?.[0]);
36
+ if (constructor === 'AudioWorkletNode')
37
+ result.realms = true;
38
+ }
39
+ if (ts.isCallExpression(node)) {
40
+ if (name(node.expression) === 'registerProcessor')
41
+ result.realms = true;
42
+ if (ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'addModule') {
43
+ const receiver = node.expression.expression;
44
+ if (ts.isPropertyAccessExpression(receiver) && receiver.name.text === 'audioWorklet')
45
+ module(node.arguments[0]);
46
+ }
47
+ }
48
+ ts.forEachChild(node, visit);
49
+ };
50
+ visit(source);
51
+ return result;
52
+ }
53
+ /** Value bindings shadow browser globals; erased type imports never do. */
54
+ function lexicalBindings(source) {
55
+ const owners = new Map();
56
+ const bind = (scope, name) => {
57
+ if (ts.isIdentifier(name))
58
+ scope.bindings.add(name.text);
59
+ else
60
+ for (const element of name.elements)
61
+ if (ts.isBindingElement(element))
62
+ bind(scope, element.name);
63
+ };
64
+ const walk = (node, inherited) => {
65
+ let scope = inherited;
66
+ if (ts.isSourceFile(node) || ts.isBlock(node) || ts.isFunctionLike(node) || ts.isCatchClause(node)) {
67
+ scope = { parent: inherited, bindings: new Set(), function: ts.isSourceFile(node) || ts.isFunctionLike(node) };
68
+ }
69
+ owners.set(node, scope);
70
+ if (ts.isImportDeclaration(node) && node.importClause && !node.importClause.isTypeOnly) {
71
+ const clause = node.importClause;
72
+ if (clause.name)
73
+ bind(scope, clause.name);
74
+ if (clause.namedBindings) {
75
+ if (ts.isNamespaceImport(clause.namedBindings))
76
+ bind(scope, clause.namedBindings.name);
77
+ else
78
+ for (const item of clause.namedBindings.elements)
79
+ if (!item.isTypeOnly)
80
+ bind(scope, item.name);
81
+ }
82
+ }
83
+ if (ts.isImportEqualsDeclaration(node) && !node.isTypeOnly)
84
+ bind(scope, node.name);
85
+ if ((ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isEnumDeclaration(node)) && node.name) {
86
+ bind(ts.isFunctionDeclaration(node) ? inherited : scope, node.name);
87
+ }
88
+ if (ts.isFunctionExpression(node) && node.name)
89
+ bind(scope, node.name);
90
+ if (ts.isParameter(node))
91
+ bind(scope, node.name);
92
+ if (ts.isVariableDeclaration(node)) {
93
+ let target = scope;
94
+ const list = node.parent;
95
+ if (ts.isVariableDeclarationList(list) && !(list.flags & ts.NodeFlags.BlockScoped)) {
96
+ while (!target.function && target.parent)
97
+ target = target.parent;
98
+ }
99
+ bind(target, node.name);
100
+ }
101
+ ts.forEachChild(node, (child) => walk(child, scope));
102
+ };
103
+ walk(source, { bindings: new Set(), function: true });
104
+ return {
105
+ shadows(node, name) {
106
+ for (let scope = owners.get(node); scope; scope = scope.parent)
107
+ if (scope.bindings.has(name))
108
+ return true;
109
+ return false;
110
+ },
111
+ };
112
+ }
package/dist/analyze.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { analyzeWorkerModules } from './analyze-workers.js';
1
2
  import { inferCanvasOnly } from './analyze-runtime.js';
2
3
  import { nodeAuxVersion, addNodeAuxFeatures, addUnknownNodeAux, cssUsesNodeAttributes } from './analyze-node-aux.js';
3
4
  import { sourceLiteralResolver } from './analyze-literals.js';
@@ -42,6 +43,7 @@ export function analyzeSourceHostBindings(entry) {
42
43
  const ranges = cssRangeObserver(features);
43
44
  const observer = {
44
45
  isSourceMethod: literals.isSourceMethod,
46
+ isString: literals.isString,
45
47
  selector(value) { css.selector?.(value); ranges.selector?.(value); if (cssUsesNodeAttributes(value))
46
48
  features.add('node-attributes'); },
47
49
  property(name, value, expression) { css.property(name, value, expression); ranges.property(name, value); variables.property(name, value); },
@@ -68,6 +70,8 @@ export function analyzeSourceHostBindings(entry) {
68
70
  addBindingsForEmbeddedHostNames(text, bindings);
69
71
  addBindingsForHostGlobals(text, bindings);
70
72
  addFeaturesForUrlSchemes(text, features);
73
+ if (analyzeWorkerModules(file, text).realms)
74
+ features.add('worker-realms');
71
75
  addRendererFeatures(file, text, features, observer, variables);
72
76
  addNodeFeatures(file, text, features);
73
77
  addNodeAuxFeatures(file, text, features, literals.isNumeric);
@@ -161,6 +165,9 @@ function addBindingsForGeaEmbeddedImports(text, bindings) {
161
165
  const hostGlobalCalls = [
162
166
  [/(?<![.\w$])fetch\s*\(/, 'fetch'],
163
167
  [/(?<![.\w$])new\s+WebSocket\s*\(/, 'websocket'],
168
+ [/(?<![.\w$])new\s+(?:window\.|globalThis\.)?RTCPeerConnection\s*\(/, 'rtc'],
169
+ [/(?<![.\w$])navigator\s*\.\s*mediaDevices\s*\.\s*getUserMedia\s*\(/, 'audio'],
170
+ [/(?<![.\w$])new\s+(?:window\.|globalThis\.)?(?:AudioContext|PcmAudioStream)\s*\(/, 'audio'],
164
171
  ];
165
172
  // A file that declares its own `fetch` (a class method, or a wrapper such as
166
173
  // image-demo's runtime.ts) calls that one; its network use, if any, shows up
@@ -216,6 +223,18 @@ function discoverSourceFiles(entry) {
216
223
  return;
217
224
  }
218
225
  const text = fs.readFileSync(resolved, 'utf8');
226
+ if (!/\.css$/i.test(resolved)) {
227
+ const workers = analyzeWorkerModules(resolved, text);
228
+ if (workers.unknown)
229
+ unknown = true;
230
+ for (const specifier of workers.modules) {
231
+ const dependency = !/^[a-z]+:/i.test(specifier) && resolveRelativeModule(resolved, specifier);
232
+ if (dependency)
233
+ visit(dependency);
234
+ else
235
+ unknown = true;
236
+ }
237
+ }
219
238
  for (const specifier of /\.css$/i.test(resolved) ? [] : moduleSpecifiers(resolved, text)) {
220
239
  // Framework host imports do not inject renderer instructions. Other
221
240
  // external code may supply styles/components we cannot inspect here.
@@ -268,11 +287,9 @@ function moduleSpecifiers(file, text) {
268
287
  return specifiers;
269
288
  }
270
289
  function resolvePackageModule(importer, specifier) {
271
- // CSS package imports must be traversed just like relative stylesheets. For
272
- // opaque JS packages keep the conservative feature set instead of assuming
273
- // their exports cannot render anything.
274
- if (!/\.css$/i.test(specifier))
275
- return null;
290
+ // Installed JS libraries can be the only consumers of networking and audio
291
+ // (e.g. livekit-client). Traverse their real source just like relative imports.
292
+ // Unresolved/native imports still retain the conservative renderer feature set.
276
293
  try {
277
294
  return createRequire(importer).resolve(specifier);
278
295
  }
@@ -0,0 +1,2 @@
1
+ import type { HostShimDefinitions } from './types.js';
2
+ export declare function extendAudioWorkletShims(shims: HostShimDefinitions): HostShimDefinitions;
@@ -0,0 +1,60 @@
1
+ import { geaHostDeclarations } from './host-declarations.js';
2
+ export function extendAudioWorkletShims(shims) {
3
+ const declarations = [...geaHostDeclarations, '#include "gea/audio-worklet-runtime.h"'];
4
+ for (const [name, native, result] of [
5
+ ['__geaAudioWorkletProcessorPort', 'gea::host::audio_worklet::processorPort', 'gea::host::workers::MessagePort'],
6
+ ['__geaFlushAudioWorkletOutput', 'gea::host::audio_worklet::flushOutput', 'void'],
7
+ ['__geaRegisterAudioWorkletProcessor', 'gea::runtime::hostaudio::registerTypedProcessor', 'void'],
8
+ ]) {
9
+ shims.embeddedHostFunctions[name] = native;
10
+ shims.embeddedHostFunctionReturnTypes[name] = result;
11
+ shims.hostExternDeclarations[native] = declarations;
12
+ }
13
+ for (const type of ['AudioContext', 'AudioWorklet', 'AudioWorkletNode', 'MediaStreamAudioSourceNode']) {
14
+ shims.nativeTypes[type] = `gea::host::${type}`;
15
+ shims.hostExternDeclarations[`gea::host::${type}`] = declarations;
16
+ }
17
+ const receiverTypes = (type) => [type, `gea::host::${type}`];
18
+ const method = (type, name, returnType, emit = `({receiver}).${name}({args})`) => {
19
+ ;
20
+ (shims.nativeMemberMethods[name] ||= []).push({ receiverTypes: receiverTypes(type), returnType, emit });
21
+ shims.hostExternDeclarations[emit] = declarations;
22
+ };
23
+ const property = (type, name, returnType, emit = `({receiver}).${name}`) => {
24
+ ;
25
+ (shims.nativeMemberPropertyGetters[name] ||= []).push({ receiverTypes: receiverTypes(type), returnType, emit });
26
+ shims.hostExternDeclarations[emit] = declarations;
27
+ };
28
+ for (const type of ['AudioContext', 'AudioWorkletNode']) {
29
+ const construct = `gea::runtime::hostaudio::create${type}({args})`;
30
+ shims.nativeTypes[`${type}Constructor`] = `gea::host::${type}`;
31
+ shims.nativeConstructors[`${type}Constructor`] = construct;
32
+ shims.embeddedHostClasses[type] = { wrapper: `gea::host::${type}`, construct };
33
+ shims.hostExternDeclarations[`gea::runtime::hostaudio::create${type}`] = declarations;
34
+ }
35
+ property('AudioContext', 'sampleRate', 'double');
36
+ property('AudioContext', 'baseLatency', 'double', '({receiver}).baseLatency()');
37
+ property('AudioContext', 'outputLatency', 'double', '({receiver}).outputLatency()');
38
+ property('AudioContext', 'state', 'std::string', '({receiver}).state()');
39
+ property('AudioContext', 'audioWorklet', 'gea::host::AudioWorklet');
40
+ property('AudioWorkletNode', 'port', 'gea::host::workers::MessagePort');
41
+ method('AudioWorklet', 'addModule', 'gea::Promise<void>', 'gea::runtime::hostaudio::workletAddModule({receiver}, {arg0})');
42
+ for (const name of ['resume', 'suspend', 'close'])
43
+ method('AudioContext', name, 'gea::Promise<void>', `gea::runtime::hostaudio::context${name[0].toUpperCase() + name.slice(1)}({receiver})`);
44
+ method('AudioContext', 'createMediaStreamSource', 'gea::host::MediaStreamAudioSourceNode');
45
+ method('MediaStreamAudioSourceNode', 'connect', 'gea::host::AudioWorkletNode');
46
+ method('AudioWorkletNode', 'connect', 'gea::host::AudioDestinationNode');
47
+ for (const type of ['MediaStreamAudioSourceNode', 'AudioWorkletNode'])
48
+ method(type, 'disconnect', 'void');
49
+ (shims.nativeMemberPropertySetters.onprocessorerror ||= []).push({
50
+ receiverTypes: receiverTypes('AudioWorkletNode'), returnType: 'void',
51
+ emit: 'gea::runtime::hostaudio::setOnProcessorError({receiver}, {value})',
52
+ });
53
+ for (const name of ['sampleRate', 'currentTime', 'currentFrame']) {
54
+ shims.hostGlobalObjects[name] = `gea::host::audio_worklet::${name}()`;
55
+ shims.hostGlobalObjectTypes[name] = 'double';
56
+ shims.embeddedHostConstants[name] = { emit: `gea::host::audio_worklet::${name}()`, type: 'double' };
57
+ shims.hostExternDeclarations[`gea::host::audio_worklet::${name}()`] = declarations;
58
+ }
59
+ return shims;
60
+ }
@@ -143,13 +143,13 @@ function lowerMember(context, expr, hint) {
143
143
  if (path === 'Date.now')
144
144
  return 'gea_cpp_now_ms';
145
145
  if (path === 'audioContext.currentTime')
146
- return 'gea::host::audioContext.currentTime';
146
+ return 'gea::host::sharedAudioContext().currentTime';
147
147
  if (path === '__gea_audioContext.currentTime')
148
- return 'gea::host::audioContext.currentTime';
148
+ return 'gea::host::sharedAudioContext().currentTime';
149
149
  if (path === 'audioContext.destination')
150
- return 'gea::host::audioContext.destination';
150
+ return 'gea::host::sharedAudioContext().destination';
151
151
  if (path === '__gea_audioContext.destination')
152
- return 'gea::host::audioContext.destination';
152
+ return 'gea::host::sharedAudioContext().destination';
153
153
  if (path === 'Accelerometer.tiltX')
154
154
  return 'gea::host::Accelerometer.tiltX';
155
155
  if (path === 'Accelerometer.tiltY')
@@ -516,9 +516,9 @@ function lowerCall(context, expr, hint) {
516
516
  return call;
517
517
  }
518
518
  if (path === 'audioContext.createOscillator')
519
- return coerceForHint('gea::host::audioContext.createOscillator()', hint);
519
+ return coerceForHint('gea::host::sharedAudioContext().createOscillator()', hint);
520
520
  if (path === '__gea_audioContext.createOscillator')
521
- return coerceForHint('gea::host::audioContext.createOscillator()', hint);
521
+ return coerceForHint('gea::host::sharedAudioContext().createOscillator()', hint);
522
522
  if (path === 'Accelerometer.start')
523
523
  return coerceForHint('gea::host::Accelerometer.start()', hint);
524
524
  if (path === 'touch.read' || path === 'touch.__gea_read') {
@@ -1,3 +1,4 @@
1
+ export declare const geaHostDeclarations: string[];
1
2
  /**
2
3
  * The `<virtual-list>` row-height getter's template, stated once.
3
4
  *
@@ -1,4 +1,4 @@
1
- const geaHostDeclarations = [
1
+ export const geaHostDeclarations = [
2
2
  '#ifndef GEA_HOST_DECLARED',
3
3
  '#define GEA_HOST_DECLARED 1',
4
4
  '#include "gea/embedded.h"',
@@ -23,6 +23,7 @@ const geaDeviceInfoDeclarations = [...geaHostDeclarations, '#include "device_inf
23
23
  // beside it need nothing extra: `Tree::instance().scrollTop` IS reachable
24
24
  // through the public header.
25
25
  const geaVirtualListDeclarations = [...geaHostDeclarations, '#include "ui/internal.h"'];
26
+ const geaBase64Declarations = [...geaHostDeclarations, '#include "gea/base64-runtime.h"'];
26
27
  /**
27
28
  * The `<virtual-list>` row-height getter's template, stated once.
28
29
  *
@@ -112,6 +113,8 @@ const geaMemoryHostMethods = [
112
113
  'allocationPsramPeakBytes',
113
114
  ];
114
115
  const rawGeaHostExternDeclarations = Object.fromEntries([
116
+ ['gea::runtime::hostbase64::encode', geaBase64Declarations],
117
+ ['gea::runtime::hostbase64::decode', geaBase64Declarations],
115
118
  [geaHostHeaderDeclarationToken, geaHostDeclarations],
116
119
  ['gea::host::navigator', geaHostDeclarations],
117
120
  ['gea::host::window', geaHostDeclarations],
@@ -173,12 +176,14 @@ const rawGeaHostExternDeclarations = Object.fromEntries([
173
176
  ['gea::host::RTCPeerConnection', geaHostDeclarations],
174
177
  ['gea::host::Math.random', geaHostDeclarations],
175
178
  ['gea::host::HTMLAudioElement', geaHostDeclarations],
176
- ['gea::host::audioContext', geaHostDeclarations],
177
- ['gea::host::audioContext.createOscillator', geaHostDeclarations],
178
- ['gea::host::audioContext.createBufferSource', geaHostDeclarations],
179
- ['gea::host::audioContext.decodeAudioData', geaHostDeclarations],
180
- ['gea::host::audioContext.currentTime', geaHostDeclarations],
181
- ['gea::host::audioContext.destination', geaHostDeclarations],
179
+ ['gea::host::PcmAudioStream', geaHostDeclarations],
180
+ ['gea::host::HTMLVideoElement', geaHostDeclarations],
181
+ ['gea::host::sharedAudioContext()', geaHostDeclarations],
182
+ ['gea::host::sharedAudioContext().createOscillator', geaHostDeclarations],
183
+ ['gea::host::sharedAudioContext().createBufferSource', geaHostDeclarations],
184
+ ['gea::host::sharedAudioContext().decodeAudioData', geaHostDeclarations],
185
+ ['gea::host::sharedAudioContext().currentTime', geaHostDeclarations],
186
+ ['gea::host::sharedAudioContext().destination', geaHostDeclarations],
182
187
  ['gea::host::apps.launch', geaHostDeclarations],
183
188
  ['gea::host::Audio.getVolume', geaHostDeclarations],
184
189
  ['gea::host::Audio.setVolume', geaHostDeclarations],
@@ -1,4 +1,8 @@
1
- import { geaHostExternDeclarations, geaVirtualListRowHeightEmit } from "./host-declarations.js";
1
+ import { extendRtcShims } from "./rtc-shims.js";
2
+ import { extendWorkerShims } from "./worker-shims.js";
3
+ import { extendAudioWorkletShims } from "./audio-worklet-shims.js";
4
+ import { fileURLToPath } from "node:url";
5
+ import { geaHostExternDeclarations, geaVirtualListRowHeightEmit, } from "./host-declarations.js";
2
6
  import { CSS_STYLE_DECLARATION_NATIVE_TYPES, CSS_STYLE_DECLARATION_NATIVE_MEMBER_METHODS, } from "./css-style-declaration-shims.js";
3
7
  // Receiver types a DOM-node property getter binding matches: the concrete C++
4
8
  // handle plus every DOM interface name that lowers to it (see `nativeTypes`).
@@ -243,7 +247,15 @@ const HOST_NATIVE_CALLABLE_SIDECARS = [
243
247
  },
244
248
  ];
245
249
  export function createGeaHostShims() {
246
- return {
250
+ return extendAudioWorkletShims(extendWorkerShims(extendRtcShims({
251
+ commonJsGlobals: Object.fromEntries(["require", "exports", "module"].map((global) => [
252
+ global,
253
+ {
254
+ global,
255
+ declarationName: global,
256
+ declarationFileName: fileURLToPath(new URL("../commonjs-wrapper.d.ts", import.meta.url)),
257
+ },
258
+ ])),
247
259
  // Gea embedded has no dynamic Symbol type: a `unique symbol` const used as a
248
260
  // property key lowers to its named string key (`__sym_<name>`) and well-known
249
261
  // symbol protocols read named members, so nothing boxes to a `gea_cpp_value`
@@ -374,6 +386,7 @@ export function createGeaHostShims() {
374
386
  MediaRecorderDataAvailableEvent: "gea::host::MediaRecorderDataEvent",
375
387
  GeaAudioBlob: "gea::host::GeaAudioBlob",
376
388
  HTMLAudioElement: "gea::host::HTMLAudioElement",
389
+ HTMLVideoElement: "gea::host::HTMLVideoElement",
377
390
  // The three ambient CONSTRUCTOR interfaces (`declare var Audio:
378
391
  // AudioConstructor`, etc.) share their instance type's own carrier
379
392
  // above: `new Audio(...)` and every `audio.play()` afterward flow
@@ -442,16 +455,12 @@ export function createGeaHostShims() {
442
455
  // Keyed by the CONSTRUCTOR interface's own declared name (see
443
456
  // `nativeConstructors`'s own field comment, types.ts, for why).
444
457
  nativeConstructors: {
445
- // `new Audio(src?: string): HTMLAudioElement` -> `HTMLAudioElement(const
446
- // std::string&)` (audio.h). One argument: the checker's own optional
447
- // `src` still reaches this template as an argument slot, padded to an
448
- // empty string when a call omits it (the shared `paddedArguments`
449
- // machinery every other constructor carrier's trailing-optional
450
- // argument goes through).
451
- AudioConstructor: "gea::host::HTMLAudioElement({arg0})",
452
- // `new MediaStream(): MediaStream` -> the default constructor
453
- // (media.h). No arguments in either the declaration or the C++ type.
454
- MediaStreamConstructor: "gea::host::MediaStream()",
458
+ // Creation allocates shared element state; the default native handle
459
+ // remains null for nullable audio-element fields.
460
+ AudioConstructor: "gea::host::HTMLAudioElement::create({args})",
461
+ // A JS stream gets a valid, independently mutable container. The C++
462
+ // default handle remains the null sentinel for nullable host results.
463
+ MediaStreamConstructor: "gea::host::media::create_media_stream({args})",
455
464
  // `new MediaRecorder(stream, options?): MediaRecorder` -> the two-
456
465
  // argument constructor (media.h's `MediaRecorder(MediaStream, const
457
466
  // Options&)` template, `Options` deduced). A call that omits `options`
@@ -466,14 +475,8 @@ export function createGeaHostShims() {
466
475
  // wrapping `gea::host::websocket::create_handle(const std::string&)`
467
476
  // (websocket.h). One argument, no padding needed -- the declared
468
477
  // constructor takes `url` as required.
469
- WebSocketConstructor: "gea::host::WebSocket(gea::host::websocket::create_handle({arg0}))",
470
- // `new RTCPeerConnection(config): RTCPeerConnection` -> the templated
471
- // `gea::host::rtc::create_handle(const Config&)` overload (rtc.h),
472
- // which accepts the emitted config record's own C++ type directly (its
473
- // own comment: "for now we ignore the contents and fall back to the
474
- // no-arg form" -- a pre-existing, already-shipped limitation this
475
- // binding does not change or paper over).
476
- RTCPeerConnectionConstructor: "gea::host::RTCPeerConnection(gea::host::rtc::create_handle({arg0}))",
478
+ WebSocketConstructor: "gea::host::WebSocket(gea::host::websocket::create_handle({args}))",
479
+ // Standard RTC construction and object members are installed by extendRtcShims.
477
480
  },
478
481
  hostGlobalObjects: {
479
482
  navigator: "gea::host::navigator",
@@ -1054,14 +1057,14 @@ export function createGeaHostShims() {
1054
1057
  deviceFacingAt: "gea::host::Camera.deviceFacingAt",
1055
1058
  },
1056
1059
  __gea_audioContext: {
1057
- createOscillator: "gea::host::audioContext.createOscillator",
1058
- createBufferSource: "gea::host::audioContext.createBufferSource",
1059
- decodeAudioData: "gea::host::audioContext.decodeAudioData",
1060
+ createOscillator: "gea::host::sharedAudioContext().createOscillator",
1061
+ createBufferSource: "gea::host::sharedAudioContext().createBufferSource",
1062
+ decodeAudioData: "gea::host::sharedAudioContext().decodeAudioData",
1060
1063
  },
1061
1064
  audioContext: {
1062
- createOscillator: "gea::host::audioContext.createOscillator",
1063
- createBufferSource: "gea::host::audioContext.createBufferSource",
1064
- decodeAudioData: "gea::host::audioContext.decodeAudioData",
1065
+ createOscillator: "gea::host::sharedAudioContext().createOscillator",
1066
+ createBufferSource: "gea::host::sharedAudioContext().createBufferSource",
1067
+ decodeAudioData: "gea::host::sharedAudioContext().decodeAudioData",
1065
1068
  },
1066
1069
  __gea_Audio: {
1067
1070
  getVolume: "gea::host::Audio.getVolume",
@@ -1704,7 +1707,10 @@ export function createGeaHostShims() {
1704
1707
  {
1705
1708
  emit: "static_cast<double>(({receiver}).delta)",
1706
1709
  returnType: "double",
1707
- receiverTypes: ["gea::framework::events::PointerEvent", "RotaryEvent"],
1710
+ receiverTypes: [
1711
+ "gea::framework::events::PointerEvent",
1712
+ "RotaryEvent",
1713
+ ],
1708
1714
  },
1709
1715
  ],
1710
1716
  // `<virtual-list>`'s scroll geometry, read off the engine's own
@@ -2372,6 +2378,10 @@ export function createGeaHostShims() {
2372
2378
  ],
2373
2379
  hostExternDeclarations: geaHostExternDeclarations,
2374
2380
  embeddedHostFunctions: {
2381
+ // These are declared by core/index.d.ts rather than the standard lib;
2382
+ // btoa also has the host's existing ArrayBuffer/Uint8Array overloads.
2383
+ atob: "gea::runtime::hostbase64::decode",
2384
+ btoa: "gea::runtime::hostbase64::encode",
2375
2385
  requestAnimationFrame: "gea::host::requestAnimationFrame",
2376
2386
  // The WHATWG timer globals, from the same engine header and the same
2377
2387
  // translation unit as `requestAnimationFrame` above
@@ -2509,29 +2519,29 @@ export function createGeaHostShims() {
2509
2519
  },
2510
2520
  __gea_audioContext: {
2511
2521
  createOscillator: {
2512
- emit: "gea::host::audioContext.createOscillator({args})",
2522
+ emit: "gea::host::sharedAudioContext().createOscillator({args})",
2513
2523
  returnType: "gea::host::OscillatorNode",
2514
2524
  },
2515
2525
  createBufferSource: {
2516
- emit: "gea::host::audioContext.createBufferSource({args})",
2526
+ emit: "gea::host::sharedAudioContext().createBufferSource({args})",
2517
2527
  returnType: "gea::host::AudioBufferSourceNode",
2518
2528
  },
2519
2529
  decodeAudioData: {
2520
- emit: "gea::host::audioContext.decodeAudioData({args})",
2530
+ emit: "gea::host::sharedAudioContext().decodeAudioData({args})",
2521
2531
  returnType: "gea::host::AudioBuffer",
2522
2532
  },
2523
2533
  },
2524
2534
  audioContext: {
2525
2535
  createOscillator: {
2526
- emit: "gea::host::audioContext.createOscillator({args})",
2536
+ emit: "gea::host::sharedAudioContext().createOscillator({args})",
2527
2537
  returnType: "gea::host::OscillatorNode",
2528
2538
  },
2529
2539
  createBufferSource: {
2530
- emit: "gea::host::audioContext.createBufferSource({args})",
2540
+ emit: "gea::host::sharedAudioContext().createBufferSource({args})",
2531
2541
  returnType: "gea::host::AudioBufferSourceNode",
2532
2542
  },
2533
2543
  decodeAudioData: {
2534
- emit: "gea::host::audioContext.decodeAudioData({args})",
2544
+ emit: "gea::host::sharedAudioContext().decodeAudioData({args})",
2535
2545
  returnType: "gea::host::AudioBuffer",
2536
2546
  },
2537
2547
  },
@@ -3002,8 +3012,8 @@ export function createGeaHostShims() {
3002
3012
  // which reconstructs the wrapper from a generic DOM node id and is
3003
3013
  // untouched.
3004
3014
  receiverTypes: ["gea::host::HTMLAudioElement", "HTMLAudioElement"],
3005
- emit: "({receiver}).play()",
3006
- returnType: "bool",
3015
+ emit: "gea::runtime::hostaudio::play({receiver})",
3016
+ returnType: "gea::Promise<void>",
3007
3017
  },
3008
3018
  {
3009
3019
  receiverTypes: NODE_HANDLE_RECEIVER_TYPES,
@@ -3198,11 +3208,11 @@ export function createGeaHostShims() {
3198
3208
  },
3199
3209
  embeddedHostConstants: {
3200
3210
  audioContext: {
3201
- emit: "gea::host::audioContext",
3211
+ emit: "gea::host::sharedAudioContext()",
3202
3212
  type: "gea::host::AudioContext",
3203
3213
  },
3204
3214
  __gea_audioContext: {
3205
- emit: "gea::host::audioContext",
3215
+ emit: "gea::host::sharedAudioContext()",
3206
3216
  type: "gea::host::AudioContext",
3207
3217
  },
3208
3218
  },
@@ -3214,12 +3224,12 @@ export function createGeaHostShims() {
3214
3224
  },
3215
3225
  Audio: {
3216
3226
  wrapper: "gea::host::HTMLAudioElement",
3217
- construct: "gea::host::HTMLAudioElement({args})",
3227
+ construct: "gea::host::HTMLAudioElement::create({args})",
3218
3228
  allowConcrete: true,
3219
3229
  },
3220
3230
  MediaStream: {
3221
3231
  wrapper: "gea::host::MediaStream",
3222
- construct: "gea::host::MediaStream({args})",
3232
+ construct: "gea::host::media::create_media_stream({args})",
3223
3233
  allowConcrete: true,
3224
3234
  },
3225
3235
  MediaRecorder: {
@@ -3236,6 +3246,6 @@ export function createGeaHostShims() {
3236
3246
  wrapper: "gea::host::RTCPeerConnection",
3237
3247
  },
3238
3248
  },
3239
- };
3249
+ })));
3240
3250
  }
3241
3251
  export const geaHostShims = createGeaHostShims();
@@ -0,0 +1,2 @@
1
+ import type { HostShimDefinitions } from './types.js';
2
+ export declare function extendRtcShims(shims: HostShimDefinitions): HostShimDefinitions;
@@ -0,0 +1,152 @@
1
+ // One mapping for the standard RTC objects. The app does not supply a plugin.
2
+ export function extendRtcShims(shims) {
3
+ const types = ['RTCDataChannel', 'RTCRtpTransceiver', 'RTCRtpSender', 'RTCRtpReceiver', 'RTCIceCandidate', 'RTCTrackEvent'];
4
+ for (const type of types)
5
+ shims.nativeTypes[type] = `gea::host::${type}`;
6
+ shims.nativeTypes.RTCSessionDescription = 'gea::host::RTCSessionDescriptionObject';
7
+ shims.nativeTypes.RTCSessionDescriptionConstructor = 'gea::host::RTCSessionDescriptionObject';
8
+ shims.nativeTypes.RTCIceCandidateConstructor = 'gea::host::RTCIceCandidate';
9
+ shims.nativeViews = {
10
+ ...shims.nativeViews,
11
+ 'gea::host::HTMLVideoElement': {
12
+ 'gea::embedded::ui::NodeHandle': 'gea::host::HTMLVideoElement({value})',
13
+ },
14
+ 'gea::host::HTMLAudioElement': {
15
+ 'gea::embedded::ui::NodeHandle': 'gea::host::HTMLAudioElement({value})',
16
+ },
17
+ };
18
+ const receivers = (type) => [shims.nativeTypes[type] ?? `gea::host::${type}`, type, ...(type === 'RTCPeerConnection' ? ['RTCPeerConnectionInstance'] : [])];
19
+ const get = (type, name, result, optional = false) => {
20
+ const rows = (shims.nativeMemberPropertyGetters[name] ||= []);
21
+ rows.push({ receiverTypes: receivers(type), returnType: result,
22
+ emit: optional ? `gea::runtime::hostrtc::optional(({receiver}).${name}())` : `({receiver}).${name}()` });
23
+ };
24
+ const set = (type, name, method) => {
25
+ const rows = (shims.nativeMemberPropertySetters[name] ||= []);
26
+ rows.push({ receiverTypes: receivers(type), returnType: 'void', emit: `({receiver}).${method}({value})` });
27
+ };
28
+ const call = (type, name, result, emit = `({receiver}).${name}({args})`) => {
29
+ const rows = (shims.nativeMemberMethods[name] ||= []);
30
+ const prior = rows.findIndex(row => row.receiverTypes?.includes(type));
31
+ const row = { receiverTypes: receivers(type), returnType: result, emit };
32
+ if (prior >= 0)
33
+ rows[prior] = row;
34
+ else
35
+ rows.push(row);
36
+ };
37
+ shims.nativeTypes.PcmAudioStream = 'gea::host::PcmAudioStream';
38
+ shims.nativeTypes.PcmAudioStreamConstructor = 'gea::host::PcmAudioStream';
39
+ shims.nativeConstructors.PcmAudioStreamConstructor = 'gea::host::PcmAudioStream::create({args})';
40
+ for (const name of ['queuedMs', 'playedMs', 'audioLevel', 'capturePendingMs', 'captureDroppedSamples', 'capturePackets'])
41
+ get('PcmAudioStream', name, 'double');
42
+ get('PcmAudioStream', 'drained', 'bool');
43
+ call('PcmAudioStream', 'readBase64', 'std::string');
44
+ for (const name of ['setInput', 'pipeTo', 'receiveFrom', 'writeBase64', 'resetPlayback', 'close'])
45
+ call('PcmAudioStream', name, 'void');
46
+ get('WebSocketInstance', 'bufferedAmount', 'double');
47
+ get('WebSocketInstance', 'readyState', 'double');
48
+ get('RTCPeerConnection', 'signalingState', 'std::string');
49
+ get('HTMLAudioElement', 'srcObject', 'gea::host::MediaStream');
50
+ get('HTMLAudioElement', 'autoplay', 'bool');
51
+ get('HTMLAudioElement', 'paused', 'bool');
52
+ get('HTMLAudioElement', 'drained', 'bool');
53
+ get('HTMLAudioElement', 'audioLevel', 'double');
54
+ call('HTMLAudioElement', 'beginDrain', 'void');
55
+ call('HTMLAudioElement', 'clearBufferedAudio', 'void');
56
+ set('HTMLAudioElement', 'srcObject', 'setSrcObject');
57
+ set('HTMLAudioElement', 'autoplay', 'setAutoplay');
58
+ get('HTMLVideoElement', 'srcObject', 'gea::host::MediaStream');
59
+ get('HTMLVideoElement', 'src', 'std::string');
60
+ get('HTMLVideoElement', 'autoplay', 'bool');
61
+ get('HTMLVideoElement', 'paused', 'bool');
62
+ get('HTMLVideoElement', 'videoWidth', 'double');
63
+ get('HTMLVideoElement', 'videoHeight', 'double');
64
+ set('HTMLVideoElement', 'srcObject', 'setSrcObject');
65
+ set('HTMLVideoElement', 'src', 'setSrc');
66
+ set('HTMLVideoElement', 'autoplay', 'setAutoplay');
67
+ set('HTMLVideoElement', 'onplaying', 'setOnPlaying');
68
+ call('HTMLVideoElement', 'play', 'gea::Promise<void>', 'gea::runtime::hostaudio::play({receiver})');
69
+ call('HTMLVideoElement', 'pause', 'void');
70
+ get('RTCTrackEvent', 'track', 'gea::host::MediaStreamTrack');
71
+ get('RTCTrackEvent', 'streams', 'std::vector<gea::host::MediaStream>');
72
+ get('RTCTrackEvent', 'receiver', 'gea::host::RTCRtpReceiver');
73
+ get('RTCTrackEvent', 'transceiver', 'gea::host::RTCRtpTransceiver');
74
+ get('RTCSessionDescription', 'type', 'std::string');
75
+ get('RTCSessionDescription', 'sdp', 'std::string');
76
+ call('RTCSessionDescription', 'toJSON', 'gea::runtime::hostrtc::DescriptionSnapshot', 'gea::runtime::hostrtc::descriptionJson({receiver})');
77
+ get('RTCIceCandidate', 'candidate', 'std::string');
78
+ for (const name of ['sdpMid', 'foundation', 'component', 'address', 'protocol', 'type', 'tcpType', 'relatedAddress', 'usernameFragment', 'relayProtocol', 'url'])
79
+ get('RTCIceCandidate', name, 'gea::Optional<std::string>', true);
80
+ for (const name of ['sdpMLineIndex', 'priority', 'port', 'relatedPort'])
81
+ get('RTCIceCandidate', name, 'gea::Optional<double>', true);
82
+ call('RTCIceCandidate', 'toJSON', 'gea::runtime::hostrtc::CandidateSnapshot', 'gea::runtime::hostrtc::candidateJson({receiver})');
83
+ get('MediaStream', 'active', 'bool');
84
+ call('MediaStream', 'getVideoTracks', 'std::vector<gea::host::MediaStreamTrack>');
85
+ call('MediaStream', 'getTrackById', 'gea::host::MediaStreamTrack');
86
+ call('MediaStream', 'addTrack', 'void');
87
+ call('MediaStream', 'removeTrack', 'void');
88
+ for (const name of ['localDescription', 'remoteDescription']) {
89
+ (shims.nativeMemberPropertyGetters[name] ||= []).push({
90
+ receiverTypes: receivers('RTCPeerConnection'), returnType: 'gea::runtime::hostrtc::DescriptionSnapshot',
91
+ emit: `gea::runtime::hostrtc::${name}({receiver})`,
92
+ });
93
+ }
94
+ for (const [type, names] of [
95
+ ['RTCDataChannel', ['label', 'protocol', 'readyState', 'binaryType']],
96
+ ['RTCRtpTransceiver', ['direction']],
97
+ ])
98
+ for (const name of names)
99
+ get(type, name, 'std::string');
100
+ for (const name of ['id', 'maxRetransmits', 'maxPacketLifeTime'])
101
+ get('RTCDataChannel', name, 'gea::Optional<double>', true);
102
+ for (const name of ['bufferedAmount', 'bufferedAmountLowThreshold'])
103
+ get('RTCDataChannel', name, 'double');
104
+ get('RTCDataChannel', 'ordered', 'bool');
105
+ get('RTCRtpTransceiver', 'stopped', 'bool');
106
+ for (const name of ['mid', 'currentDirection'])
107
+ get('RTCRtpTransceiver', name, 'gea::Optional<std::string>', true);
108
+ get('RTCRtpTransceiver', 'sender', 'gea::host::RTCRtpSender');
109
+ get('RTCRtpTransceiver', 'receiver', 'gea::host::RTCRtpReceiver');
110
+ // Nullable native handles use their zero handle, unlike nullable primitives
111
+ // (which use Optional). State keeps std::optional; the JS ABI keeps the handle.
112
+ for (const type of ['RTCRtpSender', 'RTCRtpReceiver']) {
113
+ (shims.nativeMemberPropertyGetters.track ||= []).push({
114
+ receiverTypes: receivers(type), returnType: 'gea::host::MediaStreamTrack',
115
+ emit: '({receiver}).track().value_or(gea::host::MediaStreamTrack{})',
116
+ });
117
+ }
118
+ set('RTCDataChannel', 'binaryType', 'setBinaryType');
119
+ set('RTCDataChannel', 'bufferedAmountLowThreshold', 'setBufferedAmountLowThreshold');
120
+ set('RTCRtpTransceiver', 'direction', 'setDirection');
121
+ call('RTCDataChannel', 'close', 'void');
122
+ call('RTCRtpTransceiver', 'stop', 'void');
123
+ call('RTCDataChannel', 'send', 'void', 'gea::runtime::hostrtc::send({receiver}, {arg0})');
124
+ call('RTCRtpSender', 'replaceTrack', 'gea::Promise<void>', 'gea::runtime::hostrtc::replaceTrack({receiver}, {arg0})');
125
+ call('RTCPeerConnection', 'addTrack', 'gea::host::RTCRtpSender');
126
+ call('RTCPeerConnection', 'removeTrack', 'void');
127
+ call('RTCPeerConnection', 'createDataChannel', 'gea::host::RTCDataChannel', 'gea::runtime::hostrtc::createDataChannel({receiver}, {args})');
128
+ call('RTCPeerConnection', 'addTransceiver', 'gea::host::RTCRtpTransceiver', 'gea::runtime::hostrtc::addTransceiver({receiver}, {args})');
129
+ for (const [method, type] of [['getSenders', 'RTCRtpSender'], ['getReceivers', 'RTCRtpReceiver'], ['getTransceivers', 'RTCRtpTransceiver']])
130
+ call('RTCPeerConnection', method, `std::vector<gea::host::${type}>`);
131
+ for (const [type, name, method] of [
132
+ ['RTCDataChannel', 'onopen', 'setChannelOnOpen'],
133
+ ['RTCDataChannel', 'onclose', 'setChannelOnClose'],
134
+ ['RTCDataChannel', 'onbufferedamountlow', 'setChannelOnLow'],
135
+ ['RTCDataChannel', 'onmessage', 'setChannelOnMessage'],
136
+ ['RTCPeerConnection', 'ondatachannel', 'setPeerOnDataChannel'],
137
+ ['RTCPeerConnection', 'ontrack', 'setPeerOnTrack'],
138
+ ['RTCPeerConnection', 'onsignalingstatechange', 'setPeerOnSignaling'],
139
+ ['RTCPeerConnection', 'onnegotiationneeded', 'setPeerOnNegotiation'],
140
+ ]) {
141
+ (shims.nativeMemberPropertySetters[name] ||= []).push({
142
+ receiverTypes: receivers(type), returnType: 'void', emit: `gea::runtime::hostrtc::${method}({receiver}, {value})`,
143
+ });
144
+ }
145
+ shims.nativeConstructors.RTCPeerConnectionConstructor = 'gea::runtime::hostrtc::createPeer({args})';
146
+ shims.embeddedHostClasses.RTCPeerConnection = { wrapper: 'gea::host::RTCPeerConnection', construct: 'gea::runtime::hostrtc::createPeer({args})' };
147
+ shims.nativeConstructors.RTCSessionDescriptionConstructor = 'gea::runtime::hostrtc::createDescription({arg0})';
148
+ shims.embeddedHostClasses.RTCSessionDescription = { wrapper: 'gea::host::RTCSessionDescriptionObject', construct: 'gea::runtime::hostrtc::createDescription({args})' };
149
+ shims.nativeConstructors.RTCIceCandidateConstructor = 'gea::runtime::hostrtc::createCandidate({args})';
150
+ shims.embeddedHostClasses.RTCIceCandidate = { wrapper: 'gea::host::RTCIceCandidate', construct: 'gea::runtime::hostrtc::createCandidate({args})' };
151
+ return shims;
152
+ }
package/dist/types.d.ts CHANGED
@@ -12,7 +12,15 @@ export interface PluginCppContext {
12
12
  modules: EmitModule[];
13
13
  }
14
14
  export interface HostShimDefinitions {
15
+ /** Exact host-owned declarations for the compiler's CommonJS module records. */
16
+ commonJsGlobals?: Record<string, {
17
+ global: "require" | "exports" | "module";
18
+ declarationName: string;
19
+ declarationFileName: string;
20
+ }>;
15
21
  nativeTypes?: Record<string, string>;
22
+ /** Identity-preserving views: destination carrier -> source carrier -> {value} template. */
23
+ nativeViews?: Record<string, Record<string, string>>;
16
24
  /**
17
25
  * `new <AmbientConstructor>(...)` construct spellings, for a declared
18
26
  * ambient constructor interface whose instance type already has a
@@ -0,0 +1,2 @@
1
+ import type { HostShimDefinitions } from './types.js';
2
+ export declare function extendWorkerShims(shims: HostShimDefinitions): HostShimDefinitions;
@@ -0,0 +1,51 @@
1
+ import { geaHostDeclarations } from './host-declarations.js';
2
+ export function extendWorkerShims(shims) {
3
+ const namespace = 'gea::host::workers';
4
+ const bridge = 'gea::runtime::hostworker';
5
+ const declarations = [...geaHostDeclarations, '#include "gea/worker-runtime.h"'];
6
+ const types = ['Worker', 'MessageChannel', 'MessagePort', 'DedicatedWorkerGlobalScope'];
7
+ for (const type of types) {
8
+ const native = `${namespace}::${type}`;
9
+ shims.nativeTypes[type] = native;
10
+ shims.hostExternDeclarations[native] = declarations;
11
+ }
12
+ const receivers = (type) => [type, shims.nativeTypes[type]];
13
+ const method = (type, name, result, emit) => {
14
+ ;
15
+ (shims.nativeMemberMethods[name] ||= []).push({ receiverTypes: receivers(type), returnType: result, emit });
16
+ shims.hostExternDeclarations[emit] = declarations;
17
+ };
18
+ const setter = (type, name, emit) => {
19
+ ;
20
+ (shims.nativeMemberPropertySetters[name] ||= []).push({ receiverTypes: receivers(type), returnType: 'void', emit });
21
+ shims.hostExternDeclarations[emit] = declarations;
22
+ };
23
+ shims.nativeTypes.WorkerConstructor = `${namespace}::Worker`;
24
+ shims.nativeTypes.MessageChannelConstructor = `${namespace}::MessageChannel`;
25
+ shims.nativeConstructors.WorkerConstructor = `${bridge}::createWorker({args})`;
26
+ shims.nativeConstructors.MessageChannelConstructor = `${namespace}::MessageChannel()`;
27
+ shims.hostExternDeclarations[`${bridge}::createWorker`] = declarations;
28
+ shims.hostGlobalObjects.self = `${namespace}::self()`;
29
+ shims.hostGlobalObjectTypes.self = `${namespace}::DedicatedWorkerGlobalScope`;
30
+ shims.embeddedHostConstants.self = {
31
+ emit: `${namespace}::self()`,
32
+ type: `${namespace}::DedicatedWorkerGlobalScope`,
33
+ };
34
+ shims.hostExternDeclarations[`${namespace}::self()`] = declarations;
35
+ for (const type of ['Worker', 'MessagePort', 'DedicatedWorkerGlobalScope']) {
36
+ method(type, 'postMessage', 'void', `${bridge}::postMessage({receiver}, {args})`);
37
+ setter(type, 'onmessage', `${bridge}::setOnMessage({receiver}, {value})`);
38
+ }
39
+ setter('Worker', 'onerror', `${bridge}::setOnError({receiver}, {value})`);
40
+ method('Worker', 'terminate', 'void', '({receiver}).terminate()');
41
+ method('MessagePort', 'start', 'void', '({receiver}).start()');
42
+ method('MessagePort', 'close', 'void', '({receiver}).close()');
43
+ method('DedicatedWorkerGlobalScope', 'close', 'void', `${namespace}::Context::current()->stop()`);
44
+ for (const name of ['port1', 'port2']) {
45
+ ;
46
+ (shims.nativeMemberPropertyGetters[name] ||= []).push({
47
+ receiverTypes: receivers('MessageChannel'), returnType: `${namespace}::MessagePort`, emit: `({receiver}).${name}`,
48
+ });
49
+ }
50
+ return shims;
51
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/geatsc-plugin-gea",
3
- "version": "0.1.14",
3
+ "version": "0.1.15",
4
4
  "description": "Gea IR backend plugin for geatsc.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -33,7 +33,9 @@
33
33
  "./package.json": "./package.json"
34
34
  },
35
35
  "files": [
36
- "dist"
36
+ "dist/**/*.js",
37
+ "dist/**/*.d.ts",
38
+ "commonjs-wrapper.d.ts"
37
39
  ],
38
40
  "publishConfig": {
39
41
  "access": "public"
@@ -47,13 +49,13 @@
47
49
  "pretypecheck": "npm run architecture",
48
50
  "typecheck": "tsc -p tsconfig.json --noEmit"
49
51
  },
52
+ "dependencies": {
53
+ "typescript": "^5.9.3"
54
+ },
50
55
  "devDependencies": {
51
56
  "@types/node": "^22.15.3"
52
57
  },
53
58
  "peerDependencies": {
54
59
  "@geastack/compiler": ">=1.0.20"
55
- },
56
- "dependencies": {
57
- "typescript": "^5.9.3"
58
60
  }
59
61
  }