@solidnative-dev/testing 0.0.0-stage → 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1682 @@
1
+ import { HOST_CAUSAL_OPERATION_ID_MAX_LENGTH, HOST_CONTRACT_VERSION, } from "@solidnative-dev/host-contract";
2
+ import { CORE_COMPONENT_DESCRIPTORS } from "@solidnative-dev/core";
3
+ import { mount, } from "@solidnative-dev/renderer";
4
+ class StagedNodeStore {
5
+ #committed;
6
+ #changes = new Map();
7
+ #removed = new Set();
8
+ constructor(committed) {
9
+ this.#committed = committed;
10
+ }
11
+ has(node) {
12
+ if (this.#changes.has(node))
13
+ return true;
14
+ if (this.#removed.has(node))
15
+ return false;
16
+ return this.#committed.has(node);
17
+ }
18
+ get(node) {
19
+ const changed = this.#changes.get(node);
20
+ if (changed !== undefined)
21
+ return changed;
22
+ if (this.#removed.has(node))
23
+ return undefined;
24
+ const committed = this.#committed.get(node);
25
+ if (committed === undefined)
26
+ return undefined;
27
+ const copy = cloneNode(committed);
28
+ this.#changes.set(node, copy);
29
+ return copy;
30
+ }
31
+ set(node, value) {
32
+ this.#removed.delete(node);
33
+ this.#changes.set(node, value);
34
+ return this;
35
+ }
36
+ delete(node) {
37
+ if (!this.has(node))
38
+ return false;
39
+ this.#changes.delete(node);
40
+ if (this.#committed.has(node))
41
+ this.#removed.add(node);
42
+ return true;
43
+ }
44
+ publish() {
45
+ const deleted = [];
46
+ for (const node of this.#removed) {
47
+ this.#committed.delete(node);
48
+ deleted.push(node);
49
+ }
50
+ for (const [node, value] of this.#changes) {
51
+ this.#committed.set(node, value);
52
+ }
53
+ return deleted;
54
+ }
55
+ }
56
+ const DEFAULT_CAPABILITIES = {
57
+ contractVersion: HOST_CONTRACT_VERSION,
58
+ synchronousMeasurement: true,
59
+ bubblingEvents: true,
60
+ nativeScreens: false,
61
+ uiWorklets: false,
62
+ viewRecycling: false,
63
+ commitMountEvents: true,
64
+ };
65
+ function cloneValue(value) {
66
+ if (Array.isArray(value)) {
67
+ return value.map(cloneValue);
68
+ }
69
+ if (value !== null && typeof value === "object") {
70
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, cloneValue(child)]));
71
+ }
72
+ return value;
73
+ }
74
+ function cloneProps(props) {
75
+ return Object.fromEntries(Object.entries(props).map(([key, value]) => [key, cloneValue(value)]));
76
+ }
77
+ function cloneMutation(mutation) {
78
+ switch (mutation.type) {
79
+ case "create-element":
80
+ return { ...mutation, props: cloneProps(mutation.props) };
81
+ case "update-props":
82
+ return {
83
+ ...mutation,
84
+ props: cloneProps(mutation.props),
85
+ removedProps: [...mutation.removedProps],
86
+ };
87
+ case "update-event-listeners":
88
+ return { ...mutation, events: [...mutation.events] };
89
+ case "command":
90
+ return { ...mutation, args: mutation.args.map(cloneValue) };
91
+ default:
92
+ return { ...mutation };
93
+ }
94
+ }
95
+ function cloneCausalContext(context) {
96
+ if (context.operationId.length === 0 ||
97
+ context.operationId.length > HOST_CAUSAL_OPERATION_ID_MAX_LENGTH ||
98
+ context.operationId.includes("\0")) {
99
+ throw new RangeError(`The causal operation ID must contain 1-${HOST_CAUSAL_OPERATION_ID_MAX_LENGTH} characters without null bytes.`);
100
+ }
101
+ return { operationId: context.operationId };
102
+ }
103
+ function cloneCommit(commit) {
104
+ return {
105
+ ...commit,
106
+ mutations: commit.mutations.map(cloneMutation),
107
+ ...(commit.causalContext === undefined
108
+ ? {}
109
+ : { causalContext: cloneCausalContext(commit.causalContext) }),
110
+ };
111
+ }
112
+ function cloneNode(node) {
113
+ return node.kind === "element"
114
+ ? {
115
+ ...node,
116
+ props: cloneProps(node.props),
117
+ eventListeners: [...node.eventListeners],
118
+ children: [...node.children],
119
+ }
120
+ : { ...node };
121
+ }
122
+ function cloneDescriptor(descriptor) {
123
+ return {
124
+ ...descriptor,
125
+ bubblingEvents: [...descriptor.bubblingEvents],
126
+ directEvents: [...descriptor.directEvents],
127
+ commands: Object.fromEntries(Object.entries(descriptor.commands).map(([name, parameters]) => [
128
+ name,
129
+ [...parameters],
130
+ ])),
131
+ };
132
+ }
133
+ function getNode(surface, node, operation) {
134
+ const value = surface.nodes.get(node);
135
+ if (value === undefined) {
136
+ throw new Error(`Cannot ${operation}: node ${node} does not exist on surface ${surface.id}.`);
137
+ }
138
+ return value;
139
+ }
140
+ function getElement(surface, node, operation) {
141
+ const value = getNode(surface, node, operation);
142
+ if (value.kind !== "element") {
143
+ throw new Error(`Cannot ${operation}: node ${node} is a text node.`);
144
+ }
145
+ return value;
146
+ }
147
+ /**
148
+ * A strict, deterministic implementation of the host contract for renderer tests.
149
+ * Commits are applied to a copy of the surface and become visible atomically.
150
+ */
151
+ export class InMemoryHost {
152
+ platform;
153
+ capabilities;
154
+ #surfaces = new Map();
155
+ #descriptors = new Map();
156
+ #listeners = new Set();
157
+ #lifecycleListeners = new Set();
158
+ #commits = [];
159
+ #measurements = new Map();
160
+ #clock;
161
+ #nextSurface = 1;
162
+ constructor(options = {}) {
163
+ this.#clock = options.clock ?? (() => 0);
164
+ this.platform = options.platform ?? "test";
165
+ this.capabilities = {
166
+ ...DEFAULT_CAPABILITIES,
167
+ ...options.capabilities,
168
+ contractVersion: HOST_CONTRACT_VERSION,
169
+ };
170
+ for (const descriptor of options.descriptors ?? []) {
171
+ if (this.#descriptors.has(descriptor.name)) {
172
+ throw new Error(`Duplicate component descriptor: ${descriptor.name}.`);
173
+ }
174
+ this.#descriptors.set(descriptor.name, cloneDescriptor(descriptor));
175
+ }
176
+ }
177
+ createSurface(options) {
178
+ const id = this.#nextSurface++;
179
+ this.#surfaces.set(id, {
180
+ id,
181
+ name: options.name,
182
+ initialProps: cloneProps(options.initialProps ?? {}),
183
+ nextNode: 1,
184
+ sequence: 0,
185
+ nodes: new Map(),
186
+ });
187
+ return id;
188
+ }
189
+ destroySurface(surface) {
190
+ this.#getSurface(surface);
191
+ this.#surfaces.delete(surface);
192
+ const prefix = `${surface}:`;
193
+ for (const key of this.#measurements.keys()) {
194
+ if (key.startsWith(prefix))
195
+ this.#measurements.delete(key);
196
+ }
197
+ }
198
+ allocateNode(surface) {
199
+ const state = this.#getSurface(surface);
200
+ return state.nextNode++;
201
+ }
202
+ commit(transaction) {
203
+ const causalContext = transaction.causalContext === undefined
204
+ ? undefined
205
+ : cloneCausalContext(transaction.causalContext);
206
+ const commitStartedAt = this.#clock();
207
+ const current = this.#getSurface(transaction.surface);
208
+ if (transaction.sequence <= current.sequence) {
209
+ throw new Error(`Commit sequence ${transaction.sequence} must be greater than ${current.sequence} on surface ${current.id}.`);
210
+ }
211
+ const stagedNodes = new StagedNodeStore(current.nodes);
212
+ const staged = {
213
+ ...current,
214
+ nodes: stagedNodes,
215
+ };
216
+ for (const mutation of transaction.mutations) {
217
+ this.#applyMutation(staged, mutation);
218
+ }
219
+ const deletedNodes = stagedNodes.publish();
220
+ current.sequence = transaction.sequence;
221
+ for (const node of deletedNodes) {
222
+ this.#measurements.delete(this.#measurementKey(current.id, node));
223
+ }
224
+ this.#commits.push(cloneCommit(transaction));
225
+ const producedRevision = !transaction.mutations.some((mutation) => mutation.type === "command");
226
+ if (producedRevision) {
227
+ const mountedAt = this.#clock();
228
+ const mountEvent = {
229
+ type: "commit-mounted",
230
+ surface: current.id,
231
+ sequence: current.sequence,
232
+ hostRevision: current.sequence,
233
+ commitStartedAt,
234
+ mountedAt,
235
+ mountLatency: Math.max(0, mountedAt - commitStartedAt),
236
+ ...(causalContext === undefined ? {} : { causalContext }),
237
+ };
238
+ for (const listener of [...this.#lifecycleListeners]) {
239
+ listener(mountEvent);
240
+ }
241
+ const frameStartedAt = this.#clock();
242
+ const frameEvent = {
243
+ type: "commit-frame",
244
+ surface: current.id,
245
+ sequence: current.sequence,
246
+ hostRevision: current.sequence,
247
+ mountedAt,
248
+ frameStartedAt,
249
+ frameLatency: Math.max(0, frameStartedAt - commitStartedAt),
250
+ mountToFrameLatency: Math.max(0, frameStartedAt - mountedAt),
251
+ ...(causalContext === undefined ? {} : { causalContext }),
252
+ };
253
+ for (const listener of [...this.#lifecycleListeners]) {
254
+ listener(frameEvent);
255
+ }
256
+ }
257
+ return {
258
+ surface: current.id,
259
+ sequence: current.sequence,
260
+ mounted: true,
261
+ ...(producedRevision ? { hostRevision: current.sequence } : {}),
262
+ };
263
+ }
264
+ measure(surface, node, afterSequence) {
265
+ const state = this.#getSurface(surface);
266
+ getNode(state, node, "measure node");
267
+ if (afterSequence !== undefined && state.sequence < afterSequence) {
268
+ throw new Error(`Cannot measure surface ${surface} after sequence ${afterSequence}; latest commit is ${state.sequence}.`);
269
+ }
270
+ const measurement = this.#measurements.get(this.#measurementKey(surface, node)) ??
271
+ {
272
+ x: 0,
273
+ y: 0,
274
+ width: 0,
275
+ height: 0,
276
+ pageX: 0,
277
+ pageY: 0,
278
+ observedSequence: state.sequence,
279
+ };
280
+ if (afterSequence !== undefined &&
281
+ measurement.observedSequence < afterSequence) {
282
+ throw new Error(`Measurement for node ${node} only observes sequence ${measurement.observedSequence}, before requested sequence ${afterSequence}.`);
283
+ }
284
+ return { ...measurement };
285
+ }
286
+ subscribe(listener) {
287
+ this.#listeners.add(listener);
288
+ return () => {
289
+ this.#listeners.delete(listener);
290
+ };
291
+ }
292
+ subscribeLifecycle(listener) {
293
+ this.#lifecycleListeners.add(listener);
294
+ return () => {
295
+ this.#lifecycleListeners.delete(listener);
296
+ };
297
+ }
298
+ getComponentDescriptor(name) {
299
+ const descriptor = this.#descriptors.get(name);
300
+ return descriptor === undefined ? undefined : cloneDescriptor(descriptor);
301
+ }
302
+ get commits() {
303
+ return this.#commits.map(cloneCommit);
304
+ }
305
+ hasSurface(surface) {
306
+ return this.#surfaces.has(surface);
307
+ }
308
+ getSurfaceSnapshot(surface) {
309
+ const state = this.#getSurface(surface);
310
+ return {
311
+ id: state.id,
312
+ name: state.name,
313
+ initialProps: cloneProps(state.initialProps),
314
+ sequence: state.sequence,
315
+ nodes: [...state.nodes.values()]
316
+ .sort((left, right) => left.node - right.node)
317
+ .map((node) => node.kind === "element"
318
+ ? {
319
+ kind: "element",
320
+ node: node.node,
321
+ component: node.component,
322
+ props: cloneProps(node.props),
323
+ eventListeners: [...node.eventListeners],
324
+ parent: node.parent,
325
+ children: [...node.children],
326
+ }
327
+ : { ...node }),
328
+ };
329
+ }
330
+ setMeasurement(surface, node, measurement) {
331
+ const state = this.#getSurface(surface);
332
+ getNode(state, node, "set measurement for node");
333
+ if (measurement.observedSequence !== undefined &&
334
+ measurement.observedSequence > state.sequence) {
335
+ throw new Error(`Measurement observes future sequence ${measurement.observedSequence}; latest commit is ${state.sequence}.`);
336
+ }
337
+ this.#measurements.set(this.#measurementKey(surface, node), {
338
+ ...measurement,
339
+ observedSequence: measurement.observedSequence ?? state.sequence,
340
+ });
341
+ }
342
+ injectEvent(options) {
343
+ const state = this.#getSurface(options.surface);
344
+ getNode(state, options.target, "dispatch event to node");
345
+ const observedSequence = options.observedSequence ?? state.sequence;
346
+ if (observedSequence > state.sequence) {
347
+ throw new Error(`Event observes future sequence ${observedSequence}; latest commit is ${state.sequence}.`);
348
+ }
349
+ const event = {
350
+ surface: options.surface,
351
+ target: options.target,
352
+ observedSequence,
353
+ name: options.name,
354
+ timestamp: options.timestamp ?? 0,
355
+ priority: options.priority ?? "default",
356
+ bubbles: options.bubbles ?? false,
357
+ coalescible: options.coalescible ?? false,
358
+ payload: cloneValue(options.payload ?? null),
359
+ };
360
+ const target = getElement(state, options.target, "dispatch event to node");
361
+ if (!target.eventListeners.includes(options.name)) {
362
+ throw new Error(`Node ${options.target} is not observing event ${options.name}.`);
363
+ }
364
+ for (const listener of [...this.#listeners])
365
+ listener(event);
366
+ return event;
367
+ }
368
+ #getSurface(surface) {
369
+ const state = this.#surfaces.get(surface);
370
+ if (state === undefined) {
371
+ throw new Error(`Surface ${surface} does not exist.`);
372
+ }
373
+ return state;
374
+ }
375
+ #measurementKey(surface, node) {
376
+ return `${surface}:${node}`;
377
+ }
378
+ #applyMutation(surface, mutation) {
379
+ switch (mutation.type) {
380
+ case "create-element": {
381
+ this.#assertNodeCanBeCreated(surface, mutation.node);
382
+ const descriptor = this.#descriptors.get(mutation.component);
383
+ if (descriptor === undefined) {
384
+ throw new Error(`Unknown native component: ${mutation.component}.`);
385
+ }
386
+ surface.nodes.set(mutation.node, {
387
+ kind: "element",
388
+ node: mutation.node,
389
+ component: mutation.component,
390
+ props: cloneProps(mutation.props),
391
+ eventListeners: [],
392
+ parent: null,
393
+ children: [],
394
+ });
395
+ break;
396
+ }
397
+ case "create-text":
398
+ this.#assertNodeCanBeCreated(surface, mutation.node);
399
+ surface.nodes.set(mutation.node, {
400
+ kind: "text",
401
+ node: mutation.node,
402
+ text: mutation.text,
403
+ parent: null,
404
+ });
405
+ break;
406
+ case "update-props": {
407
+ const node = getElement(surface, mutation.node, "update props on node");
408
+ const nextProps = { ...node.props };
409
+ for (const name of mutation.removedProps)
410
+ delete nextProps[name];
411
+ for (const [name, value] of Object.entries(mutation.props)) {
412
+ nextProps[name] = cloneValue(value);
413
+ }
414
+ node.props = nextProps;
415
+ break;
416
+ }
417
+ case "update-text": {
418
+ const node = getNode(surface, mutation.node, "update text on node");
419
+ if (node.kind !== "text") {
420
+ throw new Error(`Cannot update text on node ${mutation.node}: it is an element.`);
421
+ }
422
+ node.text = mutation.text;
423
+ break;
424
+ }
425
+ case "update-event-listeners": {
426
+ const node = getElement(surface, mutation.node, "update event listeners on node");
427
+ const descriptor = this.#descriptors.get(node.component);
428
+ const supported = new Set([
429
+ ...(descriptor?.bubblingEvents ?? []),
430
+ ...(descriptor?.directEvents ?? []),
431
+ ]);
432
+ const seen = new Set();
433
+ let previous = "";
434
+ for (const event of mutation.events) {
435
+ if (event.length === 0) {
436
+ throw new Error("Event listener names cannot be empty.");
437
+ }
438
+ if (seen.has(event)) {
439
+ throw new Error(`Event listener ${event} is duplicated.`);
440
+ }
441
+ if (previous !== "" && event < previous) {
442
+ throw new Error("Event listener names must be sorted.");
443
+ }
444
+ if (!supported.has(event)) {
445
+ throw new Error(`Component ${node.component} does not define event ${event}.`);
446
+ }
447
+ seen.add(event);
448
+ previous = event;
449
+ }
450
+ node.eventListeners = [...mutation.events];
451
+ break;
452
+ }
453
+ case "insert-child":
454
+ this.#insertChild(surface, mutation);
455
+ break;
456
+ case "remove-child": {
457
+ const parent = getElement(surface, mutation.parent, "remove child from node");
458
+ const child = getNode(surface, mutation.child, "remove child node");
459
+ const index = parent.children.indexOf(child.node);
460
+ if (index === -1 || child.parent !== parent.node) {
461
+ throw new Error(`Node ${child.node} is not a child of node ${parent.node}.`);
462
+ }
463
+ parent.children.splice(index, 1);
464
+ child.parent = null;
465
+ break;
466
+ }
467
+ case "delete-node": {
468
+ const node = getNode(surface, mutation.node, "delete node");
469
+ if (node.parent !== null) {
470
+ throw new Error(`Cannot delete node ${node.node} while it is attached to parent ${node.parent}.`);
471
+ }
472
+ if (node.kind === "element" && node.children.length > 0) {
473
+ throw new Error(`Cannot delete node ${node.node} while it still has children.`);
474
+ }
475
+ surface.nodes.delete(node.node);
476
+ break;
477
+ }
478
+ case "command": {
479
+ const node = getElement(surface, mutation.node, "send command to node");
480
+ const descriptor = this.#descriptors.get(node.component);
481
+ const parameters = descriptor?.commands[mutation.command];
482
+ if (parameters === undefined) {
483
+ throw new Error(`Component ${node.component} does not define command ${mutation.command}.`);
484
+ }
485
+ if (parameters.length !== mutation.args.length) {
486
+ throw new Error(`Command ${node.component}.${mutation.command} expects ${parameters.length} arguments, received ${mutation.args.length}.`);
487
+ }
488
+ break;
489
+ }
490
+ }
491
+ }
492
+ #assertNodeCanBeCreated(surface, node) {
493
+ if (node <= 0 || node >= surface.nextNode) {
494
+ throw new Error(`Node ${node} was not allocated on surface ${surface.id}.`);
495
+ }
496
+ if (surface.nodes.has(node)) {
497
+ throw new Error(`Node ${node} already exists on surface ${surface.id}.`);
498
+ }
499
+ }
500
+ #insertChild(surface, mutation) {
501
+ const parent = getElement(surface, mutation.parent, "insert child into node");
502
+ const child = getNode(surface, mutation.child, "insert child node");
503
+ if (parent.node === child.node) {
504
+ throw new Error(`Node ${child.node} cannot be its own parent.`);
505
+ }
506
+ let ancestor = parent;
507
+ while (ancestor !== undefined) {
508
+ if (ancestor.node === child.node) {
509
+ throw new Error(`Cannot insert node ${child.node}: the operation would create a cycle.`);
510
+ }
511
+ ancestor =
512
+ ancestor.parent === null
513
+ ? undefined
514
+ : surface.nodes.get(ancestor.parent);
515
+ }
516
+ if (child.kind === "text") {
517
+ const descriptor = this.#descriptors.get(parent.component);
518
+ if (descriptor?.acceptsRawText !== true) {
519
+ throw new Error(`Component ${parent.component} does not accept raw text children.`);
520
+ }
521
+ }
522
+ let beforeIndex = parent.children.length;
523
+ if (mutation.before !== undefined) {
524
+ beforeIndex = parent.children.indexOf(mutation.before);
525
+ if (beforeIndex === -1) {
526
+ throw new Error(`Before-node ${mutation.before} is not a child of node ${parent.node}.`);
527
+ }
528
+ }
529
+ if (child.parent !== null) {
530
+ const oldParent = getElement(surface, child.parent, "move child from node");
531
+ const oldIndex = oldParent.children.indexOf(child.node);
532
+ if (oldIndex === -1) {
533
+ throw new Error(`Node ${child.node} has inconsistent parent state.`);
534
+ }
535
+ oldParent.children.splice(oldIndex, 1);
536
+ if (oldParent.node === parent.node && oldIndex < beforeIndex) {
537
+ beforeIndex--;
538
+ }
539
+ }
540
+ parent.children.splice(beforeIndex, 0, child.node);
541
+ child.parent = parent.node;
542
+ }
543
+ }
544
+ export class NativeTestQueryError extends Error {
545
+ query;
546
+ matchCount;
547
+ constructor(query, matchCount, available) {
548
+ super(matchCount === 0
549
+ ? `Unable to find a native element by ${query}.${available}`
550
+ : `Found ${String(matchCount)} native elements by ${query}; expected exactly one.${available}`);
551
+ this.name = "NativeTestQueryError";
552
+ this.query = query;
553
+ this.matchCount = matchCount;
554
+ }
555
+ }
556
+ export class NativeTestCommitQueryError extends Error {
557
+ query;
558
+ matchCount;
559
+ constructor(query, matchCount, available) {
560
+ super(matchCount === 0
561
+ ? `Unable to find a native commit matching ${query}.\n\n${available}`
562
+ : `Found ${String(matchCount)} native commits matching ${query}; expected exactly one.\n\n${available}`);
563
+ this.name = "NativeTestCommitQueryError";
564
+ this.query = query;
565
+ this.matchCount = matchCount;
566
+ }
567
+ }
568
+ export class NativeTestMutationQueryError extends Error {
569
+ query;
570
+ matchCount;
571
+ constructor(query, matchCount, available) {
572
+ super(matchCount === 0
573
+ ? `Unable to find a native mutation matching ${query}.\n\n${available}`
574
+ : `Found ${String(matchCount)} native mutations matching ${query}; expected exactly one.\n\n${available}`);
575
+ this.name = "NativeTestMutationQueryError";
576
+ this.query = query;
577
+ this.matchCount = matchCount;
578
+ }
579
+ }
580
+ export class NativeTestWaitTimeoutError extends Error {
581
+ timeout;
582
+ attempts;
583
+ constructor(timeout, attempts, lastError, diagnostics) {
584
+ const lastMessage = lastError instanceof Error
585
+ ? lastError.message.slice(0, 1_000)
586
+ : "The assertion threw a non-Error value.";
587
+ super(`Native test waitFor timed out after ${String(timeout)} ms (${String(attempts)} attempt(s)).\nLast assertion: ${lastMessage}\n\n${diagnostics}`, { cause: lastError });
588
+ this.name = "NativeTestWaitTimeoutError";
589
+ this.timeout = timeout;
590
+ this.attempts = attempts;
591
+ }
592
+ }
593
+ export class NativeTestWaitAbortedError extends Error {
594
+ constructor(reason) {
595
+ super("Native test waitFor was aborted.", { cause: reason });
596
+ this.name = "NativeTestWaitAbortedError";
597
+ }
598
+ }
599
+ class NativeTestAsyncAssertionError extends TypeError {
600
+ constructor() {
601
+ super("Native test waitFor assertions must be synchronous; await asynchronous work before asserting.");
602
+ this.name = "NativeTestAsyncAssertionError";
603
+ }
604
+ }
605
+ function matchesNativeTestText(value, matcher) {
606
+ if (typeof matcher === "string")
607
+ return value === matcher;
608
+ matcher.lastIndex = 0;
609
+ const matched = matcher.test(value);
610
+ matcher.lastIndex = 0;
611
+ return matched;
612
+ }
613
+ function assertNativeTestTextMatcher(matcher) {
614
+ if (typeof matcher !== "string" && !(matcher instanceof RegExp)) {
615
+ throw new TypeError("Native text queries require a string or RegExp.");
616
+ }
617
+ }
618
+ function describeNativeTestMatcher(matcher) {
619
+ return typeof matcher === "string"
620
+ ? JSON.stringify(matcher)
621
+ : String(matcher);
622
+ }
623
+ const NATIVE_TEST_NODE_SUMMARY_LIMIT = 20;
624
+ const NATIVE_TEST_DEBUG_DEFAULT_MAX_DEPTH = 64;
625
+ const NATIVE_TEST_DEBUG_MAX_DEPTH = 256;
626
+ const NATIVE_TEST_DEBUG_DEFAULT_MAX_NODES = 200;
627
+ const NATIVE_TEST_DEBUG_MAX_NODES = 1_000;
628
+ const NATIVE_TEST_DEBUG_TEXT_MAX_CHARACTERS = 160;
629
+ const NATIVE_TEST_DEBUG_PROPS_MAX_CHARACTERS = 2_048;
630
+ const NATIVE_TEST_COMMIT_DEFAULT_MAX_COMMITS = 20;
631
+ const NATIVE_TEST_COMMIT_MAX_COMMITS = 100;
632
+ const NATIVE_TEST_COMMIT_DEFAULT_MAX_MUTATIONS = 200;
633
+ const NATIVE_TEST_COMMIT_MAX_MUTATIONS = 2_000;
634
+ const NATIVE_TEST_COMMIT_VALUE_MAX_CHARACTERS = 2_048;
635
+ const NATIVE_TEST_MATCHER_MAX_ITEMS = 2_000;
636
+ const NATIVE_TEST_MATCHER_MAX_STRING_CHARACTERS = 1_024;
637
+ const NATIVE_TEST_WAIT_DEFAULT_TIMEOUT = 1_000;
638
+ const NATIVE_TEST_WAIT_MAX_TIMEOUT = 60_000;
639
+ const NATIVE_TEST_WAIT_DEFAULT_INTERVAL = 10;
640
+ const NATIVE_TEST_WAIT_MAX_INTERVAL = 1_000;
641
+ const NATIVE_TEST_COMMIT_PRIORITIES = new Set([
642
+ "immediate",
643
+ "user-blocking",
644
+ "normal",
645
+ "background",
646
+ ]);
647
+ const NATIVE_TEST_MUTATION_TYPES = new Set([
648
+ "create-element",
649
+ "create-text",
650
+ "update-props",
651
+ "update-text",
652
+ "update-event-listeners",
653
+ "insert-child",
654
+ "remove-child",
655
+ "delete-node",
656
+ "command",
657
+ ]);
658
+ const NATIVE_TEST_COMMIT_MATCHER_KEYS = new Set([
659
+ "afterSequence",
660
+ "sequence",
661
+ "priority",
662
+ "causalOperationId",
663
+ "mutationTypes",
664
+ ]);
665
+ const NATIVE_TEST_MUTATION_COMMON_KEYS = [
666
+ "type",
667
+ "afterSequence",
668
+ "sequence",
669
+ "priority",
670
+ "causalOperationId",
671
+ ];
672
+ const NATIVE_TEST_MUTATION_SPECIFIC_KEYS = {
673
+ "create-element": ["node", "component"],
674
+ "create-text": ["node"],
675
+ "update-props": ["node", "setProps", "removedProps"],
676
+ "update-text": ["node"],
677
+ "update-event-listeners": ["node", "events"],
678
+ "insert-child": ["parent", "child", "before"],
679
+ "remove-child": ["parent", "child"],
680
+ "delete-node": ["node"],
681
+ command: ["node", "command"],
682
+ };
683
+ function nativeTestMatcherRecord(matcher, description) {
684
+ if (matcher === null ||
685
+ typeof matcher !== "object" ||
686
+ Array.isArray(matcher) ||
687
+ (Object.getPrototypeOf(matcher) !== Object.prototype &&
688
+ Object.getPrototypeOf(matcher) !== null)) {
689
+ throw new TypeError(`Native test ${description} must be a plain object.`);
690
+ }
691
+ return matcher;
692
+ }
693
+ function assertNativeTestMatcherKeys(matcher, allowed, description) {
694
+ const unknown = Object.keys(matcher).filter((key) => !allowed.has(key));
695
+ if (unknown.length > 0) {
696
+ throw new TypeError(`Native test ${description} contains unknown field ${JSON.stringify(unknown[0])}.`);
697
+ }
698
+ }
699
+ function nativeTestMatcherSequence(value, minimum, name) {
700
+ if (value === undefined)
701
+ return undefined;
702
+ if (!Number.isSafeInteger(value) || value < minimum) {
703
+ throw new RangeError(`Native test ${name} must be a safe integer of at least ${String(minimum)}.`);
704
+ }
705
+ return value;
706
+ }
707
+ function nativeTestMatcherPriority(value) {
708
+ if (value === undefined)
709
+ return undefined;
710
+ if (typeof value !== "string" ||
711
+ !NATIVE_TEST_COMMIT_PRIORITIES.has(value)) {
712
+ throw new TypeError("Native test commit priority must be immediate, user-blocking, normal, or background.");
713
+ }
714
+ return value;
715
+ }
716
+ function nativeTestMatcherString(value, name) {
717
+ if (value === undefined)
718
+ return undefined;
719
+ if (typeof value !== "string" ||
720
+ value.length === 0 ||
721
+ value.length > NATIVE_TEST_MATCHER_MAX_STRING_CHARACTERS ||
722
+ value.includes("\0")) {
723
+ throw new TypeError(`Native test ${name} must contain 1-${String(NATIVE_TEST_MATCHER_MAX_STRING_CHARACTERS)} characters without null bytes.`);
724
+ }
725
+ return value;
726
+ }
727
+ function nativeTestMatcherCausalOperationId(value) {
728
+ if (value === undefined)
729
+ return undefined;
730
+ if (typeof value !== "string" ||
731
+ value.length === 0 ||
732
+ value.length > HOST_CAUSAL_OPERATION_ID_MAX_LENGTH ||
733
+ value.includes("\0")) {
734
+ throw new TypeError(`Native test causal operation ID must contain 1-${String(HOST_CAUSAL_OPERATION_ID_MAX_LENGTH)} characters without null bytes.`);
735
+ }
736
+ return value;
737
+ }
738
+ function nativeTestMatcherStringSet(value, name) {
739
+ if (value === undefined)
740
+ return undefined;
741
+ if (!Array.isArray(value) || value.length > NATIVE_TEST_MATCHER_MAX_ITEMS) {
742
+ throw new TypeError(`Native test ${name} must be an array of at most ${String(NATIVE_TEST_MATCHER_MAX_ITEMS)} unique names.`);
743
+ }
744
+ const result = value.map((entry) => {
745
+ const nameValue = nativeTestMatcherString(entry, `${name} entry`);
746
+ if (nameValue === undefined) {
747
+ throw new TypeError(`Native test ${name} entries cannot be undefined.`);
748
+ }
749
+ return nameValue;
750
+ });
751
+ const unique = new Set(result);
752
+ if (unique.size !== result.length) {
753
+ throw new TypeError(`Native test ${name} cannot contain duplicates.`);
754
+ }
755
+ return [...result].sort();
756
+ }
757
+ function normalizeNativeTestCommitFilter(matcher) {
758
+ const afterSequence = nativeTestMatcherSequence(matcher.afterSequence, 0, "afterSequence");
759
+ const sequence = nativeTestMatcherSequence(matcher.sequence, 1, "commit sequence");
760
+ if (afterSequence !== undefined &&
761
+ sequence !== undefined &&
762
+ sequence <= afterSequence) {
763
+ throw new RangeError("Native test commit sequence must be newer than afterSequence.");
764
+ }
765
+ return {
766
+ afterSequence,
767
+ sequence,
768
+ priority: nativeTestMatcherPriority(matcher.priority),
769
+ causalOperationId: nativeTestMatcherCausalOperationId(matcher.causalOperationId),
770
+ };
771
+ }
772
+ function normalizeNativeTestCommitMatcher(matcher) {
773
+ const record = nativeTestMatcherRecord(matcher, "commit matcher");
774
+ assertNativeTestMatcherKeys(record, NATIVE_TEST_COMMIT_MATCHER_KEYS, "commit matcher");
775
+ let mutationTypes;
776
+ if (record.mutationTypes !== undefined) {
777
+ if (!Array.isArray(record.mutationTypes) ||
778
+ record.mutationTypes.length > NATIVE_TEST_MATCHER_MAX_ITEMS) {
779
+ throw new TypeError(`Native test commit mutationTypes must be an array of at most ${String(NATIVE_TEST_MATCHER_MAX_ITEMS)} mutation kinds.`);
780
+ }
781
+ mutationTypes = record.mutationTypes.map((type) => {
782
+ if (typeof type !== "string" ||
783
+ !NATIVE_TEST_MUTATION_TYPES.has(type)) {
784
+ throw new TypeError(`Native test commit mutationTypes contains invalid kind ${JSON.stringify(type)}.`);
785
+ }
786
+ return type;
787
+ });
788
+ }
789
+ return { ...normalizeNativeTestCommitFilter(record), mutationTypes };
790
+ }
791
+ function nativeTestMatcherNode(value, host, surface, name) {
792
+ if (value === undefined)
793
+ return undefined;
794
+ if (typeof value === "number") {
795
+ if (!Number.isSafeInteger(value) || value < 1) {
796
+ throw new RangeError(`Native test mutation ${name} must be a positive safe integer node handle.`);
797
+ }
798
+ return value;
799
+ }
800
+ if (value === null || typeof value !== "object") {
801
+ throw new TypeError(`Native test mutation ${name} must be a node handle or NativeTestElement.`);
802
+ }
803
+ const element = value;
804
+ if (element.host !== host || element.surface !== surface) {
805
+ throw new Error(`Native test mutation ${name} belongs to another render; expected the current host and surface ${String(surface)}.`);
806
+ }
807
+ if (!Number.isSafeInteger(element.node) || (element.node ?? 0) < 1) {
808
+ throw new TypeError(`Native test mutation ${name} contains an invalid NativeTestElement node handle.`);
809
+ }
810
+ return element.node;
811
+ }
812
+ function normalizeNativeTestMutationMatcher(matcher, host, surface) {
813
+ const record = nativeTestMatcherRecord(matcher, "mutation matcher");
814
+ if (typeof record.type !== "string" ||
815
+ !NATIVE_TEST_MUTATION_TYPES.has(record.type)) {
816
+ throw new TypeError(`Native test mutation matcher requires a valid type; received ${JSON.stringify(record.type)}.`);
817
+ }
818
+ const type = record.type;
819
+ assertNativeTestMatcherKeys(record, new Set([
820
+ ...NATIVE_TEST_MUTATION_COMMON_KEYS,
821
+ ...NATIVE_TEST_MUTATION_SPECIFIC_KEYS[type],
822
+ ]), `${type} mutation matcher`);
823
+ const node = nativeTestMatcherNode(record.node, host, surface, "node");
824
+ const parent = nativeTestMatcherNode(record.parent, host, surface, "parent");
825
+ const child = nativeTestMatcherNode(record.child, host, surface, "child");
826
+ const matchesBefore = Object.prototype.hasOwnProperty.call(record, "before");
827
+ const before = record.before === null
828
+ ? null
829
+ : nativeTestMatcherNode(record.before, host, surface, "before");
830
+ return {
831
+ commit: normalizeNativeTestCommitFilter(record),
832
+ type,
833
+ node,
834
+ component: nativeTestMatcherString(record.component, "component name"),
835
+ command: nativeTestMatcherString(record.command, "command name"),
836
+ parent,
837
+ child,
838
+ matchesBefore,
839
+ before,
840
+ setProps: nativeTestMatcherStringSet(record.setProps, "setProps"),
841
+ removedProps: nativeTestMatcherStringSet(record.removedProps, "removedProps"),
842
+ events: nativeTestMatcherStringSet(record.events, "events"),
843
+ };
844
+ }
845
+ function matchesNativeTestCommitFilter(commit, matcher) {
846
+ return ((matcher.afterSequence === undefined ||
847
+ commit.sequence > matcher.afterSequence) &&
848
+ (matcher.sequence === undefined || commit.sequence === matcher.sequence) &&
849
+ (matcher.priority === undefined || commit.priority === matcher.priority) &&
850
+ (matcher.causalOperationId === undefined ||
851
+ commit.causalContext?.operationId === matcher.causalOperationId));
852
+ }
853
+ function matchesNativeTestStringArray(actual, expected) {
854
+ if (expected === undefined)
855
+ return true;
856
+ const sorted = [...actual].sort();
857
+ return (sorted.length === expected.length &&
858
+ sorted.every((value, index) => value === expected[index]));
859
+ }
860
+ function matchesNativeTestCommit(commit, matcher) {
861
+ return (matchesNativeTestCommitFilter(commit, matcher) &&
862
+ (matcher.mutationTypes === undefined ||
863
+ (commit.mutations.length === matcher.mutationTypes.length &&
864
+ commit.mutations.every((mutation, index) => mutation.type === matcher.mutationTypes?.[index]))));
865
+ }
866
+ function matchesNativeTestMutation(mutation, matcher) {
867
+ if (mutation.type !== matcher.type)
868
+ return false;
869
+ switch (mutation.type) {
870
+ case "create-element":
871
+ return ((matcher.node === undefined || mutation.node === matcher.node) &&
872
+ (matcher.component === undefined ||
873
+ mutation.component === matcher.component));
874
+ case "create-text":
875
+ case "update-text":
876
+ case "delete-node":
877
+ return matcher.node === undefined || mutation.node === matcher.node;
878
+ case "update-props":
879
+ return ((matcher.node === undefined || mutation.node === matcher.node) &&
880
+ matchesNativeTestStringArray(Object.keys(mutation.props), matcher.setProps) &&
881
+ matchesNativeTestStringArray(mutation.removedProps, matcher.removedProps));
882
+ case "update-event-listeners":
883
+ return ((matcher.node === undefined || mutation.node === matcher.node) &&
884
+ matchesNativeTestStringArray(mutation.events, matcher.events));
885
+ case "insert-child":
886
+ return ((matcher.parent === undefined || mutation.parent === matcher.parent) &&
887
+ (matcher.child === undefined || mutation.child === matcher.child) &&
888
+ (!matcher.matchesBefore ||
889
+ (matcher.before === null
890
+ ? mutation.before === undefined
891
+ : mutation.before === matcher.before)));
892
+ case "remove-child":
893
+ return ((matcher.parent === undefined || mutation.parent === matcher.parent) &&
894
+ (matcher.child === undefined || mutation.child === matcher.child));
895
+ case "command":
896
+ return ((matcher.node === undefined || mutation.node === matcher.node) &&
897
+ (matcher.command === undefined || mutation.command === matcher.command));
898
+ }
899
+ }
900
+ function describeNativeTestCommitMatcher(matcher) {
901
+ const parts = [];
902
+ if (matcher.afterSequence !== undefined) {
903
+ parts.push(`after sequence ${String(matcher.afterSequence)}`);
904
+ }
905
+ if (matcher.sequence !== undefined) {
906
+ parts.push(`sequence ${String(matcher.sequence)}`);
907
+ }
908
+ if (matcher.priority !== undefined) {
909
+ parts.push(`priority ${JSON.stringify(matcher.priority)}`);
910
+ }
911
+ if (matcher.causalOperationId !== undefined) {
912
+ parts.push(`cause ${clippedNativeTestDebugValue(matcher.causalOperationId, HOST_CAUSAL_OPERATION_ID_MAX_LENGTH)}`);
913
+ }
914
+ if (matcher.mutationTypes !== undefined) {
915
+ parts.push(`exact mutations ${clippedNativeTestDebugValue(matcher.mutationTypes, NATIVE_TEST_COMMIT_VALUE_MAX_CHARACTERS)}`);
916
+ }
917
+ return parts.length === 0 ? "all render commits" : parts.join(", ");
918
+ }
919
+ function describeNativeTestMutationMatcher(matcher) {
920
+ const parts = [JSON.stringify(matcher.type)];
921
+ if (matcher.node !== undefined)
922
+ parts.push(`node ${String(matcher.node)}`);
923
+ if (matcher.component !== undefined) {
924
+ parts.push(`component ${JSON.stringify(matcher.component)}`);
925
+ }
926
+ if (matcher.command !== undefined) {
927
+ parts.push(`command ${JSON.stringify(matcher.command)}`);
928
+ }
929
+ if (matcher.parent !== undefined) {
930
+ parts.push(`parent ${String(matcher.parent)}`);
931
+ }
932
+ if (matcher.child !== undefined)
933
+ parts.push(`child ${String(matcher.child)}`);
934
+ if (matcher.matchesBefore) {
935
+ parts.push(matcher.before === null
936
+ ? "appended without before"
937
+ : `before ${String(matcher.before)}`);
938
+ }
939
+ for (const [name, values] of [
940
+ ["setProps", matcher.setProps],
941
+ ["removedProps", matcher.removedProps],
942
+ ["events", matcher.events],
943
+ ]) {
944
+ if (values !== undefined) {
945
+ parts.push(`${name} ${clippedNativeTestDebugValue(values, NATIVE_TEST_COMMIT_VALUE_MAX_CHARACTERS)}`);
946
+ }
947
+ }
948
+ const commit = describeNativeTestCommitMatcher({
949
+ ...matcher.commit,
950
+ mutationTypes: undefined,
951
+ });
952
+ if (commit !== "all render commits")
953
+ parts.push(commit);
954
+ return parts.join(", ");
955
+ }
956
+ function nativeTestLimit(value, fallback, maximum, description) {
957
+ const candidate = value ?? fallback;
958
+ if (!Number.isSafeInteger(candidate) ||
959
+ candidate < 1 ||
960
+ candidate > maximum) {
961
+ throw new RangeError(`Native test ${description} must be an integer from 1 through ${String(maximum)}.`);
962
+ }
963
+ return candidate;
964
+ }
965
+ function nativeTestWaitLimit(value, fallback, maximum, name) {
966
+ const candidate = value ?? fallback;
967
+ if (!Number.isSafeInteger(candidate) ||
968
+ candidate < 1 ||
969
+ candidate > maximum) {
970
+ throw new RangeError(`Native test waitFor ${name} must be an integer from 1 through ${String(maximum)} milliseconds.`);
971
+ }
972
+ return candidate;
973
+ }
974
+ function assertNativeTestWaitSignal(signal) {
975
+ if (signal !== undefined &&
976
+ (signal === null ||
977
+ typeof signal !== "object" ||
978
+ typeof signal.aborted !== "boolean" ||
979
+ typeof signal.addEventListener !== "function" ||
980
+ typeof signal.removeEventListener !== "function")) {
981
+ throw new TypeError("Native test waitFor signal must be an AbortSignal.");
982
+ }
983
+ }
984
+ function assertNativeTestWaitActive(signal) {
985
+ if (signal?.aborted === true) {
986
+ throw new NativeTestWaitAbortedError(signal.reason);
987
+ }
988
+ }
989
+ function isNativeTestPromiseLike(value) {
990
+ return (value !== null &&
991
+ (typeof value === "object" || typeof value === "function") &&
992
+ typeof value.then === "function");
993
+ }
994
+ async function nativeTestWaitDelay(milliseconds, signal) {
995
+ assertNativeTestWaitActive(signal);
996
+ await new Promise((resolve, reject) => {
997
+ const timer = setTimeout(finish, milliseconds);
998
+ function finish() {
999
+ signal?.removeEventListener("abort", abort);
1000
+ resolve();
1001
+ }
1002
+ function abort() {
1003
+ clearTimeout(timer);
1004
+ signal?.removeEventListener("abort", abort);
1005
+ reject(new NativeTestWaitAbortedError(signal?.reason));
1006
+ }
1007
+ signal?.addEventListener("abort", abort, { once: true });
1008
+ });
1009
+ }
1010
+ function clippedNativeTestDebugValue(value, maximum) {
1011
+ const serialized = JSON.stringify(value, (_key, nested) => nested !== null && typeof nested === "object" && !Array.isArray(nested)
1012
+ ? Object.fromEntries(Object.entries(nested).sort(([left], [right]) => left.localeCompare(right)))
1013
+ : nested);
1014
+ return serialized.length <= maximum
1015
+ ? serialized
1016
+ : `${serialized.slice(0, maximum)}…`;
1017
+ }
1018
+ /** Formats one trusted in-memory host snapshot without writing to the console. */
1019
+ export function formatNativeTestTree(snapshot, options = {}) {
1020
+ const includeProps = options.includeProps ?? false;
1021
+ if (typeof includeProps !== "boolean") {
1022
+ throw new TypeError("Native test debug includeProps must be a boolean.");
1023
+ }
1024
+ const maxDepth = nativeTestLimit(options.maxDepth, NATIVE_TEST_DEBUG_DEFAULT_MAX_DEPTH, NATIVE_TEST_DEBUG_MAX_DEPTH, "debug maxDepth");
1025
+ const maxNodes = nativeTestLimit(options.maxNodes, NATIVE_TEST_DEBUG_DEFAULT_MAX_NODES, NATIVE_TEST_DEBUG_MAX_NODES, "debug maxNodes");
1026
+ const nodes = new Map(snapshot.nodes.map((node) => [node.node, node]));
1027
+ const roots = snapshot.nodes.filter((node) => node.parent === null);
1028
+ const stack = roots
1029
+ .slice()
1030
+ .reverse()
1031
+ .map((node) => ({ depth: 0, node }));
1032
+ const lines = [
1033
+ `Native surface ${JSON.stringify(snapshot.name)} (id=${String(snapshot.id)}, sequence=${String(snapshot.sequence)})`,
1034
+ ];
1035
+ const visited = new Set();
1036
+ let renderedNodes = 0;
1037
+ while (stack.length > 0 && renderedNodes < maxNodes) {
1038
+ const current = stack.pop();
1039
+ if (visited.has(current.node.node))
1040
+ continue;
1041
+ visited.add(current.node.node);
1042
+ renderedNodes += 1;
1043
+ const indentation = " ".repeat(current.depth);
1044
+ if (current.node.kind === "text") {
1045
+ lines.push(`${indentation}#text node=${String(current.node.node)} ${clippedNativeTestDebugValue(current.node.text, NATIVE_TEST_DEBUG_TEXT_MAX_CHARACTERS)}`);
1046
+ continue;
1047
+ }
1048
+ const attributes = [`node=${String(current.node.node)}`];
1049
+ for (const [name, value] of [
1050
+ ["role", current.node.props.accessibilityRole],
1051
+ ["label", current.node.props.accessibilityLabel],
1052
+ ["testID", current.node.props.testID],
1053
+ ]) {
1054
+ if (typeof value === "string") {
1055
+ attributes.push(`${name}=${clippedNativeTestDebugValue(value, NATIVE_TEST_DEBUG_TEXT_MAX_CHARACTERS)}`);
1056
+ }
1057
+ }
1058
+ if (current.node.eventListeners.length > 0) {
1059
+ attributes.push(`events=${JSON.stringify([...current.node.eventListeners].sort())}`);
1060
+ }
1061
+ if (includeProps) {
1062
+ attributes.push(`props=${clippedNativeTestDebugValue(current.node.props, NATIVE_TEST_DEBUG_PROPS_MAX_CHARACTERS)}`);
1063
+ }
1064
+ lines.push(`${indentation}<${current.node.component} ${attributes.join(" ")}>`);
1065
+ if (current.node.children.length === 0)
1066
+ continue;
1067
+ if (current.depth >= maxDepth) {
1068
+ lines.push(`${indentation} … depth limit`);
1069
+ continue;
1070
+ }
1071
+ for (const childHandle of current.node.children.slice().reverse()) {
1072
+ const child = nodes.get(childHandle);
1073
+ if (child === undefined) {
1074
+ lines.push(`${indentation} <missing node=${String(childHandle)}>`);
1075
+ }
1076
+ else {
1077
+ stack.push({ depth: current.depth + 1, node: child });
1078
+ }
1079
+ }
1080
+ }
1081
+ const omitted = snapshot.nodes.length - visited.size;
1082
+ if (omitted > 0)
1083
+ lines.push(`… ${String(omitted)} node(s) omitted`);
1084
+ if (snapshot.nodes.length === 0)
1085
+ lines.push(" <empty>");
1086
+ return lines.join("\n");
1087
+ }
1088
+ function formatNativeTestMutation(mutation, includeValues) {
1089
+ switch (mutation.type) {
1090
+ case "create-element":
1091
+ return `create-element node=${String(mutation.node)} component=${clippedNativeTestDebugValue(mutation.component, NATIVE_TEST_DEBUG_TEXT_MAX_CHARACTERS)}${includeValues ? ` props=${clippedNativeTestDebugValue(mutation.props, NATIVE_TEST_COMMIT_VALUE_MAX_CHARACTERS)}` : ""}`;
1092
+ case "create-text":
1093
+ return `create-text node=${String(mutation.node)}${includeValues ? ` text=${clippedNativeTestDebugValue(mutation.text, NATIVE_TEST_DEBUG_TEXT_MAX_CHARACTERS)}` : ""}`;
1094
+ case "update-props": {
1095
+ const set = Object.keys(mutation.props).sort();
1096
+ const removed = [...mutation.removedProps].sort();
1097
+ return `update-props node=${String(mutation.node)} set=${clippedNativeTestDebugValue(set, NATIVE_TEST_COMMIT_VALUE_MAX_CHARACTERS)} removed=${clippedNativeTestDebugValue(removed, NATIVE_TEST_COMMIT_VALUE_MAX_CHARACTERS)}${includeValues ? ` props=${clippedNativeTestDebugValue(mutation.props, NATIVE_TEST_COMMIT_VALUE_MAX_CHARACTERS)}` : ""}`;
1098
+ }
1099
+ case "update-text":
1100
+ return `update-text node=${String(mutation.node)}${includeValues ? ` text=${clippedNativeTestDebugValue(mutation.text, NATIVE_TEST_DEBUG_TEXT_MAX_CHARACTERS)}` : ""}`;
1101
+ case "update-event-listeners":
1102
+ return `update-event-listeners node=${String(mutation.node)} events=${clippedNativeTestDebugValue([...mutation.events].sort(), NATIVE_TEST_COMMIT_VALUE_MAX_CHARACTERS)}`;
1103
+ case "insert-child":
1104
+ return `insert-child parent=${String(mutation.parent)} child=${String(mutation.child)}${mutation.before === undefined ? "" : ` before=${String(mutation.before)}`}`;
1105
+ case "remove-child":
1106
+ return `remove-child parent=${String(mutation.parent)} child=${String(mutation.child)}`;
1107
+ case "delete-node":
1108
+ return `delete-node node=${String(mutation.node)}`;
1109
+ case "command":
1110
+ return `command node=${String(mutation.node)} name=${clippedNativeTestDebugValue(mutation.command, NATIVE_TEST_DEBUG_TEXT_MAX_CHARACTERS)}${includeValues ? ` args=${clippedNativeTestDebugValue(mutation.args, NATIVE_TEST_COMMIT_VALUE_MAX_CHARACTERS)}` : ""}`;
1111
+ }
1112
+ }
1113
+ /** Formats trusted, render-scoped commits without writing to the console. */
1114
+ export function formatNativeTestCommits(commits, options = {}) {
1115
+ const includeValues = options.includeValues ?? false;
1116
+ if (typeof includeValues !== "boolean") {
1117
+ throw new TypeError("Native test commit debug includeValues must be a boolean.");
1118
+ }
1119
+ const maxCommits = nativeTestLimit(options.maxCommits, NATIVE_TEST_COMMIT_DEFAULT_MAX_COMMITS, NATIVE_TEST_COMMIT_MAX_COMMITS, "commit debug maxCommits");
1120
+ const maxMutations = nativeTestLimit(options.maxMutations, NATIVE_TEST_COMMIT_DEFAULT_MAX_MUTATIONS, NATIVE_TEST_COMMIT_MAX_MUTATIONS, "commit debug maxMutations");
1121
+ const selected = commits.slice(-maxCommits);
1122
+ const lines = [
1123
+ `Native commits (showing ${String(selected.length)} of ${String(commits.length)})`,
1124
+ ];
1125
+ const omittedCommits = commits.length - selected.length;
1126
+ if (omittedCommits > 0) {
1127
+ lines.push(`… ${String(omittedCommits)} earlier commit(s) omitted`);
1128
+ }
1129
+ let mutationsToOmit = Math.max(0, selected.reduce((total, commit) => total + commit.mutations.length, 0) -
1130
+ maxMutations);
1131
+ for (const commit of selected) {
1132
+ lines.push(`commit surface=${String(commit.surface)} sequence=${String(commit.sequence)} priority=${commit.priority} mutations=${String(commit.mutations.length)}${commit.causalContext === undefined ? "" : ` cause=${clippedNativeTestDebugValue(commit.causalContext.operationId, NATIVE_TEST_DEBUG_TEXT_MAX_CHARACTERS)}`}`);
1133
+ const omittedMutations = Math.min(mutationsToOmit, commit.mutations.length);
1134
+ mutationsToOmit -= omittedMutations;
1135
+ if (omittedMutations > 0) {
1136
+ lines.push(` … ${String(omittedMutations)} earlier mutation(s) omitted`);
1137
+ }
1138
+ const visibleMutations = commit.mutations.slice(omittedMutations);
1139
+ for (const mutation of visibleMutations) {
1140
+ lines.push(` ${formatNativeTestMutation(mutation, includeValues)}`);
1141
+ }
1142
+ }
1143
+ if (commits.length === 0)
1144
+ lines.push(" <empty>");
1145
+ return lines.join("\n");
1146
+ }
1147
+ function nativeTestElements(host, snapshot) {
1148
+ const nodes = new Map(snapshot.nodes.map((node) => [node.node, node]));
1149
+ const textContent = (node) => node.kind === "text"
1150
+ ? node.text
1151
+ : node.children
1152
+ .map((child) => nodes.get(child))
1153
+ .filter((child) => child !== undefined)
1154
+ .map(textContent)
1155
+ .join("");
1156
+ return snapshot.nodes.flatMap((node) => node.kind === "text"
1157
+ ? []
1158
+ : [
1159
+ {
1160
+ host,
1161
+ surface: snapshot.id,
1162
+ node: node.node,
1163
+ component: node.component,
1164
+ props: node.props,
1165
+ eventListeners: node.eventListeners,
1166
+ parent: node.parent,
1167
+ children: node.children,
1168
+ textContent: textContent(node),
1169
+ },
1170
+ ]);
1171
+ }
1172
+ function nativeTestAvailableSummary(elements) {
1173
+ if (elements.length === 0)
1174
+ return " No native elements are mounted.";
1175
+ const summary = elements
1176
+ .slice(0, NATIVE_TEST_NODE_SUMMARY_LIMIT)
1177
+ .map((element) => {
1178
+ const role = element.props.accessibilityRole;
1179
+ const label = element.props.accessibilityLabel;
1180
+ const testId = element.props.testID;
1181
+ return `<${element.component} node=${String(element.node)}${typeof role === "string" ? ` role=${JSON.stringify(role)}` : ""}${typeof label === "string" ? ` label=${JSON.stringify(label)}` : ""}${typeof testId === "string" ? ` testID=${JSON.stringify(testId)}` : ""}${element.textContent.length === 0 ? "" : ` text=${JSON.stringify(element.textContent.slice(0, 120))}`}>`;
1182
+ })
1183
+ .join(", ");
1184
+ return ` Available: ${summary}${elements.length > NATIVE_TEST_NODE_SUMMARY_LIMIT ? ", …" : ""}.`;
1185
+ }
1186
+ function describeNativeTestRoleQuery(role, options) {
1187
+ return options.name === undefined
1188
+ ? `role ${JSON.stringify(role)}`
1189
+ : `role ${JSON.stringify(role)} and accessible name ${describeNativeTestMatcher(options.name)}`;
1190
+ }
1191
+ class NativeTestRenderImplementation {
1192
+ application;
1193
+ host;
1194
+ surfaceId;
1195
+ #commitOffset;
1196
+ #disposal;
1197
+ #disposed = false;
1198
+ constructor(application, host, commitOffset) {
1199
+ this.application = application;
1200
+ this.host = host;
1201
+ this.surfaceId = application.root.surfaceId;
1202
+ this.#commitOffset = commitOffset;
1203
+ }
1204
+ get commits() {
1205
+ return this.host.commits
1206
+ .slice(this.#commitOffset)
1207
+ .filter((commit) => commit.surface === this.surfaceId);
1208
+ }
1209
+ get disposed() {
1210
+ return this.#disposed;
1211
+ }
1212
+ snapshot() {
1213
+ if (this.#disposed) {
1214
+ throw new Error("Cannot inspect a disposed native test render.");
1215
+ }
1216
+ return this.host.getSurfaceSnapshot(this.surfaceId);
1217
+ }
1218
+ debug(options = {}) {
1219
+ return formatNativeTestTree(this.snapshot(), options);
1220
+ }
1221
+ debugCommits(options = {}) {
1222
+ if (this.#disposed) {
1223
+ throw new Error("Cannot inspect commits for a disposed native test render.");
1224
+ }
1225
+ return formatNativeTestCommits(this.commits, options);
1226
+ }
1227
+ commitCheckpoint() {
1228
+ this.#assertCommitInspection();
1229
+ return this.commits.at(-1)?.sequence ?? 0;
1230
+ }
1231
+ queryAllCommits(matcher = {}) {
1232
+ this.#assertCommitInspection();
1233
+ const normalized = normalizeNativeTestCommitMatcher(matcher);
1234
+ return this.commits.filter((commit) => matchesNativeTestCommit(commit, normalized));
1235
+ }
1236
+ queryCommit(matcher = {}) {
1237
+ const normalized = normalizeNativeTestCommitMatcher(matcher);
1238
+ return this.#optionalCommit(this.queryAllCommits(matcher), describeNativeTestCommitMatcher(normalized));
1239
+ }
1240
+ getCommit(matcher = {}) {
1241
+ const normalized = normalizeNativeTestCommitMatcher(matcher);
1242
+ return this.#oneCommit(this.queryAllCommits(matcher), describeNativeTestCommitMatcher(normalized));
1243
+ }
1244
+ queryAllMutations(matcher) {
1245
+ this.#assertCommitInspection();
1246
+ const normalized = normalizeNativeTestMutationMatcher(matcher, this.host, this.surfaceId);
1247
+ const matches = [];
1248
+ for (const commit of this.commits) {
1249
+ if (!matchesNativeTestCommitFilter(commit, normalized.commit))
1250
+ continue;
1251
+ commit.mutations.forEach((mutation, index) => {
1252
+ if (matchesNativeTestMutation(mutation, normalized)) {
1253
+ matches.push({ commit, mutation, index });
1254
+ }
1255
+ });
1256
+ }
1257
+ return matches;
1258
+ }
1259
+ queryMutation(matcher) {
1260
+ const normalized = normalizeNativeTestMutationMatcher(matcher, this.host, this.surfaceId);
1261
+ return this.#optionalMutation(this.queryAllMutations(matcher), describeNativeTestMutationMatcher(normalized));
1262
+ }
1263
+ getMutation(matcher) {
1264
+ const normalized = normalizeNativeTestMutationMatcher(matcher, this.host, this.surfaceId);
1265
+ return this.#oneMutation(this.queryAllMutations(matcher), describeNativeTestMutationMatcher(normalized));
1266
+ }
1267
+ async flush() {
1268
+ if (this.#disposed) {
1269
+ throw new Error("Cannot flush a disposed native test render.");
1270
+ }
1271
+ return await this.application.root.flush();
1272
+ }
1273
+ async act(callback) {
1274
+ if (typeof callback !== "function") {
1275
+ throw new TypeError("Native test act requires a callback.");
1276
+ }
1277
+ if (this.#disposed) {
1278
+ throw new Error("Cannot act on a disposed native test render.");
1279
+ }
1280
+ const result = await callback();
1281
+ await Promise.resolve();
1282
+ await this.flush();
1283
+ return result;
1284
+ }
1285
+ async waitFor(assertion, options = {}) {
1286
+ if (typeof assertion !== "function") {
1287
+ throw new TypeError("Native test waitFor requires an assertion callback.");
1288
+ }
1289
+ if (this.#disposed) {
1290
+ throw new Error("Cannot wait on a disposed native test render.");
1291
+ }
1292
+ const timeout = nativeTestWaitLimit(options.timeout, NATIVE_TEST_WAIT_DEFAULT_TIMEOUT, NATIVE_TEST_WAIT_MAX_TIMEOUT, "timeout");
1293
+ const interval = nativeTestWaitLimit(options.interval, NATIVE_TEST_WAIT_DEFAULT_INTERVAL, NATIVE_TEST_WAIT_MAX_INTERVAL, "interval");
1294
+ assertNativeTestWaitSignal(options.signal);
1295
+ const startedAt = Date.now();
1296
+ let attempts = 0;
1297
+ let lastError;
1298
+ for (;;) {
1299
+ assertNativeTestWaitActive(options.signal);
1300
+ await Promise.resolve();
1301
+ await this.flush();
1302
+ attempts += 1;
1303
+ try {
1304
+ const result = assertion();
1305
+ if (isNativeTestPromiseLike(result)) {
1306
+ void Promise.resolve(result).catch(() => undefined);
1307
+ throw new NativeTestAsyncAssertionError();
1308
+ }
1309
+ return result;
1310
+ }
1311
+ catch (error) {
1312
+ if (error instanceof NativeTestAsyncAssertionError)
1313
+ throw error;
1314
+ lastError = error;
1315
+ }
1316
+ const elapsed = Date.now() - startedAt;
1317
+ if (elapsed >= timeout) {
1318
+ throw new NativeTestWaitTimeoutError(timeout, attempts, lastError, `${this.debug({ maxDepth: 16, maxNodes: 50 })}\n\n${this.debugCommits({ maxCommits: 3, maxMutations: 20 })}`);
1319
+ }
1320
+ await nativeTestWaitDelay(Math.min(interval, Math.max(1, timeout - elapsed)), options.signal);
1321
+ }
1322
+ }
1323
+ queryAllByComponent(component) {
1324
+ if (typeof component !== "string" || component.length === 0) {
1325
+ throw new TypeError("Native component queries require a non-empty name.");
1326
+ }
1327
+ return this.#elements().filter((element) => element.component === component);
1328
+ }
1329
+ queryByComponent(component) {
1330
+ return this.#optionalOne(this.queryAllByComponent(component), `component ${JSON.stringify(component)}`);
1331
+ }
1332
+ getByComponent(component) {
1333
+ return this.#one(this.queryAllByComponent(component), `component ${JSON.stringify(component)}`);
1334
+ }
1335
+ async findByComponent(component, options = {}) {
1336
+ this.queryAllByComponent(component);
1337
+ return await this.waitFor(() => this.getByComponent(component), options);
1338
+ }
1339
+ queryAllByText(matcher) {
1340
+ assertNativeTestTextMatcher(matcher);
1341
+ return this.#elements().filter((element) => {
1342
+ const descriptor = this.host.getComponentDescriptor(element.component);
1343
+ return (descriptor?.acceptsRawText === true &&
1344
+ matchesNativeTestText(element.textContent, matcher));
1345
+ });
1346
+ }
1347
+ queryByText(matcher) {
1348
+ return this.#optionalOne(this.queryAllByText(matcher), `text ${describeNativeTestMatcher(matcher)}`);
1349
+ }
1350
+ getByText(matcher) {
1351
+ return this.#one(this.queryAllByText(matcher), `text ${describeNativeTestMatcher(matcher)}`);
1352
+ }
1353
+ async findByText(matcher, options = {}) {
1354
+ this.queryAllByText(matcher);
1355
+ return await this.waitFor(() => this.getByText(matcher), options);
1356
+ }
1357
+ queryAllByTestId(testId) {
1358
+ if (typeof testId !== "string" || testId.length === 0) {
1359
+ throw new TypeError("Native test-ID queries require a non-empty value.");
1360
+ }
1361
+ return this.#elements().filter((element) => element.props.testID === testId);
1362
+ }
1363
+ queryByTestId(testId) {
1364
+ return this.#optionalOne(this.queryAllByTestId(testId), `test ID ${JSON.stringify(testId)}`);
1365
+ }
1366
+ getByTestId(testId) {
1367
+ return this.#one(this.queryAllByTestId(testId), `test ID ${JSON.stringify(testId)}`);
1368
+ }
1369
+ async findByTestId(testId, options = {}) {
1370
+ this.queryAllByTestId(testId);
1371
+ return await this.waitFor(() => this.getByTestId(testId), options);
1372
+ }
1373
+ queryAllByLabelText(matcher) {
1374
+ assertNativeTestTextMatcher(matcher);
1375
+ return this.#elements().filter((element) => {
1376
+ const label = element.props.accessibilityLabel;
1377
+ return typeof label === "string" && matchesNativeTestText(label, matcher);
1378
+ });
1379
+ }
1380
+ queryByLabelText(matcher) {
1381
+ return this.#optionalOne(this.queryAllByLabelText(matcher), `accessibility label ${describeNativeTestMatcher(matcher)}`);
1382
+ }
1383
+ getByLabelText(matcher) {
1384
+ return this.#one(this.queryAllByLabelText(matcher), `accessibility label ${describeNativeTestMatcher(matcher)}`);
1385
+ }
1386
+ async findByLabelText(matcher, options = {}) {
1387
+ this.queryAllByLabelText(matcher);
1388
+ return await this.waitFor(() => this.getByLabelText(matcher), options);
1389
+ }
1390
+ queryAllByRole(role, options = {}) {
1391
+ if (typeof role !== "string" || role.length === 0) {
1392
+ throw new TypeError("Native role queries require a non-empty role.");
1393
+ }
1394
+ if (options.name !== undefined) {
1395
+ assertNativeTestTextMatcher(options.name);
1396
+ }
1397
+ return this.#elements().filter((element) => {
1398
+ if (element.props.accessibilityRole !== role)
1399
+ return false;
1400
+ if (options.name === undefined)
1401
+ return true;
1402
+ const label = element.props.accessibilityLabel;
1403
+ const accessibleName = typeof label === "string" ? label : element.textContent;
1404
+ return matchesNativeTestText(accessibleName, options.name);
1405
+ });
1406
+ }
1407
+ queryByRole(role, options = {}) {
1408
+ return this.#optionalOne(this.queryAllByRole(role, options), describeNativeTestRoleQuery(role, options));
1409
+ }
1410
+ getByRole(role, options = {}) {
1411
+ return this.#one(this.queryAllByRole(role, options), describeNativeTestRoleQuery(role, options));
1412
+ }
1413
+ async findByRole(role, options = {}, waitOptions = {}) {
1414
+ this.queryAllByRole(role, options);
1415
+ return await this.waitFor(() => this.getByRole(role, options), waitOptions);
1416
+ }
1417
+ within(target) {
1418
+ if (target.host !== this.host || target.surface !== this.surfaceId) {
1419
+ throw new Error(`Native test element ${String(target.node)} belongs to another render (surface ${String(target.surface)}); expected the current host and surface ${String(this.surfaceId)}.`);
1420
+ }
1421
+ const current = this.#elementByHandle(target.node);
1422
+ if (current.component !== target.component) {
1423
+ throw new Error(`Native test element ${String(target.node)} is stale; expected ${target.component}, found ${current.component}.`);
1424
+ }
1425
+ return new NativeTestScopeImplementation(this, current);
1426
+ }
1427
+ async fireEvent(target, name, payload = null, options = {}) {
1428
+ if (typeof name !== "string" || name.length === 0) {
1429
+ throw new TypeError("Native test events require a non-empty name.");
1430
+ }
1431
+ if (target.host !== this.host || target.surface !== this.surfaceId) {
1432
+ throw new Error(`Native test element ${String(target.node)} belongs to another render (surface ${String(target.surface)}); expected the current host and surface ${String(this.surfaceId)}.`);
1433
+ }
1434
+ const current = this.#elementByHandle(target.node);
1435
+ if (current.component !== target.component) {
1436
+ throw new Error(`Native test element ${String(target.node)} is stale; expected ${target.component}, found ${current.component}.`);
1437
+ }
1438
+ const descriptor = this.host.getComponentDescriptor(current.component);
1439
+ const bubbles = options.bubbles ?? descriptor?.bubblingEvents.includes(name) ?? false;
1440
+ let event;
1441
+ await this.act(() => {
1442
+ event = this.host.injectEvent({
1443
+ surface: this.surfaceId,
1444
+ target: current.node,
1445
+ name,
1446
+ payload,
1447
+ bubbles,
1448
+ ...(options.observedSequence === undefined
1449
+ ? {}
1450
+ : { observedSequence: options.observedSequence }),
1451
+ ...(options.timestamp === undefined
1452
+ ? {}
1453
+ : { timestamp: options.timestamp }),
1454
+ ...(options.priority === undefined
1455
+ ? {}
1456
+ : { priority: options.priority }),
1457
+ ...(options.coalescible === undefined
1458
+ ? {}
1459
+ : { coalescible: options.coalescible }),
1460
+ });
1461
+ });
1462
+ return event;
1463
+ }
1464
+ async press(target, payload = null) {
1465
+ return await this.fireEvent(target, "press", payload, {
1466
+ priority: "discrete",
1467
+ });
1468
+ }
1469
+ cleanup() {
1470
+ this.#disposal ??= (async () => {
1471
+ await this.application.dispose();
1472
+ if (this.host.hasSurface(this.surfaceId)) {
1473
+ throw new Error(`Native test cleanup left surface ${String(this.surfaceId)} alive.`);
1474
+ }
1475
+ this.#disposed = true;
1476
+ })();
1477
+ return this.#disposal;
1478
+ }
1479
+ assertDisposed() {
1480
+ if (!this.#disposed) {
1481
+ throw new Error("Native test render has not completed cleanup.");
1482
+ }
1483
+ }
1484
+ #assertCommitInspection() {
1485
+ if (this.#disposed) {
1486
+ throw new Error("Cannot inspect commits for a disposed native test render.");
1487
+ }
1488
+ }
1489
+ #optionalCommit(commits, query) {
1490
+ if (commits.length <= 1)
1491
+ return commits[0];
1492
+ throw new NativeTestCommitQueryError(query, commits.length, this.debugCommits());
1493
+ }
1494
+ #oneCommit(commits, query) {
1495
+ const commit = commits.length === 1 ? commits[0] : undefined;
1496
+ if (commit !== undefined)
1497
+ return commit;
1498
+ throw new NativeTestCommitQueryError(query, commits.length, this.debugCommits());
1499
+ }
1500
+ #optionalMutation(mutations, query) {
1501
+ if (mutations.length <= 1)
1502
+ return mutations[0];
1503
+ throw new NativeTestMutationQueryError(query, mutations.length, this.debugCommits());
1504
+ }
1505
+ #oneMutation(mutations, query) {
1506
+ const mutation = mutations.length === 1 ? mutations[0] : undefined;
1507
+ if (mutation !== undefined)
1508
+ return mutation;
1509
+ throw new NativeTestMutationQueryError(query, mutations.length, this.debugCommits());
1510
+ }
1511
+ #optionalOne(elements, query) {
1512
+ if (elements.length <= 1)
1513
+ return elements[0];
1514
+ throw new NativeTestQueryError(query, elements.length, this.#availableSummary());
1515
+ }
1516
+ #one(elements, query) {
1517
+ const element = elements.length === 1 ? elements[0] : undefined;
1518
+ if (element !== undefined)
1519
+ return element;
1520
+ throw new NativeTestQueryError(query, elements.length, this.#availableSummary());
1521
+ }
1522
+ #elementByHandle(node) {
1523
+ const element = this.#elements().find((candidate) => candidate.node === node);
1524
+ if (element === undefined) {
1525
+ throw new Error(`Native test element ${String(node)} is no longer mounted on surface ${String(this.surfaceId)}.`);
1526
+ }
1527
+ return element;
1528
+ }
1529
+ #elements() {
1530
+ return nativeTestElements(this.host, this.snapshot());
1531
+ }
1532
+ #availableSummary() {
1533
+ return nativeTestAvailableSummary(this.#elements());
1534
+ }
1535
+ }
1536
+ class NativeTestScopeImplementation {
1537
+ root;
1538
+ #render;
1539
+ constructor(render, root) {
1540
+ this.#render = render;
1541
+ this.root = root;
1542
+ }
1543
+ queryAllByComponent(component) {
1544
+ return this.#filter(this.#render.queryAllByComponent(component));
1545
+ }
1546
+ queryByComponent(component) {
1547
+ return this.#optionalOne(this.queryAllByComponent(component), `component ${JSON.stringify(component)}`);
1548
+ }
1549
+ getByComponent(component) {
1550
+ return this.#one(this.queryAllByComponent(component), `component ${JSON.stringify(component)}`);
1551
+ }
1552
+ async findByComponent(component, options = {}) {
1553
+ this.queryAllByComponent(component);
1554
+ return await this.#render.waitFor(() => this.getByComponent(component), options);
1555
+ }
1556
+ queryAllByText(matcher) {
1557
+ return this.#filter(this.#render.queryAllByText(matcher));
1558
+ }
1559
+ queryByText(matcher) {
1560
+ return this.#optionalOne(this.queryAllByText(matcher), `text ${describeNativeTestMatcher(matcher)}`);
1561
+ }
1562
+ getByText(matcher) {
1563
+ return this.#one(this.queryAllByText(matcher), `text ${describeNativeTestMatcher(matcher)}`);
1564
+ }
1565
+ async findByText(matcher, options = {}) {
1566
+ this.queryAllByText(matcher);
1567
+ return await this.#render.waitFor(() => this.getByText(matcher), options);
1568
+ }
1569
+ queryAllByTestId(testId) {
1570
+ return this.#filter(this.#render.queryAllByTestId(testId));
1571
+ }
1572
+ queryByTestId(testId) {
1573
+ return this.#optionalOne(this.queryAllByTestId(testId), `test ID ${JSON.stringify(testId)}`);
1574
+ }
1575
+ getByTestId(testId) {
1576
+ return this.#one(this.queryAllByTestId(testId), `test ID ${JSON.stringify(testId)}`);
1577
+ }
1578
+ async findByTestId(testId, options = {}) {
1579
+ this.queryAllByTestId(testId);
1580
+ return await this.#render.waitFor(() => this.getByTestId(testId), options);
1581
+ }
1582
+ queryAllByLabelText(matcher) {
1583
+ return this.#filter(this.#render.queryAllByLabelText(matcher));
1584
+ }
1585
+ queryByLabelText(matcher) {
1586
+ return this.#optionalOne(this.queryAllByLabelText(matcher), `accessibility label ${describeNativeTestMatcher(matcher)}`);
1587
+ }
1588
+ getByLabelText(matcher) {
1589
+ return this.#one(this.queryAllByLabelText(matcher), `accessibility label ${describeNativeTestMatcher(matcher)}`);
1590
+ }
1591
+ async findByLabelText(matcher, options = {}) {
1592
+ this.queryAllByLabelText(matcher);
1593
+ return await this.#render.waitFor(() => this.getByLabelText(matcher), options);
1594
+ }
1595
+ queryAllByRole(role, options = {}) {
1596
+ return this.#filter(this.#render.queryAllByRole(role, options));
1597
+ }
1598
+ queryByRole(role, options = {}) {
1599
+ return this.#optionalOne(this.queryAllByRole(role, options), describeNativeTestRoleQuery(role, options));
1600
+ }
1601
+ getByRole(role, options = {}) {
1602
+ return this.#one(this.queryAllByRole(role, options), describeNativeTestRoleQuery(role, options));
1603
+ }
1604
+ async findByRole(role, options = {}, waitOptions = {}) {
1605
+ this.queryAllByRole(role, options);
1606
+ return await this.#render.waitFor(() => this.getByRole(role, options), waitOptions);
1607
+ }
1608
+ #filter(elements) {
1609
+ const handles = new Set(this.#scopedElements().map((element) => element.node));
1610
+ return elements.filter((element) => handles.has(element.node));
1611
+ }
1612
+ #scopedElements() {
1613
+ const snapshot = this.#render.snapshot();
1614
+ const elements = nativeTestElements(this.#render.host, snapshot);
1615
+ const currentRoot = elements.find((element) => element.node === this.root.node);
1616
+ if (currentRoot === undefined) {
1617
+ throw new Error(`Native test scope root ${String(this.root.node)} is no longer mounted on surface ${String(this.root.surface)}.`);
1618
+ }
1619
+ if (currentRoot.component !== this.root.component) {
1620
+ throw new Error(`Native test scope root ${String(this.root.node)} is stale; expected ${this.root.component}, found ${currentRoot.component}.`);
1621
+ }
1622
+ const nodes = new Map(snapshot.nodes.map((node) => [node.node, node]));
1623
+ return elements.filter((element) => {
1624
+ let current = nodes.get(element.node);
1625
+ let remaining = nodes.size + 1;
1626
+ while (current !== undefined && remaining > 0) {
1627
+ if (current.node === this.root.node)
1628
+ return true;
1629
+ current =
1630
+ current.parent === null ? undefined : nodes.get(current.parent);
1631
+ remaining -= 1;
1632
+ }
1633
+ return false;
1634
+ });
1635
+ }
1636
+ #optionalOne(elements, query) {
1637
+ if (elements.length <= 1)
1638
+ return elements[0];
1639
+ throw new NativeTestQueryError(query, elements.length, nativeTestAvailableSummary(this.#scopedElements()));
1640
+ }
1641
+ #one(elements, query) {
1642
+ const element = elements.length === 1 ? elements[0] : undefined;
1643
+ if (element !== undefined)
1644
+ return element;
1645
+ throw new NativeTestQueryError(query, elements.length, nativeTestAvailableSummary(this.#scopedElements()));
1646
+ }
1647
+ }
1648
+ /**
1649
+ * Mounts one Solid Native tree into the strict in-memory host and flushes its
1650
+ * initial commit before returning. The render always disables background
1651
+ * auto-commit scheduling so every later mutation crosses an explicit test
1652
+ * boundary through flush, act, or fireEvent.
1653
+ */
1654
+ export async function renderNative(code, options = {}) {
1655
+ if (typeof code !== "function") {
1656
+ throw new TypeError("renderNative requires a root callback.");
1657
+ }
1658
+ if (options.host !== undefined && options.hostOptions !== undefined) {
1659
+ throw new TypeError("renderNative cannot combine host and hostOptions.");
1660
+ }
1661
+ const host = options.host ??
1662
+ new InMemoryHost({
1663
+ ...options.hostOptions,
1664
+ descriptors: options.hostOptions?.descriptors ?? CORE_COMPONENT_DESCRIPTORS,
1665
+ });
1666
+ const commitOffset = host.commits.length;
1667
+ const application = mount(code, host, {
1668
+ ...options.rootOptions,
1669
+ surface: options.surface ?? { name: "test" },
1670
+ autoCommit: false,
1671
+ });
1672
+ const result = new NativeTestRenderImplementation(application, host, commitOffset);
1673
+ try {
1674
+ await result.flush();
1675
+ return result;
1676
+ }
1677
+ catch (error) {
1678
+ await result.cleanup().catch(() => undefined);
1679
+ throw error;
1680
+ }
1681
+ }
1682
+ //# sourceMappingURL=index.js.map