react-native-roku 0.0.0-stage → 0.2.0-preview.3

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.
Files changed (200) hide show
  1. package/CHANGELOG.md +328 -0
  2. package/CONTRIBUTING.md +34 -0
  3. package/LICENSE +21 -0
  4. package/NOTICE.md +10 -0
  5. package/README.md +66 -2
  6. package/bin/react-native-roku.mjs +91 -0
  7. package/build/assets.cjs +311 -0
  8. package/build/assets.d.cts +50 -0
  9. package/build/compatibility.d.mts +40 -0
  10. package/build/compatibility.mjs +272 -0
  11. package/build/dev.d.mts +34 -0
  12. package/build/dev.mjs +297 -0
  13. package/build/devWorkspace.d.mts +11 -0
  14. package/build/devWorkspace.mjs +86 -0
  15. package/build/device.d.mts +47 -0
  16. package/build/device.mjs +310 -0
  17. package/build/environment.d.mts +29 -0
  18. package/build/environment.mjs +144 -0
  19. package/build/esbuild.d.mts +5 -0
  20. package/build/esbuild.mjs +118 -0
  21. package/build/fontVariants.d.mts +27 -0
  22. package/build/fontVariants.mjs +424 -0
  23. package/build/frontend.d.mts +52 -0
  24. package/build/frontend.mjs +75 -0
  25. package/build/identity.mjs +45 -0
  26. package/build/index.d.mts +22 -0
  27. package/build/index.mjs +87 -0
  28. package/build/intl.mjs +121 -0
  29. package/build/metro.cjs +38 -0
  30. package/build/metro.d.cts +37 -0
  31. package/build/metroFrontend.mjs +222 -0
  32. package/build/metroMetadata.mjs +119 -0
  33. package/build/metroModules.mjs +397 -0
  34. package/build/metroRefresh.d.mts +64 -0
  35. package/build/metroRefresh.mjs +346 -0
  36. package/build/metroTransformer.cjs +146 -0
  37. package/build/nativeTextMemo.mjs +296 -0
  38. package/build/nativewind.d.mts +9 -0
  39. package/build/nativewind.mjs +92 -0
  40. package/build/project.d.mts +111 -0
  41. package/build/project.mjs +615 -0
  42. package/build/reactCompiler.mjs +113 -0
  43. package/build/reactProfile.cjs +35 -0
  44. package/build/refreshRuntime.mjs +187 -0
  45. package/build/refreshSourceMap.mjs +53 -0
  46. package/build/release.mjs +99 -0
  47. package/build/resolution.d.mts +3 -0
  48. package/build/resolution.mjs +25 -0
  49. package/build/surfaces.d.mts +1 -0
  50. package/build/surfaces.mjs +42 -0
  51. package/build/testing/node.d.mts +29 -0
  52. package/build/testing/node.mjs +106 -0
  53. package/build/yoga.d.mts +8 -0
  54. package/build/yoga.mjs +186 -0
  55. package/compatibility/public-api.json +327 -0
  56. package/compatibility/registry.json +2258 -0
  57. package/config/release.json +15 -0
  58. package/config/toolchain.json +34 -0
  59. package/docs/compatibility.md +813 -0
  60. package/docs/getting-started.md +460 -0
  61. package/docs/maintenance.md +368 -0
  62. package/docs/qualification.md +241 -0
  63. package/docs/standalone-testing.md +56 -0
  64. package/examples/hello-roku/README.md +35 -0
  65. package/examples/hello-roku/package.template.json +31 -0
  66. package/examples/hello-roku/pnpm-workspace.yaml +11 -0
  67. package/examples/hello-roku/roku.config.json +22 -0
  68. package/examples/hello-roku/src/App.tsx +54 -0
  69. package/examples/hello-roku/src/Catalog.tsx +200 -0
  70. package/examples/hello-roku/src/assets.d.ts +16 -0
  71. package/examples/hello-roku/src/catalog-cover.png +0 -0
  72. package/examples/hello-roku/tsconfig.json +1 -0
  73. package/examples/hello-roku/tsconfig.react.json +1 -0
  74. package/native/components/RNRAppControl.brs +215 -0
  75. package/native/components/RNRAppControl.xml +13 -0
  76. package/native/components/RNRDeviceFacts.brs +19 -0
  77. package/native/components/RNRDeviceFacts.xml +9 -0
  78. package/native/components/RNRDeviceFactsTask.brs +74 -0
  79. package/native/components/RNRDeviceFactsTask.xml +9 -0
  80. package/native/components/RNRTextRaster.brs +15 -0
  81. package/native/components/RNRTextRaster.xml +9 -0
  82. package/native/components/RNRTextRasterTask.brs +77 -0
  83. package/native/components/RNRTextRasterTask.xml +9 -0
  84. package/native/manifest.json +7 -0
  85. package/package.json +183 -3
  86. package/src/animation/clock.ts +10 -0
  87. package/src/animation/derivedValue.ts +163 -0
  88. package/src/animation/legacyAnimated.ts +255 -0
  89. package/src/animation/reanimated.ts +243 -0
  90. package/src/animation/sharedValue.ts +285 -0
  91. package/src/animation/worklets.ts +23 -0
  92. package/src/application/AppRegistry.ts +31 -0
  93. package/src/application/mountApplication.ts +136 -0
  94. package/src/graphics/BitmapLayer.tsx +68 -0
  95. package/src/graphics/RoundedBorder.tsx +116 -0
  96. package/src/graphics/TextRasterCache.ts +259 -0
  97. package/src/graphics/gradient.ts +37 -0
  98. package/src/graphics/inlineRaster.ts +85 -0
  99. package/src/graphics/png.ts +77 -0
  100. package/src/graphics/rasterPixels.ts +89 -0
  101. package/src/graphics/surfaces.ts +105 -0
  102. package/src/graphics/textRaster.types.ts +60 -0
  103. package/src/graphics/textRasterGeometry.ts +116 -0
  104. package/src/host/host.types.ts +57 -0
  105. package/src/index.ts +22 -0
  106. package/src/interop/nativewind.ts +2 -0
  107. package/src/layout/FontResources.ts +252 -0
  108. package/src/layout/affine.ts +89 -0
  109. package/src/layout/flexLayout.ts +398 -0
  110. package/src/layout/fontFaces.d.mts +19 -0
  111. package/src/layout/fontFaces.mjs +85 -0
  112. package/src/layout/fontVariants.d.mts +2 -0
  113. package/src/layout/fontVariants.mjs +8 -0
  114. package/src/layout/inlineParagraph.ts +158 -0
  115. package/src/layout/inlineText.ts +68 -0
  116. package/src/layout/layoutReuse.ts +117 -0
  117. package/src/layout/nativeNodeFields.ts +179 -0
  118. package/src/layout/preparedFields.ts +78 -0
  119. package/src/layout/textLayout.ts +138 -0
  120. package/src/layout/transform.ts +113 -0
  121. package/src/media/SceneGraphAudio.ts +161 -0
  122. package/src/media/SceneGraphVideo.ts +167 -0
  123. package/src/media/audioSession.ts +84 -0
  124. package/src/media/index.ts +2 -0
  125. package/src/media/videoErrorDetails.ts +40 -0
  126. package/src/media/videoSession.ts +136 -0
  127. package/src/navigation/RouterStore.ts +244 -0
  128. package/src/navigation/expoRouter.ts +115 -0
  129. package/src/react-native/NativeInput.ts +494 -0
  130. package/src/react-native/NativeSystemState.ts +95 -0
  131. package/src/react-native/accessibility.ts +265 -0
  132. package/src/react-native/activityIndicator.ts +72 -0
  133. package/src/react-native/compilerPressable.ts +26 -0
  134. package/src/react-native/createNativeRoot.ts +2126 -0
  135. package/src/react-native/directionalFocus.ts +55 -0
  136. package/src/react-native/environment.ts +275 -0
  137. package/src/react-native/flatList.ts +1001 -0
  138. package/src/react-native/flatListViewability.ts +231 -0
  139. package/src/react-native/focusEvents.ts +85 -0
  140. package/src/react-native/image.ts +247 -0
  141. package/src/react-native/index.ts +54 -0
  142. package/src/react-native/interactionManager.ts +76 -0
  143. package/src/react-native/keyboard.ts +60 -0
  144. package/src/react-native/linearGradient.ts +94 -0
  145. package/src/react-native/modal.tsx +148 -0
  146. package/src/react-native/nativeHostContext.ts +80 -0
  147. package/src/react-native/nativeModules.ts +86 -0
  148. package/src/react-native/nativeRoot.types.ts +22 -0
  149. package/src/react-native/nativeViewHandle.ts +191 -0
  150. package/src/react-native/nativewindPressable.ts +38 -0
  151. package/src/react-native/panResponder.ts +73 -0
  152. package/src/react-native/primitives.ts +685 -0
  153. package/src/react-native/safeArea.ts +76 -0
  154. package/src/react-native/scrollView.ts +289 -0
  155. package/src/react-native/styleInterop.ts +8 -0
  156. package/src/react-native/styleSheet.ts +54 -0
  157. package/src/react-native/textInput.ts +334 -0
  158. package/src/react-native/unsupported.ts +25 -0
  159. package/src/renderer/SceneRoot.ts +1006 -0
  160. package/src/scene/SdkDeviceFacts.ts +151 -0
  161. package/src/scene/SdkDeviceServices.ts +72 -0
  162. package/src/scene/SdkSceneGraph.ts +124 -0
  163. package/src/scene/SdkTextEntry.ts +321 -0
  164. package/src/scene/SdkTextMetrics.ts +136 -0
  165. package/src/scene/SdkTextRasterTransport.ts +191 -0
  166. package/src/scene/SdkWebTransport.ts +122 -0
  167. package/src/scene/createRokuHost.ts +213 -0
  168. package/src/scene/sceneGraph.types.ts +38 -0
  169. package/src/services/DeviceServices.ts +53 -0
  170. package/src/services/RegistryStorage.ts +85 -0
  171. package/src/services/RokuKeySession.ts +29 -0
  172. package/src/services/asyncStorage.ts +23 -0
  173. package/src/services/base64.ts +52 -0
  174. package/src/services/crypto.ts +18 -0
  175. package/src/services/expoConstants.ts +11 -0
  176. package/src/services/expoLinking.ts +12 -0
  177. package/src/services/expoStatusBar.ts +4 -0
  178. package/src/services/installWebRuntime.ts +105 -0
  179. package/src/services/intlEnglish.ts +54 -0
  180. package/src/services/languageRuntime.ts +65 -0
  181. package/src/services/nativeTimers.ts +96 -0
  182. package/src/services/secureStore.ts +23 -0
  183. package/src/services/textEntryRequest.ts +22 -0
  184. package/src/services/utf8.ts +57 -0
  185. package/src/services/webRuntime.ts +346 -0
  186. package/src/testing/CanvasResources.ts +141 -0
  187. package/src/testing/CanvasSceneGraph.ts +496 -0
  188. package/src/testing/CanvasTextEntry.ts +237 -0
  189. package/src/testing/PreviewTextObservations.ts +82 -0
  190. package/src/testing/RecordingSceneGraph.ts +136 -0
  191. package/src/types/normalize-colors.d.ts +4 -0
  192. package/src/vector/dynamicSvg.tsx +226 -0
  193. package/src/vector/svg.ts +222 -0
  194. package/src/vector/svg.types.ts +4 -0
  195. package/src/vector/svgElements.ts +58 -0
  196. package/src/vector/svgKey.d.mts +4 -0
  197. package/src/vector/svgKey.mjs +16 -0
  198. package/src/vector/svgPath.ts +157 -0
  199. package/src/vector/svgPixels.ts +133 -0
  200. package/tsconfig.consumer.json +29 -0
@@ -0,0 +1,151 @@
1
+ import type { DomNode, TmValue } from "@roku-sdk/interfaces";
2
+ import { tmTransaction } from "@roku-sdk/solid";
3
+ import { transactionManager } from "@roku-sdk/common/transaction";
4
+ import { RokuHostError } from "./sceneGraph.types";
5
+ import type { SystemSnapshot } from "../react-native/NativeSystemState";
6
+
7
+ /** Bounded raw DeviceInfo RPC. Codec policy lives in shared playback code. */
8
+ export class SdkDeviceFacts {
9
+ private sequence = 0;
10
+ private disposed = false;
11
+ private tail = Promise.resolve();
12
+ private current?: {
13
+ id: number;
14
+ resolve(value: unknown): void;
15
+ reject(error: unknown): void;
16
+ timer: ReturnType<typeof setTimeout>;
17
+ };
18
+ private readonly listeners = new Map<
19
+ string,
20
+ Set<(event: Readonly<Record<string, unknown>>) => void>
21
+ >();
22
+ private readonly reply = (value: unknown) => {
23
+ let packet: { id?: number; facts?: unknown; error?: string };
24
+ try {
25
+ packet = JSON.parse(String(value));
26
+ } catch {
27
+ return;
28
+ }
29
+ if (!this.current || packet.id !== this.current.id) return;
30
+ const pending = this.current;
31
+ this.current = undefined;
32
+ clearTimeout(pending.timer);
33
+ if (packet.error) pending.reject(new RokuHostError("C31_DEVICE_FACTS", packet.error));
34
+ else pending.resolve(packet.facts);
35
+ };
36
+ private readonly event = (value: unknown) => {
37
+ if (this.disposed) return;
38
+ let packet: {
39
+ type?: string;
40
+ snapshot?: Partial<SystemSnapshot>;
41
+ routeEpoch?: number;
42
+ level?: string;
43
+ };
44
+ try {
45
+ packet = JSON.parse(String(value));
46
+ } catch {
47
+ return;
48
+ }
49
+ if (packet.type === "system" && packet.snapshot) this.onSystem(packet.snapshot);
50
+ else if (packet.type === "capabilities")
51
+ for (const listener of this.listeners.get("onAudioRouteChanged") ?? [])
52
+ listener({ audioRouteEpoch: packet.routeEpoch });
53
+ else if (packet.type === "memory") {
54
+ const level = packet.level === "low" ? "warning" : packet.level;
55
+ this.onMemory(level);
56
+ for (const listener of this.listeners.get("onResourcePressure") ?? []) listener({ level });
57
+ }
58
+ };
59
+ constructor(
60
+ private readonly node: DomNode,
61
+ private readonly onSystem: (snapshot: Partial<SystemSnapshot>) => void,
62
+ private readonly onMemory: (level?: string) => void,
63
+ ) {
64
+ this.batch(() => {
65
+ tmTransaction.setProperty(node, "onReply", this.reply as TmValue);
66
+ tmTransaction.setProperty(node, "onEvent", this.event as TmValue);
67
+ });
68
+ }
69
+ private batch(work: () => void) {
70
+ transactionManager.startTransaction();
71
+ work();
72
+ }
73
+ probe(request: Readonly<Record<string, unknown>>): Promise<unknown> {
74
+ const payload = JSON.stringify(request);
75
+ if (payload.length > 16_384)
76
+ return Promise.reject(
77
+ new RokuHostError("C31_DEVICE_FACTS", "Decoder request exceeds the bridge limit"),
78
+ );
79
+ const result = this.tail.then(
80
+ () =>
81
+ new Promise<unknown>((resolve, reject) => {
82
+ if (this.disposed) {
83
+ reject(new RokuHostError("C31_DEVICE_FACTS", "Device facts bridge retired"));
84
+ return;
85
+ }
86
+ const id = ++this.sequence;
87
+ const timer = setTimeout(() => {
88
+ if (this.current?.id === id) {
89
+ this.current = undefined;
90
+ reject(new RokuHostError("C31_DEVICE_FACTS", "Device facts query timed out"));
91
+ }
92
+ }, 5000);
93
+ this.current = { id, resolve, reject, timer };
94
+ try {
95
+ this.batch(() =>
96
+ tmTransaction.setProperty(this.node, "request", JSON.stringify({ ...request, id })),
97
+ );
98
+ } catch (error) {
99
+ clearTimeout(timer);
100
+ this.current = undefined;
101
+ reject(error);
102
+ }
103
+ }),
104
+ );
105
+ this.tail = result.then(
106
+ () => undefined,
107
+ () => undefined,
108
+ );
109
+ return result;
110
+ }
111
+ addListener(
112
+ name: string,
113
+ listener: (event: Readonly<Record<string, unknown>>) => void,
114
+ ): { remove(): void } {
115
+ const listeners = this.listeners.get(name) ?? new Set();
116
+ listeners.add(listener);
117
+ this.listeners.set(name, listeners);
118
+ return {
119
+ remove: () => {
120
+ listeners.delete(listener);
121
+ if (!listeners.size && this.listeners.get(name) === listeners) this.listeners.delete(name);
122
+ },
123
+ };
124
+ }
125
+ dispose() {
126
+ if (this.disposed) return;
127
+ this.disposed = true;
128
+ if (this.current) {
129
+ clearTimeout(this.current.timer);
130
+ this.current.reject(new RokuHostError("C31_DEVICE_FACTS", "Device facts bridge retired"));
131
+ this.current = undefined;
132
+ }
133
+ for (const listeners of this.listeners.values()) listeners.clear();
134
+ this.listeners.clear();
135
+ this.batch(() => {
136
+ tmTransaction.setProperty(this.node, "request", JSON.stringify({ type: "dispose" }));
137
+ tmTransaction.setProperty(
138
+ this.node,
139
+ "onReply",
140
+ null as unknown as TmValue,
141
+ this.reply as TmValue,
142
+ );
143
+ tmTransaction.setProperty(
144
+ this.node,
145
+ "onEvent",
146
+ null as unknown as TmValue,
147
+ this.event as TmValue,
148
+ );
149
+ });
150
+ }
151
+ }
@@ -0,0 +1,72 @@
1
+ import { getRegistry } from "@roku-sdk/runtime/registry";
2
+ import { getRandomBytes, randomUUID, subtle } from "@roku-sdk/runtime/crypto";
3
+ import type { CryptoKey } from "@roku-sdk/interfaces";
4
+ import { RegistryStorage } from "../services/RegistryStorage";
5
+ import type { DeviceServices } from "../services/DeviceServices";
6
+ import { decodeUtf8, encodeUtf8, fromHex, toHex } from "../services/utf8";
7
+ import { RokuHostError } from "./sceneGraph.types";
8
+ const deviceKey: CryptoKey = {
9
+ type: "secret",
10
+ extractable: false,
11
+ algorithm: { name: "device" },
12
+ usages: ["encrypt", "decrypt"],
13
+ };
14
+ export async function createSdkDeviceServices(
15
+ options: { readonly namespace?: string } = {},
16
+ ): Promise<DeviceServices> {
17
+ const registry = await getRegistry();
18
+ if (!registry) throw new RokuHostError("C21_STORAGE_HOST", "The device registry is unavailable");
19
+ const storage = new RegistryStorage(
20
+ registry,
21
+ {
22
+ async encode(value) {
23
+ // Empty logical strings still need nonempty plaintext, so a failed native
24
+ // decryption can never be mistaken for a successfully stored empty value.
25
+ const encrypted = await subtle.encrypt(
26
+ "DeviceCrypto",
27
+ deviceKey,
28
+ encodeUtf8(JSON.stringify(["react-native-roku", 2, value])).buffer as ArrayBuffer,
29
+ );
30
+ if (!encrypted.byteLength)
31
+ throw new RokuHostError("C21_SECRET_STORAGE", "Device encryption returned no ciphertext");
32
+ return `pdr2:${toHex(new Uint8Array(encrypted))}`;
33
+ },
34
+ async decode(value) {
35
+ const legacy = value.startsWith("pdr1:");
36
+ if (!legacy && !value.startsWith("pdr2:"))
37
+ throw new RokuHostError("C21_SECRET_STORAGE", "Unrecognized device credential encoding");
38
+ if (!/^(?:[0-9a-f]{2})+$/i.test(value.slice(5)))
39
+ throw new RokuHostError("C21_SECRET_STORAGE", "Invalid device credential ciphertext");
40
+ const decrypted = await subtle.decrypt(
41
+ "DeviceCrypto",
42
+ deviceKey,
43
+ fromHex(value.slice(5)).buffer as ArrayBuffer,
44
+ );
45
+ if (!decrypted.byteLength)
46
+ throw new RokuHostError("C21_SECRET_STORAGE", "Device decryption returned no credential");
47
+ if (legacy) return decodeUtf8(new Uint8Array(decrypted));
48
+ let envelope: unknown;
49
+ try {
50
+ envelope = JSON.parse(decodeUtf8(new Uint8Array(decrypted)));
51
+ } catch {
52
+ throw new RokuHostError("C21_SECRET_STORAGE", "Invalid device credential envelope");
53
+ }
54
+ if (
55
+ !Array.isArray(envelope) ||
56
+ envelope.length !== 3 ||
57
+ envelope[0] !== "react-native-roku" ||
58
+ envelope[1] !== 2 ||
59
+ typeof envelope[2] !== "string"
60
+ )
61
+ throw new RokuHostError("C21_SECRET_STORAGE", "Invalid device credential envelope");
62
+ return envelope[2];
63
+ },
64
+ },
65
+ options.namespace,
66
+ );
67
+ return {
68
+ storage,
69
+ randomUUID,
70
+ randomBytes: (length) => new Uint8Array(getRandomBytes(length)),
71
+ };
72
+ }
@@ -0,0 +1,124 @@
1
+ import type { DomNode, TmValue } from "@roku-sdk/interfaces";
2
+ import { transactionManager } from "@roku-sdk/common/transaction";
3
+ import { tmTransaction } from "@roku-sdk/solid";
4
+ import {
5
+ RokuHostError,
6
+ type SceneFieldListener,
7
+ type SceneGraphPort,
8
+ type SceneNodeRef,
9
+ type SceneValue,
10
+ } from "./sceneGraph.types";
11
+
12
+ /** All unstable SDK Tree API access stays in this device-only adapter. */
13
+ export class SdkSceneGraph implements SceneGraphPort {
14
+ readonly root: SceneNodeRef;
15
+ private nextId = 0;
16
+ private readonly nativeNodes = new Map<SceneNodeRef, DomNode>();
17
+ private readonly issuedRefs = new WeakSet<object>();
18
+
19
+ private focusSampleSequence = 0;
20
+ private releaseFocusSample?: () => void;
21
+
22
+ constructor(
23
+ container: DomNode,
24
+ private readonly focusControl?: DomNode,
25
+ ) {
26
+ this.root = this.retain(container);
27
+ }
28
+ cancelFocusSample(): void {
29
+ this.releaseFocusSample?.();
30
+ }
31
+ sampleFocus(nodes: readonly SceneNodeRef[], receive: (node: SceneNodeRef) => void): void {
32
+ const control = this.focusControl;
33
+ if (!control) return;
34
+ this.releaseFocusSample?.();
35
+ const ticket = ++this.focusSampleSequence;
36
+ const property = "onFocusSampleReply";
37
+ const listener = (value: unknown) => {
38
+ if (typeof value !== "string") return;
39
+ const [sequence, index] = value.split(":").map(Number);
40
+ if (sequence !== ticket) return;
41
+ release();
42
+ if (nodes[index]) receive(nodes[index]);
43
+ };
44
+ const release = () => {
45
+ if (this.releaseFocusSample !== release) return;
46
+ this.releaseFocusSample = undefined;
47
+ clearTimeout(timer);
48
+ this.batch(() =>
49
+ tmTransaction.setProperty(control, property, null as unknown as TmValue, listener),
50
+ );
51
+ };
52
+ const timer = setTimeout(release, 250);
53
+ this.releaseFocusSample = release;
54
+ this.batch(() => {
55
+ tmTransaction.setProperty(control, property, listener);
56
+ tmTransaction.setProperty(control, "focusSampleTarget", this.native(nodes[0]));
57
+ if (nodes[1])
58
+ tmTransaction.setProperty(control, "focusSamplePrevious", this.native(nodes[1]));
59
+ tmTransaction.setProperty(control, "focusSampleTicket", ticket);
60
+ });
61
+ }
62
+ create(type: string): SceneNodeRef {
63
+ return this.retain(tmTransaction.createElement(type));
64
+ }
65
+ set(node: SceneNodeRef, field: string, value: SceneValue): void {
66
+ // The SDK coerces a cleared float to zero. SceneGraph opacity defaults to one.
67
+ const nativeValue = field === "opacity" && value === null ? 1 : value;
68
+ tmTransaction.setProperty(this.native(node), field, this.convert(nativeValue) as TmValue);
69
+ }
70
+ insert(parent: SceneNodeRef, child: SceneNodeRef, before?: SceneNodeRef): void {
71
+ const nativeParent = this.native(parent),
72
+ nativeChild = this.native(child);
73
+ // The SDK maintains parent.c for same-parent moves only. Detach a moved node
74
+ // from the old bookkeeping tree before insertion cancels deferred removal.
75
+ if (nativeChild.parent && nativeChild.parent !== nativeParent)
76
+ tmTransaction.removeNode(nativeChild.parent, nativeChild);
77
+ tmTransaction.insertNode(nativeParent, nativeChild, before && this.native(before));
78
+ }
79
+ remove(parent: SceneNodeRef, child: SceneNodeRef): void {
80
+ const nativeChild = this.native(child);
81
+ tmTransaction.removeNode(this.native(parent), nativeChild);
82
+ const retired = new Set<DomNode>();
83
+ const visit = (node: DomNode) => {
84
+ retired.add(node);
85
+ for (const descendant of node.c ?? []) visit(descendant);
86
+ };
87
+ visit(nativeChild);
88
+ for (const [ref, native] of this.nativeNodes)
89
+ if (retired.has(native)) this.nativeNodes.delete(ref);
90
+ }
91
+ subscribe(node: SceneNodeRef, field: string, listener: SceneFieldListener): () => void {
92
+ const native = this.native(node);
93
+ const property = `on${field.charAt(0).toUpperCase()}${field.slice(1)}`;
94
+ tmTransaction.setProperty(native, property, listener as TmValue);
95
+ return () => {
96
+ tmTransaction.setProperty(native, property, null as unknown as TmValue, listener as TmValue);
97
+ };
98
+ }
99
+ batch(work: () => void): void {
100
+ transactionManager.startTransaction();
101
+ work();
102
+ }
103
+ native(ref: SceneNodeRef): DomNode {
104
+ const node = this.nativeNodes.get(ref);
105
+ if (!node) throw new RokuHostError("STALE_NODE", `Unknown or retired SDK node ${ref.id}`);
106
+ return node;
107
+ }
108
+ private retain(node: DomNode): SceneNodeRef {
109
+ const ref = Object.freeze({ id: ++this.nextId, type: node.t ?? "anchor" });
110
+ this.issuedRefs.add(ref);
111
+ this.nativeNodes.set(ref, node);
112
+ return ref;
113
+ }
114
+ private convert(value: unknown): unknown {
115
+ if (value && typeof value === "object" && this.issuedRefs.has(value))
116
+ return this.native(value as SceneNodeRef);
117
+ if (Array.isArray(value)) return value.map((item) => this.convert(item));
118
+ if (value && typeof value === "object")
119
+ return Object.fromEntries(
120
+ Object.entries(value).map(([key, item]) => [key, this.convert(item)]),
121
+ );
122
+ return value;
123
+ }
124
+ }
@@ -0,0 +1,321 @@
1
+ import type { DomNode, TmValue } from "@roku-sdk/interfaces";
2
+ import { tmTransaction } from "@roku-sdk/solid";
3
+ import { transactionManager } from "@roku-sdk/common/transaction";
4
+ import type { TextEntryPort, TextEntryRequest, TextEntrySession } from "../services/DeviceServices";
5
+ import { RokuHostError } from "./sceneGraph.types";
6
+ import { validateTextEntryRequest, validateTextEntryText } from "../services/textEntryRequest";
7
+
8
+ type Selection = Readonly<{ start: number; end: number }>;
9
+ type Entry = {
10
+ id: number;
11
+ maxLength: number;
12
+ closing: boolean;
13
+ revision: number;
14
+ sequence: number;
15
+ text: string;
16
+ observedText?: string;
17
+ listeners: Set<(text: string) => void>;
18
+ selection?: Selection;
19
+ selectionListeners: Set<(selection: Selection) => void>;
20
+ timer: ReturnType<typeof setTimeout>;
21
+ result(value: string | null): void;
22
+ finish(value: string | null, observed: boolean): void;
23
+ };
24
+
25
+ /** Logical cancellation and observed native dismissal have separate lifetimes. */
26
+ export class SdkTextEntry implements TextEntryPort {
27
+ private sequence = 0;
28
+ private disposed = false;
29
+ private current?: Entry;
30
+ private readonly pending = new Map<number, Entry>();
31
+ private readonly uncertain = new Set<number>();
32
+ private readonly reply = (value: unknown) => {
33
+ if (this.disposed || value === "") return;
34
+ this.set("textEntryReply", "");
35
+ if (typeof value !== "string" || value.length > 65536) return;
36
+ let packet: {
37
+ version?: number;
38
+ id?: number;
39
+ text?: unknown;
40
+ closed?: boolean;
41
+ revision?: number;
42
+ draft?: boolean;
43
+ caret?: boolean;
44
+ prefix?: unknown;
45
+ sequence?: number;
46
+ } | null;
47
+ try {
48
+ packet = JSON.parse(value);
49
+ } catch {
50
+ return;
51
+ }
52
+ if (
53
+ packet?.version !== 2 ||
54
+ !Number.isSafeInteger(packet.id) ||
55
+ packet.id! < 1 ||
56
+ (packet.revision !== undefined &&
57
+ (!Number.isSafeInteger(packet.revision) || packet.revision < 0))
58
+ )
59
+ return;
60
+ const id = packet.id!;
61
+ const entry = this.pending.get(id);
62
+ if (packet.draft !== undefined || packet.caret !== undefined) {
63
+ const isDraft = packet.draft === true && packet.caret === undefined;
64
+ const isCaret = packet.caret === true && packet.draft === undefined;
65
+ if (
66
+ (!isDraft && !isCaret) ||
67
+ !entry ||
68
+ entry !== this.current ||
69
+ entry.closing ||
70
+ packet.revision !== entry.revision ||
71
+ !Number.isSafeInteger(packet.sequence) ||
72
+ packet.sequence! <= entry.sequence ||
73
+ typeof packet.text !== "string" ||
74
+ packet.text.length > 4096
75
+ )
76
+ return;
77
+ const prefix = packet.prefix;
78
+ if (prefix !== undefined || isCaret) {
79
+ if (typeof prefix !== "string" || !packet.text.startsWith(prefix)) return;
80
+ // Native supplies the actual prefix rather than a platform-specific
81
+ // character index. JS length converts that prefix to RN UTF-16 units.
82
+ const last = prefix.charCodeAt(prefix.length - 1);
83
+ const next = packet.text.charCodeAt(prefix.length);
84
+ if (last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) return;
85
+ }
86
+ if (isCaret && packet.text !== entry.text) return;
87
+ entry.sequence = packet.sequence!;
88
+ const text = packet.text.slice(0, entry.maxLength);
89
+ const ownsPublication = () =>
90
+ !entry.closing &&
91
+ this.current === entry &&
92
+ this.pending.has(id) &&
93
+ entry.sequence === packet.sequence &&
94
+ entry.revision === packet.revision;
95
+ if (isDraft && text !== entry.text) {
96
+ entry.text = text;
97
+ entry.observedText = text;
98
+ entry.selection = undefined;
99
+ for (const listener of [...entry.listeners]) {
100
+ if (!ownsPublication()) break;
101
+ if (entry.listeners.has(listener)) this.notify(entry, listener, text);
102
+ }
103
+ }
104
+ if (ownsPublication() && typeof prefix === "string" && packet.text === entry.text) {
105
+ const selection = { start: prefix.length, end: prefix.length };
106
+ const previous = entry.selection;
107
+ entry.selection = selection;
108
+ if (previous?.start === selection.start && previous.end === selection.end) return;
109
+ for (const listener of [...entry.selectionListeners]) {
110
+ if (!ownsPublication()) break;
111
+ if (entry.selectionListeners.has(listener))
112
+ this.notify(entry, listener, { ...selection });
113
+ }
114
+ }
115
+ return;
116
+ }
117
+ if (typeof packet.closed !== "boolean") return;
118
+ // A late acknowledgement may restore transport certainty, but cannot revive
119
+ // an expired session or manufacture a late keyboard event.
120
+ this.uncertain.delete(id);
121
+ if (!entry) return;
122
+ entry.finish(
123
+ packet.closed && (packet.revision ?? 0) === entry.revision && typeof packet.text === "string"
124
+ ? packet.text.slice(0, entry.maxLength)
125
+ : null,
126
+ packet.closed,
127
+ );
128
+ };
129
+ constructor(private readonly node: DomNode) {
130
+ this.set("onTextEntryReply", this.reply as TmValue);
131
+ }
132
+ private set(name: string, value: TmValue, previous?: TmValue) {
133
+ transactionManager.startTransaction();
134
+ tmTransaction.setProperty(this.node, name, value, previous);
135
+ }
136
+ private notify<Value>(entry: Entry, listener: (value: Value) => void, value: Value) {
137
+ try {
138
+ listener(value);
139
+ } catch (error) {
140
+ try {
141
+ this.cancel(entry);
142
+ } catch {
143
+ /* Preserve the subscriber failure; cancellation retains uncertainty. */
144
+ }
145
+ throw error;
146
+ }
147
+ }
148
+ private cancel(entry: Entry) {
149
+ if (!this.pending.has(entry.id) || entry.closing) return;
150
+ entry.closing = true;
151
+ entry.text = "";
152
+ entry.observedText = undefined;
153
+ entry.listeners.clear();
154
+ entry.selection = undefined;
155
+ entry.selectionListeners.clear();
156
+ if (this.current === entry) this.current = undefined;
157
+ clearTimeout(entry.timer);
158
+ entry.result(null);
159
+ entry.timer = setTimeout(() => {
160
+ this.uncertain.add(entry.id);
161
+ entry.finish(null, false);
162
+ // A queued successor cannot be admitted behind an unconfirmed dialog.
163
+ for (const other of [...this.pending.values()]) {
164
+ try {
165
+ this.cancel(other);
166
+ } catch {
167
+ /* closed=false and uncertainty retain the failure */
168
+ }
169
+ }
170
+ }, 10000);
171
+ try {
172
+ this.set("textEntryRequest", JSON.stringify({ version: 2, id: entry.id, close: true }));
173
+ } catch (error) {
174
+ this.uncertain.add(entry.id);
175
+ entry.finish(null, false);
176
+ throw error;
177
+ }
178
+ }
179
+ open(request: TextEntryRequest): TextEntrySession {
180
+ if (this.disposed || this.current || this.uncertain.size || this.pending.size >= 32)
181
+ throw new RokuHostError("C07_TEXT_ENTRY", "Text entry is unavailable or already active");
182
+ validateTextEntryRequest(request);
183
+ const id = ++this.sequence;
184
+ let resolveResult!: (value: string | null) => void,
185
+ resolveClosed!: (observed: boolean) => void,
186
+ settled = false;
187
+ const result = new Promise<string | null>((resolve) => {
188
+ resolveResult = resolve;
189
+ });
190
+ const closed = new Promise<boolean>((resolve) => {
191
+ resolveClosed = resolve;
192
+ });
193
+ const entry: Entry = {
194
+ id,
195
+ maxLength: request.maxLength,
196
+ closing: false,
197
+ revision: 0,
198
+ sequence: 0,
199
+ text: request.text.slice(0, request.maxLength),
200
+ listeners: new Set(),
201
+ selectionListeners: new Set(),
202
+ timer: setTimeout(() => {
203
+ try {
204
+ this.cancel(entry);
205
+ } catch {
206
+ /* closed=false reports the lost acknowledgement */
207
+ }
208
+ }, 600000),
209
+ result(value) {
210
+ if (!settled) {
211
+ settled = true;
212
+ resolveResult(value);
213
+ }
214
+ },
215
+ finish: (value, observed) => {
216
+ if (!this.pending.delete(id)) return;
217
+ clearTimeout(entry.timer);
218
+ entry.text = "";
219
+ entry.observedText = undefined;
220
+ entry.listeners.clear();
221
+ entry.selection = undefined;
222
+ entry.selectionListeners.clear();
223
+ if (this.current === entry) this.current = undefined;
224
+ // Accepted text must reach TextInput before a hide callback can blur it.
225
+ entry.result(value);
226
+ resolveClosed(observed);
227
+ },
228
+ };
229
+ this.pending.set(id, entry);
230
+ this.current = entry;
231
+ try {
232
+ this.set(
233
+ "textEntryRequest",
234
+ JSON.stringify({
235
+ ...request,
236
+ version: 2,
237
+ id,
238
+ revision: 0,
239
+ observeChanges: true,
240
+ observeSelection: true,
241
+ }),
242
+ );
243
+ } catch (error) {
244
+ this.uncertain.add(id);
245
+ entry.finish(null, false);
246
+ throw error;
247
+ }
248
+ return {
249
+ result,
250
+ closed,
251
+ setText: (text) => {
252
+ validateTextEntryText(text);
253
+ if (this.disposed || !this.pending.has(id) || entry.closing) return false;
254
+ text = text.slice(0, entry.maxLength);
255
+ // React commonly echoes an observed draft into its controlled value.
256
+ // An unchanged echo must not invalidate a pending native submission.
257
+ if (text === entry.text && entry.observedText === text) return true;
258
+ entry.text = text;
259
+ entry.observedText = undefined;
260
+ entry.selection = undefined;
261
+ entry.revision++;
262
+ try {
263
+ this.set(
264
+ "textEntryRequest",
265
+ JSON.stringify({
266
+ version: 2,
267
+ id,
268
+ update: true,
269
+ revision: entry.revision,
270
+ text,
271
+ }),
272
+ );
273
+ } catch (error) {
274
+ try {
275
+ this.cancel(entry);
276
+ } catch {
277
+ /* cancellation retains uncertainty */
278
+ }
279
+ throw error;
280
+ }
281
+ return true;
282
+ },
283
+ subscribeText: (listener) => {
284
+ if (this.disposed || !this.pending.has(id) || entry.closing) return () => {};
285
+ entry.listeners.add(listener);
286
+ if (entry.observedText !== undefined) this.notify(entry, listener, entry.observedText);
287
+ return () => entry.listeners.delete(listener);
288
+ },
289
+ subscribeSelection: (listener) => {
290
+ if (this.disposed || !this.pending.has(id) || entry.closing) return () => {};
291
+ entry.selectionListeners.add(listener);
292
+ if (entry.selection !== undefined) this.notify(entry, listener, { ...entry.selection });
293
+ return () => entry.selectionListeners.delete(listener);
294
+ },
295
+ close: () => this.cancel(entry),
296
+ };
297
+ }
298
+ dismiss() {
299
+ if (this.current) this.cancel(this.current);
300
+ }
301
+ dispose() {
302
+ if (this.disposed) return;
303
+ this.disposed = true;
304
+ let failure: unknown;
305
+ for (const entry of [...this.pending.values()]) {
306
+ try {
307
+ this.cancel(entry);
308
+ } catch (error) {
309
+ failure ??= error;
310
+ }
311
+ entry.finish(null, false);
312
+ }
313
+ this.uncertain.clear();
314
+ try {
315
+ this.set("onTextEntryReply", null as unknown as TmValue, this.reply as TmValue);
316
+ } catch (error) {
317
+ failure ??= error;
318
+ }
319
+ if (failure) throw failure;
320
+ }
321
+ }