@ansight/pencil-runtime 0.0.0-stage → 1.9.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/LICENSE ADDED
@@ -0,0 +1,166 @@
1
+ # PolyForm Shield License 1.0.0
2
+
3
+ <https://polyformproject.org/licenses/shield/1.0.0>
4
+
5
+ ## Acceptance
6
+
7
+ In order to get any license under these terms, you must agree
8
+ to them as both strict obligations and conditions to all
9
+ your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the
14
+ software to do everything you might do with the software
15
+ that would otherwise infringe the licensor's copyright
16
+ in it for any permitted purpose. However, you may
17
+ only distribute the software according to [Distribution
18
+ License](#distribution-license) and make changes or new works
19
+ based on the software according to [Changes and New Works
20
+ License](#changes-and-new-works-license).
21
+
22
+ ## Distribution License
23
+
24
+ The licensor grants you an additional copyright license
25
+ to distribute copies of the software. Your license
26
+ to distribute covers distributing the software with
27
+ changes and new works permitted by [Changes and New Works
28
+ License](#changes-and-new-works-license).
29
+
30
+ ## Notices
31
+
32
+ You must ensure that anyone who gets a copy of any part of
33
+ the software from you also gets a copy of these terms or the
34
+ URL for them above, as well as copies of any plain-text lines
35
+ beginning with `Required Notice:` that the licensor provided
36
+ with the software. For example:
37
+
38
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
39
+
40
+ ## Changes and New Works License
41
+
42
+ The licensor grants you an additional copyright license to
43
+ make changes and new works based on the software for any
44
+ permitted purpose.
45
+
46
+ ## Patent License
47
+
48
+ The licensor grants you a patent license for the software that
49
+ covers patent claims the licensor can license, or becomes able
50
+ to license, that you would infringe by using the software.
51
+
52
+ ## Noncompete
53
+
54
+ Any purpose is a permitted purpose, except for providing any
55
+ product that competes with the software or any product the
56
+ licensor or any of its affiliates provides using the software.
57
+
58
+ ## Competition
59
+
60
+ Goods and services compete even when they provide functionality
61
+ through different kinds of interfaces or for different technical
62
+ platforms. Applications can compete with services, libraries
63
+ with plugins, frameworks with development tools, and so on,
64
+ even if they're written in different programming languages
65
+ or for different computer architectures. Goods and services
66
+ compete even when provided free of charge. If you market a
67
+ product as a practical substitute for the software or another
68
+ product, it definitely competes.
69
+
70
+ ## New Products
71
+
72
+ If you are using the software to provide a product that does
73
+ not compete, but the licensor or any of its affiliates brings
74
+ your product into competition by providing a new version of
75
+ the software or another product using the software, you may
76
+ continue using versions of the software available under these
77
+ terms beforehand to provide your competing product, but not
78
+ any later versions.
79
+
80
+ ## Discontinued Products
81
+
82
+ You may begin using the software to compete with a product
83
+ or service that the licensor or any of its affiliates has
84
+ stopped providing, unless the licensor includes a plain-text
85
+ line beginning with `Licensor Line of Business:` with the
86
+ software that mentions that line of business. For example:
87
+
88
+ > Licensor Line of Business: YoyodyneCMS Content Management
89
+ System (http://example.com/cms)
90
+
91
+ ## Sales of Business
92
+
93
+ If the licensor or any of its affiliates sells a line of
94
+ business developing the software or using the software
95
+ to provide a product, the buyer can also enforce
96
+ [Noncompete](#noncompete) for that product.
97
+
98
+ ## Fair Use
99
+
100
+ You may have "fair use" rights for the software under the
101
+ law. These terms do not limit them.
102
+
103
+ ## No Other Rights
104
+
105
+ These terms do not allow you to sublicense or transfer any of
106
+ your licenses to anyone else, or prevent the licensor from
107
+ granting licenses to anyone else. These terms do not imply
108
+ any other licenses.
109
+
110
+ ## Patent Defense
111
+
112
+ If you make any written claim that the software infringes or
113
+ contributes to infringement of any patent, your patent license
114
+ for the software granted under these terms ends immediately. If
115
+ your company makes such a claim, your patent license ends
116
+ immediately for work on behalf of your company.
117
+
118
+ ## Violations
119
+
120
+ The first time you are notified in writing that you have
121
+ violated any of these terms, or done anything with the software
122
+ not covered by your licenses, your licenses can nonetheless
123
+ continue if you come into full compliance with these terms,
124
+ and take practical steps to correct past violations, within
125
+ 32 days of receiving notice. Otherwise, all your licenses
126
+ end immediately.
127
+
128
+ ## No Liability
129
+
130
+ ***As far as the law allows, the software comes as is, without
131
+ any warranty or condition, and the licensor will not be liable
132
+ to you for any damages arising out of these terms or the use
133
+ or nature of the software, under any kind of legal claim.***
134
+
135
+ ## Definitions
136
+
137
+ The **licensor** is the individual or entity offering these
138
+ terms, and the **software** is the software the licensor makes
139
+ available under these terms.
140
+
141
+ A **product** can be a good or service, or a combination
142
+ of them.
143
+
144
+ **You** refers to the individual or entity agreeing to these
145
+ terms.
146
+
147
+ **Your company** is any legal entity, sole proprietorship,
148
+ or other kind of organization that you work for, plus all
149
+ its affiliates.
150
+
151
+ **Affiliates** means the other organizations than an
152
+ organization has control over, is under the control of, or is
153
+ under common control with.
154
+
155
+ **Control** means ownership of substantially all the assets of
156
+ an entity, or the power to direct its management and policies
157
+ by vote, contract, or otherwise. Control can be direct or
158
+ indirect.
159
+
160
+ **Your licenses** are all the licenses granted to you for the
161
+ software under these terms.
162
+
163
+ **Use** means anything you do with the software requiring one
164
+ of your licenses.
165
+
166
+ Required Notice: Copyright (c) 2026 Ansight, Inc. (https://www.ansight.ai)
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # @ansight/pencil-runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Optional Pencil support for iOS Simulator.
4
+
5
+ [Documentation: integration, playback, capture, compatibility and package updates](https://www.ansight.ai/docs/sdk/pencil).
6
+
7
+ These packages are currently local and unpublished.
package/index.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ export interface PenSample { phase: 'down'|'move'|'up'|'cancel'|'hoverEnter'|'hoverMove'|'hoverExit'; x: number; y: number; pressure: number; altitudeRadians: number; azimuthRadians: number; rollRadians: number; distance: number; }
2
+ export interface SurfaceGeometry { x: number; y: number; width: number; height: number; viewportWidth: number; viewportHeight: number; scale: number; }
3
+ export interface PencilAdapter {
4
+ validate?(samples: PenSample[]): void;
5
+ snapshot(): SurfaceGeometry | Promise<SurfaceGeometry>;
6
+ hitTest(point: {x: number; y: number}): boolean | Promise<boolean>;
7
+ dispatch(sample: PenSample, geometry: SurfaceGeometry, pointerId: number): void | Promise<void>;
8
+ finish?(pointerId: number): void | Promise<void>;
9
+ isBusy?(): boolean;
10
+ onError?(error: unknown): void;
11
+ }
12
+ export function createPencilRuntime(options: {
13
+ capture(sample: PenSample, geometry: SurfaceGeometry, pointerId: number): Promise<void>;
14
+ checkPlayback(): Promise<void>; timeoutMs?: number;
15
+ }): {
16
+ definition: { id: string; name: string; category: string; policy: 'write'; description: string; argumentsSchema: Record<string, unknown> };
17
+ bindSurface(id: string, adapter: PencilAdapter): () => Promise<void>;
18
+ handle(args: {command: string}): Promise<{success: true; result?: unknown} | {success: false; message: string; errorCode?: string}>;
19
+ };
20
+ export function pointerProperties(sample: PenSample, geometry: SurfaceGeometry, pointerId: number): {
21
+ pointerId: number; pointerType: string; isPrimary: boolean; clientX: number; clientY: number;
22
+ pageX: number; pageY: number; pressure: number; width: number; height: number;
23
+ buttons: number; button: number; tiltX: number; tiltY: number; twist: number;
24
+ altitudeAngle: number; azimuthAngle: number; ansightPencil: PenSample & {inputSource: string};
25
+ };
26
+ export function validateSequence(samples: unknown[]): PenSample[];
package/index.js ADDED
@@ -0,0 +1,139 @@
1
+ 'use strict';
2
+
3
+ const phases = ['down', 'move', 'up', 'cancel', 'hoverEnter', 'hoverMove', 'hoverExit'];
4
+ const fields = ['phase', 'x', 'y', 'pressure', 'altitudeRadians', 'azimuthRadians', 'rollRadians', 'distance'];
5
+ function normalize(value) {
6
+ if (!value || typeof value !== 'object' || !phases.includes(value.phase)) throw new Error('Invalid Pencil sample.');
7
+ const sample = { pressure: 0, altitudeRadians: Math.PI / 2, azimuthRadians: 0, rollRadians: 0, distance: 0, ...value };
8
+ if (Object.keys(sample).some(key => !fields.includes(key))) throw new Error('Unknown Pencil sample field.');
9
+ for (const key of fields.slice(1)) if (!Number.isFinite(sample[key])) throw new Error('Pencil values must be finite.');
10
+ for (const key of ['x', 'y', 'pressure', 'distance']) if (sample[key] < 0 || sample[key] > 1) throw new Error(`${key} must be between 0 and 1.`);
11
+ if (sample.altitudeRadians < 0 || sample.altitudeRadians > Math.PI / 2) throw new Error('Invalid altitude.');
12
+ if (!['down', 'move'].includes(sample.phase) && sample.pressure !== 0) throw new Error('Non-contact pressure must be zero.');
13
+ return Object.fromEntries(fields.map(key => [key, sample[key]]));
14
+ }
15
+ function validateSequence(values) {
16
+ if (!Array.isArray(values) || values.length < 2 || values.length > 2000) throw new Error('Supply 2..2000 samples.');
17
+ let touching = false, hovering = false;
18
+ return values.map(normalize).map((sample, index, all) => {
19
+ const p = sample.phase;
20
+ if ((p === 'down' && touching) || (['move', 'up', 'cancel'].includes(p) && !touching)
21
+ || (p === 'hoverEnter' && (touching || hovering)) || (['hoverMove', 'hoverExit'].includes(p) && (!hovering || touching))) throw new Error('Invalid Pencil sequence.');
22
+ if (p === 'down') { touching = true; hovering = false; }
23
+ if (p === 'up') { touching = false; hovering = true; }
24
+ if (p === 'hoverEnter') hovering = true;
25
+ if (['cancel', 'hoverExit'].includes(p)) { touching = false; hovering = false; }
26
+ if (index === all.length - 1 && touching) throw new Error('End contact with up or cancel.');
27
+ return sample;
28
+ });
29
+ }
30
+ function geometry(value) {
31
+ if (!value || !['x', 'y', 'width', 'height', 'viewportWidth', 'viewportHeight', 'scale'].every(key => Number.isFinite(value[key]))) throw new Error('Surface is not laid out.');
32
+ if (['width', 'height', 'viewportWidth', 'viewportHeight', 'scale'].some(key => value[key] <= 0)) throw new Error('Surface has no visible area.');
33
+ return Object.fromEntries(['x', 'y', 'width', 'height', 'viewportWidth', 'viewportHeight', 'scale'].map(key => [key, value[key]]));
34
+ }
35
+ function point(sample, rect) { return { x: sample.x * rect.viewportWidth, y: sample.y * rect.viewportHeight }; }
36
+ function inside(sample, rect) {
37
+ const p = point(sample, rect);
38
+ return p.x >= rect.x && p.y >= rect.y && p.x < rect.x + rect.width && p.y < rect.y + rect.height;
39
+ }
40
+
41
+ const definition = {
42
+ id: 'ui.simulate_pen_framework', name: 'Play Pencil input on a registered framework surface', category: 'ui', policy: 'write',
43
+ description: 'Explicit SDK playback; invokes only a registered framework surface. Does not inject HID or install UIKit hooks.',
44
+ argumentsSchema: { type: 'object', required: ['command'], additionalProperties: false, properties: { command: { type: 'string' } } },
45
+ };
46
+
47
+ function createPencilRuntime({ capture, checkPlayback, timeoutMs = 35000 }) {
48
+ const surfaces = new Map();
49
+ let active = null, handling = false, nextPointer = 1900000000;
50
+ async function finish(run = active) {
51
+ if (!run || active !== run) return;
52
+ active = null;
53
+ clearTimeout(run.timer);
54
+ const last = run.last;
55
+ try {
56
+ if (last && (run.touching || run.hovering)) {
57
+ const terminal = { ...last, phase: run.touching ? 'cancel' : 'hoverExit', pressure: 0 };
58
+ try { await run.adapter.dispatch(terminal, run.rect, run.pointerId); }
59
+ finally { await capture(terminal, run.rect, run.pointerId); }
60
+ }
61
+ } finally { await run.adapter.finish?.(run.pointerId); }
62
+ }
63
+ function bindSurface(id, adapter) {
64
+ if (typeof id !== 'string' || !id.trim() || surfaces.has(id)) throw new Error('Pencil surface IDs must be unique and nonempty.');
65
+ surfaces.set(id, adapter);
66
+ return async () => {
67
+ if (surfaces.get(id) !== adapter) return;
68
+ surfaces.delete(id);
69
+ if (active?.adapter === adapter) await finish();
70
+ };
71
+ }
72
+ async function execute(command) {
73
+ if (!command || typeof command.runId !== 'string' || !command.runId.trim()) throw new Error('A run ID is required.');
74
+ if (command.action === 'prepare') {
75
+ if (active) throw new Error('A Pencil run is already active.');
76
+ const adapter = surfaces.get(command.target);
77
+ if (!adapter) throw new Error('Pencil target is not mounted or registered.');
78
+ const samples = validateSequence(command.samples);
79
+ adapter.validate?.(samples);
80
+ await checkPlayback();
81
+ const rect = geometry(await adapter.snapshot());
82
+ if (adapter.isBusy?.()) throw new Error('The surface has active real input.');
83
+ for (const sample of samples) if (!inside(sample, rect) || !(await adapter.hitTest(point(sample, rect)))) throw new Error('A sample does not hit the selected surface.');
84
+ if (surfaces.get(command.target) !== adapter || adapter.isBusy?.()) throw new Error('Surface detached or received real input during preparation.');
85
+ const run = { adapter, target: command.target, id: command.runId, samples, rect, index: 0, pointerId: nextPointer++, touching: false, hovering: false, last: null };
86
+ active = run;
87
+ run.timer = setTimeout(() => { finish(run).catch(error => adapter.onError?.(error)); }, timeoutMs);
88
+ run.timer.unref?.();
89
+ return { protocolVersion: 1, delivery: 'framework' };
90
+ }
91
+ if (!active && command.action === 'finish') return {};
92
+ if (!active || active.id !== command.runId) throw new Error('No matching Pencil run.');
93
+ const run = active;
94
+ if (command.action === 'finish') { await finish(run); return {}; }
95
+ if (command.action !== 'sample') throw new Error('Unknown Pencil action.');
96
+ try {
97
+ const sample = normalize(command.sample);
98
+ if (JSON.stringify(sample) !== JSON.stringify(run.samples[run.index])) throw new Error('Sample differs from the prepared sequence.');
99
+ if (surfaces.get(run.target) !== run.adapter || run.adapter.isBusy?.()) throw new Error('Surface detached or received real input.');
100
+ if (JSON.stringify(geometry(await run.adapter.snapshot())) !== JSON.stringify(run.rect) || !(await run.adapter.hitTest(point(sample, run.rect)))) throw new Error('Surface moved, resized or became covered.');
101
+ await checkPlayback();
102
+ // Native checks yield to the app; disposal or lease expiry can happen while awaiting them.
103
+ if (active !== run || surfaces.get(run.target) !== run.adapter || run.adapter.isBusy?.()) throw new Error('Pencil run ended or the surface changed during validation.');
104
+ run.last = sample;
105
+ run.touching = ['down', 'move'].includes(sample.phase);
106
+ run.hovering = ['up', 'hoverEnter', 'hoverMove'].includes(sample.phase);
107
+ await run.adapter.dispatch(sample, run.rect, run.pointerId);
108
+ await capture(sample, run.rect, run.pointerId);
109
+ if (active !== run) throw new Error('Pencil run ended during delivery.');
110
+ run.index++;
111
+ return { delivered: true, sampleIndex: run.index - 1 };
112
+ } catch (error) { await finish(run); throw error; }
113
+ }
114
+ async function handle(args) {
115
+ if (handling) return { success: false, errorCode: 'pen_busy', message: 'Another Pencil command is executing.' };
116
+ handling = true;
117
+ try {
118
+ const command = JSON.parse(args.command);
119
+ return { success: true, result: await execute(command) };
120
+ } catch (error) { return { success: false, errorCode: 'pen_framework_failed', message: String(error.message || error) }; }
121
+ finally { handling = false; }
122
+ }
123
+ return { definition, bindSurface, handle };
124
+ }
125
+
126
+ function pointerProperties(sample, rect, pointerId) {
127
+ const p = point(sample, rect), contact = ['down', 'move'].includes(sample.phase);
128
+ const altitude = sample.altitudeRadians, azimuth = sample.azimuthRadians;
129
+ const degrees = 180 / Math.PI;
130
+ return { pointerId, pointerType: 'pen', isPrimary: true, clientX: p.x, clientY: p.y,
131
+ pageX: p.x, pageY: p.y, pressure: sample.pressure, width: 1, height: 1,
132
+ buttons: contact ? 1 : 0, button: ['down', 'up'].includes(sample.phase) ? 0 : -1,
133
+ tiltX: Math.atan2(Math.cos(azimuth) * Math.cos(altitude), Math.sin(altitude)) * degrees,
134
+ tiltY: Math.atan2(Math.sin(azimuth) * Math.cos(altitude), Math.sin(altitude)) * degrees,
135
+ twist: ((sample.rollRadians * degrees % 360) + 360) % 360,
136
+ altitudeAngle: altitude, azimuthAngle: azimuth,
137
+ ansightPencil: Object.freeze({ ...sample, inputSource: 'simulator-sdk-framework' }) };
138
+ }
139
+ module.exports = { createPencilRuntime, pointerProperties, validateSequence };
package/index.mjs ADDED
@@ -0,0 +1,139 @@
1
+ 'use strict';
2
+
3
+ const phases = ['down', 'move', 'up', 'cancel', 'hoverEnter', 'hoverMove', 'hoverExit'];
4
+ const fields = ['phase', 'x', 'y', 'pressure', 'altitudeRadians', 'azimuthRadians', 'rollRadians', 'distance'];
5
+ function normalize(value) {
6
+ if (!value || typeof value !== 'object' || !phases.includes(value.phase)) throw new Error('Invalid Pencil sample.');
7
+ const sample = { pressure: 0, altitudeRadians: Math.PI / 2, azimuthRadians: 0, rollRadians: 0, distance: 0, ...value };
8
+ if (Object.keys(sample).some(key => !fields.includes(key))) throw new Error('Unknown Pencil sample field.');
9
+ for (const key of fields.slice(1)) if (!Number.isFinite(sample[key])) throw new Error('Pencil values must be finite.');
10
+ for (const key of ['x', 'y', 'pressure', 'distance']) if (sample[key] < 0 || sample[key] > 1) throw new Error(`${key} must be between 0 and 1.`);
11
+ if (sample.altitudeRadians < 0 || sample.altitudeRadians > Math.PI / 2) throw new Error('Invalid altitude.');
12
+ if (!['down', 'move'].includes(sample.phase) && sample.pressure !== 0) throw new Error('Non-contact pressure must be zero.');
13
+ return Object.fromEntries(fields.map(key => [key, sample[key]]));
14
+ }
15
+ function validateSequence(values) {
16
+ if (!Array.isArray(values) || values.length < 2 || values.length > 2000) throw new Error('Supply 2..2000 samples.');
17
+ let touching = false, hovering = false;
18
+ return values.map(normalize).map((sample, index, all) => {
19
+ const p = sample.phase;
20
+ if ((p === 'down' && touching) || (['move', 'up', 'cancel'].includes(p) && !touching)
21
+ || (p === 'hoverEnter' && (touching || hovering)) || (['hoverMove', 'hoverExit'].includes(p) && (!hovering || touching))) throw new Error('Invalid Pencil sequence.');
22
+ if (p === 'down') { touching = true; hovering = false; }
23
+ if (p === 'up') { touching = false; hovering = true; }
24
+ if (p === 'hoverEnter') hovering = true;
25
+ if (['cancel', 'hoverExit'].includes(p)) { touching = false; hovering = false; }
26
+ if (index === all.length - 1 && touching) throw new Error('End contact with up or cancel.');
27
+ return sample;
28
+ });
29
+ }
30
+ function geometry(value) {
31
+ if (!value || !['x', 'y', 'width', 'height', 'viewportWidth', 'viewportHeight', 'scale'].every(key => Number.isFinite(value[key]))) throw new Error('Surface is not laid out.');
32
+ if (['width', 'height', 'viewportWidth', 'viewportHeight', 'scale'].some(key => value[key] <= 0)) throw new Error('Surface has no visible area.');
33
+ return Object.fromEntries(['x', 'y', 'width', 'height', 'viewportWidth', 'viewportHeight', 'scale'].map(key => [key, value[key]]));
34
+ }
35
+ function point(sample, rect) { return { x: sample.x * rect.viewportWidth, y: sample.y * rect.viewportHeight }; }
36
+ function inside(sample, rect) {
37
+ const p = point(sample, rect);
38
+ return p.x >= rect.x && p.y >= rect.y && p.x < rect.x + rect.width && p.y < rect.y + rect.height;
39
+ }
40
+
41
+ const definition = {
42
+ id: 'ui.simulate_pen_framework', name: 'Play Pencil input on a registered framework surface', category: 'ui', policy: 'write',
43
+ description: 'Explicit SDK playback; invokes only a registered framework surface. Does not inject HID or install UIKit hooks.',
44
+ argumentsSchema: { type: 'object', required: ['command'], additionalProperties: false, properties: { command: { type: 'string' } } },
45
+ };
46
+
47
+ function createPencilRuntime({ capture, checkPlayback, timeoutMs = 35000 }) {
48
+ const surfaces = new Map();
49
+ let active = null, handling = false, nextPointer = 1900000000;
50
+ async function finish(run = active) {
51
+ if (!run || active !== run) return;
52
+ active = null;
53
+ clearTimeout(run.timer);
54
+ const last = run.last;
55
+ try {
56
+ if (last && (run.touching || run.hovering)) {
57
+ const terminal = { ...last, phase: run.touching ? 'cancel' : 'hoverExit', pressure: 0 };
58
+ try { await run.adapter.dispatch(terminal, run.rect, run.pointerId); }
59
+ finally { await capture(terminal, run.rect, run.pointerId); }
60
+ }
61
+ } finally { await run.adapter.finish?.(run.pointerId); }
62
+ }
63
+ function bindSurface(id, adapter) {
64
+ if (typeof id !== 'string' || !id.trim() || surfaces.has(id)) throw new Error('Pencil surface IDs must be unique and nonempty.');
65
+ surfaces.set(id, adapter);
66
+ return async () => {
67
+ if (surfaces.get(id) !== adapter) return;
68
+ surfaces.delete(id);
69
+ if (active?.adapter === adapter) await finish();
70
+ };
71
+ }
72
+ async function execute(command) {
73
+ if (!command || typeof command.runId !== 'string' || !command.runId.trim()) throw new Error('A run ID is required.');
74
+ if (command.action === 'prepare') {
75
+ if (active) throw new Error('A Pencil run is already active.');
76
+ const adapter = surfaces.get(command.target);
77
+ if (!adapter) throw new Error('Pencil target is not mounted or registered.');
78
+ const samples = validateSequence(command.samples);
79
+ adapter.validate?.(samples);
80
+ await checkPlayback();
81
+ const rect = geometry(await adapter.snapshot());
82
+ if (adapter.isBusy?.()) throw new Error('The surface has active real input.');
83
+ for (const sample of samples) if (!inside(sample, rect) || !(await adapter.hitTest(point(sample, rect)))) throw new Error('A sample does not hit the selected surface.');
84
+ if (surfaces.get(command.target) !== adapter || adapter.isBusy?.()) throw new Error('Surface detached or received real input during preparation.');
85
+ const run = { adapter, target: command.target, id: command.runId, samples, rect, index: 0, pointerId: nextPointer++, touching: false, hovering: false, last: null };
86
+ active = run;
87
+ run.timer = setTimeout(() => { finish(run).catch(error => adapter.onError?.(error)); }, timeoutMs);
88
+ run.timer.unref?.();
89
+ return { protocolVersion: 1, delivery: 'framework' };
90
+ }
91
+ if (!active && command.action === 'finish') return {};
92
+ if (!active || active.id !== command.runId) throw new Error('No matching Pencil run.');
93
+ const run = active;
94
+ if (command.action === 'finish') { await finish(run); return {}; }
95
+ if (command.action !== 'sample') throw new Error('Unknown Pencil action.');
96
+ try {
97
+ const sample = normalize(command.sample);
98
+ if (JSON.stringify(sample) !== JSON.stringify(run.samples[run.index])) throw new Error('Sample differs from the prepared sequence.');
99
+ if (surfaces.get(run.target) !== run.adapter || run.adapter.isBusy?.()) throw new Error('Surface detached or received real input.');
100
+ if (JSON.stringify(geometry(await run.adapter.snapshot())) !== JSON.stringify(run.rect) || !(await run.adapter.hitTest(point(sample, run.rect)))) throw new Error('Surface moved, resized or became covered.');
101
+ await checkPlayback();
102
+ // Native checks yield to the app; disposal or lease expiry can happen while awaiting them.
103
+ if (active !== run || surfaces.get(run.target) !== run.adapter || run.adapter.isBusy?.()) throw new Error('Pencil run ended or the surface changed during validation.');
104
+ run.last = sample;
105
+ run.touching = ['down', 'move'].includes(sample.phase);
106
+ run.hovering = ['up', 'hoverEnter', 'hoverMove'].includes(sample.phase);
107
+ await run.adapter.dispatch(sample, run.rect, run.pointerId);
108
+ await capture(sample, run.rect, run.pointerId);
109
+ if (active !== run) throw new Error('Pencil run ended during delivery.');
110
+ run.index++;
111
+ return { delivered: true, sampleIndex: run.index - 1 };
112
+ } catch (error) { await finish(run); throw error; }
113
+ }
114
+ async function handle(args) {
115
+ if (handling) return { success: false, errorCode: 'pen_busy', message: 'Another Pencil command is executing.' };
116
+ handling = true;
117
+ try {
118
+ const command = JSON.parse(args.command);
119
+ return { success: true, result: await execute(command) };
120
+ } catch (error) { return { success: false, errorCode: 'pen_framework_failed', message: String(error.message || error) }; }
121
+ finally { handling = false; }
122
+ }
123
+ return { definition, bindSurface, handle };
124
+ }
125
+
126
+ function pointerProperties(sample, rect, pointerId) {
127
+ const p = point(sample, rect), contact = ['down', 'move'].includes(sample.phase);
128
+ const altitude = sample.altitudeRadians, azimuth = sample.azimuthRadians;
129
+ const degrees = 180 / Math.PI;
130
+ return { pointerId, pointerType: 'pen', isPrimary: true, clientX: p.x, clientY: p.y,
131
+ pageX: p.x, pageY: p.y, pressure: sample.pressure, width: 1, height: 1,
132
+ buttons: contact ? 1 : 0, button: ['down', 'up'].includes(sample.phase) ? 0 : -1,
133
+ tiltX: Math.atan2(Math.cos(azimuth) * Math.cos(altitude), Math.sin(altitude)) * degrees,
134
+ tiltY: Math.atan2(Math.sin(azimuth) * Math.cos(altitude), Math.sin(altitude)) * degrees,
135
+ twist: ((sample.rollRadians * degrees % 360) + 360) % 360,
136
+ altitudeAngle: altitude, azimuthAngle: azimuth,
137
+ ansightPencil: Object.freeze({ ...sample, inputSource: 'simulator-sdk-framework' }) };
138
+ }
139
+ export { createPencilRuntime, pointerProperties, validateSequence };
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@ansight/pencil-runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.9.0",
4
+ "description": "Scoped playback lifecycle for optional Ansight Pencil framework adapters.",
5
+ "main": "index.js",
6
+ "module": "index.mjs",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./index.d.ts",
10
+ "import": "./index.mjs",
11
+ "require": "./index.js"
12
+ }
13
+ },
14
+ "types": "index.d.ts",
15
+ "files": [
16
+ "index.js",
17
+ "index.mjs",
18
+ "index.d.ts",
19
+ "LICENSE"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "license": "SEE LICENSE IN LICENSE",
25
+ "scripts": {
26
+ "build": "node build.mjs",
27
+ "prepack": "npm run build",
28
+ "test": "npm run build && node --test test/*.test.js",
29
+ "check": "npm test"
30
+ }
31
+ }