@popmelt.com/core 0.38.1 → 0.40.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.
Files changed (165) hide show
  1. package/README.md +5 -32
  2. package/claude-plugin/.claude-plugin/plugin.json +1 -1
  3. package/claude-plugin/skills/popmelt-core/SKILL.md +5 -1
  4. package/codex-plugin/.codex-plugin/plugin.json +1 -1
  5. package/codex-plugin/skills/popmelt-core/SKILL.md +5 -1
  6. package/dist/{ExploreAttachment-IIEORQP3.mjs → ExploreAttachment-DBMYVYWK.mjs} +1 -1
  7. package/dist/PagePreviewLayer-CVUA6CTQ.mjs +1 -0
  8. package/dist/ParticipantRuntime-PCBEG3Q2.mjs +1 -0
  9. package/dist/PhoneHostGate-FZLK4R6M.mjs +1 -0
  10. package/dist/PopmeltTasteConnectedPane-62LUNNWZ.mjs +1 -0
  11. package/dist/{PreviewRuntime-3ANAJNFO.mjs → PreviewRuntime-7EQNIOF5.mjs} +1 -1
  12. package/dist/SamplePlacementOverlay-LR7GZVYP.mjs +1 -0
  13. package/dist/ShareProjectPane-U47UTAOP.mjs +1 -0
  14. package/dist/SuppliedContext-F7WKJ5XO.mjs +1 -0
  15. package/dist/ThreadErrorCard-KPP7YUFC.mjs +1 -0
  16. package/dist/ThreadPanel-GOYQEF3I.mjs +1 -0
  17. package/dist/adapter-react-three-fiber.d.mts +4 -37
  18. package/dist/adapter-react-three-fiber.mjs +1 -1
  19. package/dist/adapter-three.d.mts +23 -228
  20. package/dist/adapter-three.mjs +1 -45
  21. package/dist/bridge-entry.mjs +1 -1
  22. package/dist/{bridgeSSEStream-HUFNXYPG.mjs → bridgeSSEStream-2KKFO64A.mjs} +1 -1
  23. package/dist/{bridgeWebSocketStream-AS22Y2FP.mjs → bridgeWebSocketStream-XTHQPBPI.mjs} +1 -1
  24. package/dist/browser-runtime-BBQQQLF7.mjs +1 -0
  25. package/dist/browser.d.mts +4 -4
  26. package/dist/browser.mjs +1 -1
  27. package/dist/canvas-chat-note-XMVKWL2J.mjs +1 -0
  28. package/dist/canvas-text.d.mts +38 -0
  29. package/dist/canvas-text.mjs +1 -0
  30. package/dist/{checkFixture-UNTXJKRN.mjs → checkFixture-VDRYDCUX.mjs} +1 -1
  31. package/dist/{chunk-UOK5LOPJ.mjs → chunk-27WBFE5X.mjs} +1 -1
  32. package/dist/{chunk-5F34UIKL.mjs → chunk-3EYAVOPH.mjs} +1 -1
  33. package/dist/chunk-4EDMISUV.mjs +1 -0
  34. package/dist/chunk-52OTX7DP.mjs +1 -0
  35. package/dist/chunk-53QOGFAT.mjs +1 -0
  36. package/dist/{chunk-3VOEPWRL.mjs → chunk-5TCWBNV4.mjs} +1 -1
  37. package/dist/chunk-6GS4BQVU.mjs +30 -0
  38. package/dist/{chunk-TXL2CR66.mjs → chunk-6U5JWZ4X.mjs} +1 -1
  39. package/dist/{chunk-WJVRGXOS.mjs → chunk-7D4BUDKG.mjs} +1 -1
  40. package/dist/chunk-7DXJSJCI.mjs +1 -0
  41. package/dist/chunk-AKUIREET.mjs +1 -0
  42. package/dist/chunk-B4RLDY5H.mjs +1 -0
  43. package/dist/{chunk-ZHXTB5IN.mjs → chunk-BDUWFDBP.mjs} +1 -1
  44. package/dist/chunk-C4AMAM3W.mjs +1 -0
  45. package/dist/{chunk-2WQXHUEQ.mjs → chunk-CR6TRUUV.mjs} +1 -1
  46. package/dist/{chunk-KHDXOXYF.mjs → chunk-DJFZGYX6.mjs} +1 -1
  47. package/dist/chunk-EHM2ZBQU.mjs +1 -0
  48. package/dist/{chunk-QXFBFKN6.mjs → chunk-EWTZVC7E.mjs} +1 -1
  49. package/dist/{chunk-BJUSVIDN.mjs → chunk-FFBBRCPC.mjs} +1 -1
  50. package/dist/chunk-FR6VIGJ2.mjs +1 -0
  51. package/dist/{chunk-GTVTUWGH.mjs → chunk-FSSHNWMO.mjs} +1 -1
  52. package/dist/{chunk-AEC67LMY.mjs → chunk-HC2SF7KE.mjs} +1 -1
  53. package/dist/chunk-HM6EBJVO.mjs +1 -0
  54. package/dist/chunk-HOWDQUPT.mjs +1 -0
  55. package/dist/{chunk-XJJDBMZI.mjs → chunk-HQVWOBYH.mjs} +1 -1
  56. package/dist/chunk-HTQEMKFA.mjs +1 -0
  57. package/dist/{chunk-GLF7Z5IR.mjs → chunk-K22VZV3V.mjs} +1 -1
  58. package/dist/chunk-KOHR4LAQ.mjs +1 -0
  59. package/dist/chunk-LLVF422C.mjs +1 -0
  60. package/dist/{chunk-F3VZQGPM.mjs → chunk-LUTP7QBD.mjs} +1 -1
  61. package/dist/chunk-MHTX52KW.mjs +1 -0
  62. package/dist/chunk-NC7YXD7Q.mjs +1 -0
  63. package/dist/{chunk-RJWFSAKE.mjs → chunk-NFO2CREV.mjs} +1 -1
  64. package/dist/{chunk-TCGXG7UA.mjs → chunk-OECEYJNK.mjs} +1 -1
  65. package/dist/{chunk-BEGAJYOY.mjs → chunk-OEJXPUAR.mjs} +1 -1
  66. package/dist/{chunk-FQLIJAUB.mjs → chunk-P2LMCRUN.mjs} +1 -1
  67. package/dist/{chunk-43BZCDGL.mjs → chunk-PQITT2QK.mjs} +1 -1
  68. package/dist/chunk-PQKSXNIZ.mjs +1 -0
  69. package/dist/chunk-RCY5N5KQ.mjs +1 -0
  70. package/dist/{chunk-W62YY5IT.mjs → chunk-RDB75FUD.mjs} +1 -1
  71. package/dist/chunk-RIGP4DAV.mjs +1 -0
  72. package/dist/chunk-RXC7B7SX.mjs +1 -0
  73. package/dist/{chunk-JAMYVQFC.mjs → chunk-T4WUQPBS.mjs} +1 -1
  74. package/dist/chunk-TTOCYOEH.mjs +1 -0
  75. package/dist/chunk-U5NROUVA.mjs +24 -0
  76. package/dist/chunk-UBPJIVWE.mjs +1 -0
  77. package/dist/{chunk-SKM4ZXV5.mjs → chunk-UFU5IA3G.mjs} +1 -1
  78. package/dist/chunk-UIADZXVT.mjs +1 -0
  79. package/dist/chunk-UPEEIAVJ.mjs +1 -0
  80. package/dist/{chunk-P2WAXWAZ.mjs → chunk-V5FCWXMN.mjs} +1 -1
  81. package/dist/chunk-VBH2YQLG.mjs +1 -0
  82. package/dist/chunk-VQ76TWRR.mjs +1 -0
  83. package/dist/chunk-WYQZ7DAK.mjs +1 -0
  84. package/dist/{chunk-N3MHDOMU.mjs → chunk-Y2BJZLYU.mjs} +1 -1
  85. package/dist/chunk-ZC2I35WD.mjs +1 -0
  86. package/dist/cli.mjs +1 -1
  87. package/dist/codex-note-context-2CHDGTG3.mjs +1 -0
  88. package/dist/codex-project-TIMWOCE5.mjs +1 -0
  89. package/dist/{codex-store-mount-WJAATWHT.mjs → codex-store-mount-MAQK6VEG.mjs} +1 -1
  90. package/dist/dev-server-ESGE6QNP.mjs +1 -0
  91. package/dist/{focus-inspection-LGIRFL2T.mjs → focus-inspection-BMDJJC5K.mjs} +1 -1
  92. package/dist/guest-admission.mjs +1 -1
  93. package/dist/guest-live-canvas.mjs +1 -1
  94. package/dist/index.d.mts +5 -5
  95. package/dist/index.mjs +1 -1
  96. package/dist/media.d.mts +3 -3
  97. package/dist/memory-legacy.d.mts +43 -1
  98. package/dist/memory-legacy.mjs +1 -1
  99. package/dist/memory-store.d.mts +5 -162
  100. package/dist/memory-store.mjs +1 -1
  101. package/dist/memory.d.mts +3 -531
  102. package/dist/{page-interaction-TV3P6B3X.mjs → page-interaction-YXHXEYOT.mjs} +1 -1
  103. package/dist/{page-planes-2ZepTpen.d.mts → page-planes-Jz2yR_Wk.d.mts} +246 -2
  104. package/dist/{participantBootstrap-BTcD7XgB.d.mts → participantBootstrap-DDOxY-Cy.d.mts} +2 -2
  105. package/dist/peer-client-LPDWWFT4.mjs +1 -0
  106. package/dist/plugin-astro.d.mts +1 -1
  107. package/dist/plugin-astro.mjs +1 -1
  108. package/dist/plugin-nuxt.mjs +1 -1
  109. package/dist/plugin-vite.d.mts +1 -1
  110. package/dist/plugin-vite.mjs +1 -1
  111. package/dist/server.d.mts +6 -4
  112. package/dist/server.mjs +1 -1
  113. package/dist/shared-page-QN2XRXUE.mjs +1 -0
  114. package/dist/{subjects-D_yanOQ2.d.mts → subjects-cLtt9-iK.d.mts} +12 -0
  115. package/dist/{types-CggBG-H6.d.mts → types-XKO-uva0.d.mts} +1 -1
  116. package/dist/{index-CHp2bgs1.d.mts → validate-0kt2EgVe.d.mts} +7 -40
  117. package/dist/{video-adapter-CWpR4NSt.d.mts → video-adapter-xL95wukX.d.mts} +1 -1
  118. package/infra/phone-pairing/binding.mjs +105 -0
  119. package/infra/phone-pairing/machine-config.mjs +134 -0
  120. package/infra/phone-pairing/machine-service.mjs +159 -0
  121. package/infra/phone-pairing/machine.mjs +98 -0
  122. package/infra/phone-pairing/managed-install.mjs +179 -0
  123. package/package.json +12 -1
  124. package/dist/PagePreviewLayer-AFSRCBAX.mjs +0 -1
  125. package/dist/ParticipantRuntime-ZNEFG34O.mjs +0 -1
  126. package/dist/PhoneHostGate-OCIMKPLM.mjs +0 -1
  127. package/dist/PopmeltTasteConnectedPane-N2A5XPRO.mjs +0 -1
  128. package/dist/SamplePlacementOverlay-EOJW6XGE.mjs +0 -1
  129. package/dist/ShareProjectPane-VYWTF3FW.mjs +0 -1
  130. package/dist/SuppliedContext-3S4HT6U6.mjs +0 -1
  131. package/dist/ThreadErrorCard-CTMVMETS.mjs +0 -1
  132. package/dist/ThreadPanel-G7OKSWD4.mjs +0 -1
  133. package/dist/browser-runtime-Q26JF5EA.mjs +0 -1
  134. package/dist/canvas-chat-note-OLVVP55Y.mjs +0 -1
  135. package/dist/chunk-25EXQOPI.mjs +0 -1
  136. package/dist/chunk-2IWVTTYX.mjs +0 -1
  137. package/dist/chunk-3OGSLX4V.mjs +0 -1
  138. package/dist/chunk-AGCS65LT.mjs +0 -1
  139. package/dist/chunk-AYZUOBFI.mjs +0 -1
  140. package/dist/chunk-B3RA4XAR.mjs +0 -1
  141. package/dist/chunk-BOZVNUHJ.mjs +0 -1
  142. package/dist/chunk-DBCBG5J6.mjs +0 -1
  143. package/dist/chunk-EFWBHWHP.mjs +0 -1
  144. package/dist/chunk-FYURSPM3.mjs +0 -1
  145. package/dist/chunk-G6BN5TAZ.mjs +0 -1
  146. package/dist/chunk-IW7V7WNL.mjs +0 -1
  147. package/dist/chunk-JJK4LAN6.mjs +0 -1
  148. package/dist/chunk-JJRKR4X3.mjs +0 -1
  149. package/dist/chunk-KF73S7MG.mjs +0 -1
  150. package/dist/chunk-KL5ODVJA.mjs +0 -1
  151. package/dist/chunk-L356S4EY.mjs +0 -1
  152. package/dist/chunk-OZBMHEOD.mjs +0 -1
  153. package/dist/chunk-QQPUMPKU.mjs +0 -1
  154. package/dist/chunk-TEXVTTWA.mjs +0 -1
  155. package/dist/chunk-TSQEBZYO.mjs +0 -1
  156. package/dist/chunk-UTP56NCY.mjs +0 -1
  157. package/dist/chunk-VG4ZV2OT.mjs +0 -30
  158. package/dist/chunk-WC7B5NU3.mjs +0 -24
  159. package/dist/chunk-WNOLXY3Y.mjs +0 -1
  160. package/dist/codex-note-context-4X7I5AIJ.mjs +0 -1
  161. package/dist/codex-project-Q6YT5P37.mjs +0 -1
  162. package/dist/dev-server-NROXLQKM.mjs +0 -1
  163. package/dist/peer-client-DWC5F6JN.mjs +0 -1
  164. package/dist/shared-page-GO76UP7I.mjs +0 -1
  165. /package/dist/{chunk-L45FX4SU.mjs → chunk-ERPJ6LXX.mjs} +0 -0
@@ -0,0 +1,134 @@
1
+ // The CLI and the running provisioner share one registry and one writer lock.
2
+ import { existsSync, mkdirSync, rmdirSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import {
6
+ base,
7
+ bind,
8
+ privateDir,
9
+ projectKeyFor,
10
+ readBinding,
11
+ readPrivate,
12
+ route,
13
+ writePrivate,
14
+ } from './binding.mjs';
15
+
16
+ export const machine = join(base, 'machine');
17
+ export const registry = join(machine, 'projects.json');
18
+ export const config = join(machine, 'connector.yml');
19
+ export const routerSocket = join(machine, 'router.sock');
20
+ export const controlSocket = join(machine, 'control.sock');
21
+ const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
22
+
23
+ export function readState() {
24
+ const state = JSON.parse(readPrivate(registry));
25
+ if (!uuid.test(state.tunnel) || !Array.isArray(state.projects))
26
+ throw Error('Invalid machine pairing state.');
27
+ return state;
28
+ }
29
+
30
+ export function routingTable(state) {
31
+ const bindings = state.projects.map(readBinding),
32
+ table = new Map(),
33
+ ports = new Set();
34
+ for (const { id, appOrigin } of bindings) {
35
+ const { hostname, socket } = route(id),
36
+ port = new URL(appOrigin).port;
37
+ if (ports.has(port) || table.has(hostname))
38
+ throw Error('Each project needs its own hostname and loopback app port.');
39
+ ports.add(port);
40
+ table.set(hostname, socket);
41
+ }
42
+ return table;
43
+ }
44
+
45
+ export async function configure(command, args = [], provisionDns, idForKey) {
46
+ privateDir(base);
47
+ privateDir(machine);
48
+ const lock = join(machine, 'provision.lock');
49
+ try {
50
+ mkdirSync(lock, { mode: 0o700 });
51
+ } catch (e) {
52
+ if (e.code === 'EEXIST')
53
+ throw Error(
54
+ 'Another project is being configured. Try again in a moment.',
55
+ );
56
+ throw e;
57
+ }
58
+ try {
59
+ let state;
60
+ try {
61
+ state = readState();
62
+ } catch (e) {
63
+ if (e.code !== 'ENOENT' || command !== 'init' || !uuid.test(args[0]))
64
+ throw e;
65
+ state = { tunnel: args[0], projects: [] };
66
+ }
67
+ if (command === 'init' && state.tunnel !== args[0])
68
+ throw Error('This Mac already has a different named tunnel.');
69
+ const table = routingTable(state);
70
+ let project;
71
+ if (command === 'add') {
72
+ const key = projectKeyFor(args[0]);
73
+ const port = new URL(args[1]).port;
74
+ if (
75
+ state.projects.some(
76
+ (k) => k !== key && new URL(readBinding(k).appOrigin).port === port,
77
+ )
78
+ )
79
+ throw Error(
80
+ 'That loopback app port is already assigned to another project.',
81
+ );
82
+ project = bind(...args, idForKey?.(key));
83
+ const { hostname, socket } = route(project.id);
84
+ if (!state.projects.includes(key)) {
85
+ if (table.has(hostname))
86
+ throw Error('This hostname already belongs to another project.');
87
+ if (provisionDns) await provisionDns(state.tunnel, hostname, key);
88
+ state.projects.push(key);
89
+ table.set(hostname, socket);
90
+ }
91
+ }
92
+ if (command === 'run') state.liveRouting = true;
93
+ const ingress = state.liveRouting
94
+ ? [{ hostname: '*.popmelt.com', service: 'unix:' + routerSocket }]
95
+ : Array.from(table, ([hostname, socket]) => ({
96
+ hostname,
97
+ service: 'unix:' + socket,
98
+ }));
99
+ ingress.push({ service: 'http_status:404' });
100
+ const data =
101
+ JSON.stringify(
102
+ {
103
+ tunnel: state.tunnel,
104
+ 'credentials-file': existsSync(
105
+ join(machine, 'connector-credentials.json'),
106
+ )
107
+ ? join(machine, 'connector-credentials.json')
108
+ : join(homedir(), '.cloudflared', state.tunnel + '.json'),
109
+ ingress,
110
+ },
111
+ null,
112
+ 2,
113
+ ) + '\n';
114
+ const stateData = JSON.stringify(state, null, 2) + '\n';
115
+ function update(file, value) {
116
+ try {
117
+ if (readPrivate(file) === value) return;
118
+ } catch (e) {
119
+ if (e.code !== 'ENOENT') throw e;
120
+ }
121
+ writePrivate(file, value);
122
+ }
123
+ update(registry, stateData);
124
+ update(config, data);
125
+ return {
126
+ tunnel: state.tunnel,
127
+ config,
128
+ projects: table.size,
129
+ ...(project && route(project.id)),
130
+ };
131
+ } finally {
132
+ rmdirSync(lock);
133
+ }
134
+ }
@@ -0,0 +1,159 @@
1
+ import { createServer, request } from 'node:http';
2
+ import { createConnection } from 'node:net';
3
+ import { chmod, lstat, unlink } from 'node:fs/promises';
4
+ import { execFile } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+ import { isAbsolute } from 'node:path';
7
+ import {
8
+ configure,
9
+ controlSocket,
10
+ machine,
11
+ readState,
12
+ routerSocket,
13
+ routingTable,
14
+ } from './machine-config.mjs';
15
+
16
+ const exec = promisify(execFile);
17
+ export async function provisionDns(tunnel, hostname) {
18
+ try {
19
+ await exec('cloudflared', ['tunnel', 'route', 'dns', tunnel, hostname], {
20
+ cwd: machine,
21
+ env: { ...process.env, TUNNEL_FORCE_PROVISIONING_DNS: 'false' },
22
+ timeout: 15000,
23
+ maxBuffer: 65536,
24
+ });
25
+ } catch {
26
+ throw Error(
27
+ 'Cloudflare could not register the project hostname. Retry, or pair over Wi-Fi.',
28
+ );
29
+ }
30
+ }
31
+
32
+ // Only reclaim a socket left by a dead process. A second live service cannot take it.
33
+ async function listen(server, path) {
34
+ try {
35
+ const stat = await lstat(path);
36
+ if (!stat.isSocket() || stat.uid !== process.getuid())
37
+ throw Error('Unexpected entry at ' + path);
38
+ await new Promise((resolve, reject) => {
39
+ const probe = createConnection(path);
40
+ probe.once('connect', () => {
41
+ probe.destroy();
42
+ reject(Error('The pairing service is already running.'));
43
+ });
44
+ probe.once('error', (e) =>
45
+ e.code === 'ECONNREFUSED' ? resolve() : reject(e),
46
+ );
47
+ });
48
+ await unlink(path);
49
+ } catch (e) {
50
+ if (e.code !== 'ENOENT') throw e;
51
+ }
52
+ await new Promise((resolve, reject) => {
53
+ server.once('error', reject);
54
+ server.listen(path, resolve);
55
+ });
56
+ await chmod(path, 0o600);
57
+ }
58
+
59
+ export async function serve(registerDns = provisionDns, idForKey) {
60
+ let routes = routingTable(readState());
61
+ const router = createServer((req, res) => {
62
+ const socket = routes.get(req.headers.host);
63
+ if (!socket) {
64
+ res.writeHead(404).end();
65
+ return;
66
+ }
67
+ // Forward only to a registered project's private gateway, which checks Host
68
+ // again and authenticates every app request. The control socket is separate.
69
+ const upstream = request(
70
+ {
71
+ socketPath: socket,
72
+ path: req.url,
73
+ method: req.method,
74
+ headers: req.headers,
75
+ agent: false,
76
+ },
77
+ (reply) => {
78
+ res.writeHead(reply.statusCode, reply.headers);
79
+ reply.once('error', () => res.destroy());
80
+ reply.pipe(res);
81
+ },
82
+ );
83
+ upstream.once('error', () => {
84
+ if (!res.headersSent) res.writeHead(503, { 'Cache-Control': 'no-store' });
85
+ res.end();
86
+ });
87
+ res.once('close', () => upstream.destroy());
88
+ req.once('error', () => upstream.destroy());
89
+ req.pipe(upstream);
90
+ });
91
+ // Serialize adds, including the DNS operation. Duplicate clicks reuse the
92
+ // persisted binding and never start another connector.
93
+ let tail = Promise.resolve();
94
+ const control = createServer({ requestTimeout: 10000 }, async (req, res) => {
95
+ if (
96
+ req.method !== 'POST' ||
97
+ req.url !== '/projects' ||
98
+ req.headers['content-type'] !== 'application/json'
99
+ ) {
100
+ res.writeHead(404).end();
101
+ return;
102
+ }
103
+ try {
104
+ const chunks = [];
105
+ let size = 0;
106
+ for await (const chunk of req) {
107
+ size += chunk.length;
108
+ if (size > 8192) throw Error('Invalid project registration.');
109
+ chunks.push(chunk);
110
+ }
111
+ const { root, origin } = JSON.parse(
112
+ Buffer.concat(chunks).toString('utf8'),
113
+ );
114
+ if (
115
+ typeof root !== 'string' ||
116
+ !isAbsolute(root) ||
117
+ typeof origin !== 'string'
118
+ )
119
+ throw Error('Invalid project registration.');
120
+ const added = tail.then(async () => {
121
+ const result = await configure(
122
+ 'add',
123
+ [root, origin],
124
+ registerDns,
125
+ idForKey,
126
+ );
127
+ routes = routingTable(readState());
128
+ return result;
129
+ });
130
+ tail = added.catch(() => {});
131
+ const result = await added;
132
+ res
133
+ .writeHead(200, { 'Content-Type': 'application/json' })
134
+ .end(JSON.stringify(result));
135
+ } catch (e) {
136
+ const message = e.message?.includes('loopback app port')
137
+ ? 'This app port is assigned to another paired project.'
138
+ : 'Could not register this project with the Mac’s tunnel. Retry, or pair over Wi-Fi.';
139
+ res
140
+ .writeHead(503, { 'Content-Type': 'application/json' })
141
+ .end(JSON.stringify({ error: message }));
142
+ }
143
+ });
144
+ // cloudflared only receives the router socket. Both are in the user's
145
+ // private directory and the control listener is never bound to TCP.
146
+ await listen(control, controlSocket);
147
+ try {
148
+ await listen(router, routerSocket);
149
+ } catch (e) {
150
+ control.close();
151
+ throw e;
152
+ }
153
+ return () => {
154
+ for (const server of [control, router]) {
155
+ server.close();
156
+ server.closeAllConnections();
157
+ }
158
+ };
159
+ }
@@ -0,0 +1,98 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { enroll, wake, managedDns, credentials } from './managed-install.mjs';
3
+ import { spawn } from 'node:child_process';
4
+ import { request } from 'node:http';
5
+ import { resolve } from 'node:path';
6
+ import {
7
+ configure,
8
+ controlSocket,
9
+ machine,
10
+ readState,
11
+ } from './machine-config.mjs';
12
+ import { serve } from './machine-service.mjs';
13
+
14
+ const [command, ...args] = process.argv.slice(2);
15
+ if (
16
+ !(
17
+ (command === 'init' && args.length === 1) ||
18
+ (command === 'add' && args.length === 2) ||
19
+ (['sync', 'run', 'enroll', 'wake'].includes(command) && !args.length)
20
+ )
21
+ )
22
+ throw Error(
23
+ 'Usage: machine.mjs init <tunnel-uuid> | add <project-directory> <loopback-app-origin> | sync | run',
24
+ );
25
+ if (command === 'enroll' || command === 'wake') {
26
+ try {
27
+ if (command === 'enroll') {
28
+ let invitation = '';
29
+ for await (const chunk of process.stdin) {
30
+ invitation += chunk;
31
+ if (invitation.length > 100) throw Error('Invalid invitation.');
32
+ }
33
+ await enroll(invitation.trim());
34
+ }
35
+ if (!existsSync(credentials)) throw Error('Mac enrollment was not found.');
36
+ await wake();
37
+ } catch (e) {
38
+ console.error(e.message);
39
+ process.exitCode = 1;
40
+ }
41
+ } else if (command === 'run') {
42
+ const remote = existsSync(credentials) ? await managedDns() : undefined;
43
+ const close = await serve(remote?.register, remote?.idForKey);
44
+ try {
45
+ const { config, tunnel } = await configure('run');
46
+ const child = spawn(
47
+ 'cloudflared',
48
+ ['tunnel', '--config', config, 'run', tunnel],
49
+ { cwd: machine, stdio: 'inherit' },
50
+ );
51
+ const stop = () => child.kill('SIGTERM');
52
+ process.once('SIGINT', stop);
53
+ process.once('SIGTERM', stop);
54
+ try {
55
+ const code = await new Promise((resolve, reject) => {
56
+ child.once('error', reject);
57
+ child.once('exit', resolve);
58
+ });
59
+ process.exitCode = code ?? 0;
60
+ } finally {
61
+ process.off('SIGINT', stop);
62
+ process.off('SIGTERM', stop);
63
+ }
64
+ } finally {
65
+ close();
66
+ }
67
+ } else if (command === 'add' && readState().liveRouting) {
68
+ const result = await new Promise((done, fail) => {
69
+ const req = request(
70
+ {
71
+ socketPath: controlSocket,
72
+ path: '/projects',
73
+ method: 'POST',
74
+ headers: { 'Content-Type': 'application/json' },
75
+ signal: AbortSignal.timeout(25000),
76
+ },
77
+ (res) => {
78
+ let body = '';
79
+ res.on('error', fail);
80
+ res.on('data', (chunk) => (body += chunk));
81
+ res.on('end', () =>
82
+ res.statusCode === 200
83
+ ? done(body)
84
+ : fail(
85
+ Error(
86
+ 'Could not register this project with the Mac’s pairing service.',
87
+ ),
88
+ ),
89
+ );
90
+ },
91
+ );
92
+ req.on('error', fail);
93
+ req.end(JSON.stringify({ root: resolve(args[0]), origin: args[1] }));
94
+ });
95
+ console.log(result);
96
+ } else {
97
+ console.log(JSON.stringify(await configure(command, args), null, 2));
98
+ }
@@ -0,0 +1,179 @@
1
+ import {
2
+ createHash,
3
+ createPrivateKey,
4
+ createPublicKey,
5
+ generateKeyPairSync,
6
+ randomBytes,
7
+ sign,
8
+ } from 'node:crypto';
9
+ import { existsSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+ import { createConnection } from 'node:net';
12
+ import { spawn } from 'node:child_process';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { setTimeout as delay } from 'node:timers/promises';
15
+ import { base, privateDir, readPrivate, writePrivate } from './binding.mjs';
16
+ import {
17
+ configure,
18
+ controlSocket,
19
+ machine,
20
+ readState,
21
+ registry,
22
+ } from './machine-config.mjs';
23
+
24
+ const endpoint = 'https://provision-pair.popmelt.com';
25
+ const identityPath = join(machine, 'device.json');
26
+ export const credentials = join(machine, 'connector-credentials.json');
27
+ const hash = (s) => createHash('sha256').update(s).digest('hex');
28
+ export const projectId = (device, key) =>
29
+ hash('popmelt-project-v1:' + device + ':' + key).slice(0, 32);
30
+ const keyService = 'com.popmelt.phone-provisioning';
31
+ const cli = fileURLToPath(new URL('./machine.mjs', import.meta.url));
32
+
33
+ async function identity(create = false) {
34
+ const { AsyncEntry } = await import('@napi-rs/keyring');
35
+ if (!existsSync(identityPath) && create) {
36
+ const { privateKey, publicKey } = generateKeyPairSync('ed25519');
37
+ const key = publicKey
38
+ .export({ type: 'spki', format: 'der' })
39
+ .toString('base64url');
40
+ const entry = new AsyncEntry(keyService, hash(key));
41
+ await entry.setPassword(
42
+ JSON.stringify({
43
+ pk: privateKey
44
+ .export({ type: 'pkcs8', format: 'der' })
45
+ .toString('base64'),
46
+ tunnelSecret: randomBytes(32).toString('base64'),
47
+ }),
48
+ );
49
+ try {
50
+ writePrivate(identityPath, JSON.stringify({ key }), true);
51
+ } catch (error) {
52
+ await entry.deleteCredential();
53
+ if (error.code !== 'EEXIST') throw error;
54
+ }
55
+ }
56
+ const { key } = JSON.parse(readPrivate(identityPath));
57
+ const secret = await new AsyncEntry(keyService, hash(key)).getPassword();
58
+ if (!secret) throw Error('The Mac pairing key is unavailable in Keychain.');
59
+ const { pk, tunnelSecret } = JSON.parse(secret);
60
+ const privateKey = createPrivateKey({
61
+ key: Buffer.from(pk, 'base64'),
62
+ type: 'pkcs8',
63
+ format: 'der',
64
+ });
65
+ if (
66
+ createPublicKey(privateKey)
67
+ .export({ type: 'spki', format: 'der' })
68
+ .toString('base64url') !== key
69
+ )
70
+ throw Error('The Mac pairing key changed.');
71
+ return { key, privateKey, tunnelSecret };
72
+ }
73
+ async function send(device, path, body) {
74
+ const time = Date.now(),
75
+ data = JSON.stringify(body);
76
+ const signature = sign(
77
+ null,
78
+ Buffer.from(['popmelt-phone-v1', path, time, data].join('\n')),
79
+ device.privateKey,
80
+ ).toString('base64url');
81
+ const response = await fetch(endpoint + path, {
82
+ method: 'POST',
83
+ redirect: 'error',
84
+ headers: { 'Content-Type': 'application/json' },
85
+ body: JSON.stringify({ key: device.key, time, data, signature }),
86
+ signal: AbortSignal.timeout(25000),
87
+ });
88
+ if (!response.ok)
89
+ throw Error(
90
+ response.status === 403
91
+ ? 'The remote pairing invitation or device was declined.'
92
+ : response.status === 429
93
+ ? 'This Mac has reached its pilot project limit.'
94
+ : 'Popmelt could not provision remote pairing. Try again.',
95
+ );
96
+ return response.json();
97
+ }
98
+
99
+ export async function enroll(invitation) {
100
+ if (process.platform !== 'darwin' || !/^[A-Za-z0-9_-]{43}$/.test(invitation))
101
+ throw Error('Enter a valid remote pairing invitation.');
102
+ privateDir(base);
103
+ privateDir(machine);
104
+ if (existsSync(registry) && !existsSync(credentials))
105
+ throw Error('This Mac already has a configured tunnel.');
106
+ const device = await identity(true);
107
+ const info = await send(device, '/v1/machine', {
108
+ invitation,
109
+ tunnelSecret: device.tunnelSecret,
110
+ });
111
+ if (
112
+ !/^[a-f0-9]{32}$/.test(info.account) ||
113
+ !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(info.tunnel)
114
+ )
115
+ throw Error('Invalid tunnel registration.');
116
+ if (existsSync(registry) && readState().tunnel !== info.tunnel)
117
+ throw Error('The registered tunnel changed.');
118
+ writePrivate(
119
+ credentials,
120
+ JSON.stringify({
121
+ AccountTag: info.account,
122
+ TunnelID: info.tunnel,
123
+ TunnelSecret: device.tunnelSecret,
124
+ }),
125
+ );
126
+ await configure('init', [info.tunnel]);
127
+ }
128
+
129
+ export async function managedDns() {
130
+ const device = await identity();
131
+ const deviceId = hash(device.key);
132
+ return {
133
+ idForKey: (key) => projectId(deviceId, key),
134
+ register: async (tunnel, hostname, key) => {
135
+ const result = await send(device, '/v1/project', { project: key });
136
+ if (
137
+ result.tunnel !== tunnel ||
138
+ result.id !== projectId(deviceId, key) ||
139
+ hostname !== 'p-' + result.id + '.popmelt.com'
140
+ )
141
+ throw Error('Could not verify the project registration.');
142
+ },
143
+ };
144
+ }
145
+
146
+ function listening() {
147
+ return new Promise((resolve) => {
148
+ const socket = createConnection(controlSocket);
149
+ const finish = (ok) => {
150
+ socket.destroy();
151
+ resolve(ok);
152
+ };
153
+ socket.setTimeout(500, () => finish(false));
154
+ socket.once('connect', () => finish(true));
155
+ socket.once('error', () => finish(false));
156
+ });
157
+ }
158
+ export async function wake() {
159
+ if ((await listening()) && readState().liveRouting) return;
160
+ // The service binds an exclusive socket before launching cloudflared. Concurrent
161
+ // project starts can therefore share a single daemon and connector.
162
+ const child = spawn(process.execPath, [cli, 'run'], {
163
+ cwd: machine,
164
+ detached: true,
165
+ stdio: 'ignore',
166
+ env: {
167
+ HOME: process.env.HOME,
168
+ PATH: process.env.PATH,
169
+ TMPDIR: process.env.TMPDIR,
170
+ },
171
+ });
172
+ child.once('error', () => {});
173
+ child.unref();
174
+ for (let attempt = 0; attempt < 65; attempt++) {
175
+ if ((await listening()) && readState().liveRouting) return;
176
+ await delay(100);
177
+ }
178
+ throw Error('Could not start the remote pairing connector.');
179
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popmelt.com/core",
3
- "version": "0.38.1",
3
+ "version": "0.40.0",
4
4
  "description": "A tiny, powerful design layer for humans and AI",
5
5
  "license": "PolyForm-Shield-1.0.0",
6
6
  "author": "Popmelt <reb@popmelt.com> (https://popmelt.com)",
@@ -28,6 +28,7 @@
28
28
  "node": ">=18.0.0"
29
29
  },
30
30
  "imports": {
31
+ "#phone-pairing-machine": "./infra/phone-pairing/machine.mjs",
31
32
  "#guest-live-canvas": "./dist/guest-live-canvas.mjs",
32
33
  "#guest-admission": "./dist/guest-admission.mjs",
33
34
  "#guest-browser": "./dist/browser.mjs"
@@ -92,6 +93,10 @@
92
93
  "types": "./dist/media.d.mts",
93
94
  "import": "./dist/media.mjs"
94
95
  },
96
+ "./canvas-text": {
97
+ "types": "./dist/canvas-text.d.mts",
98
+ "import": "./dist/canvas-text.mjs"
99
+ },
95
100
  "./three": {
96
101
  "types": "./dist/adapter-three.d.mts",
97
102
  "import": "./dist/adapter-three.mjs"
@@ -103,6 +108,11 @@
103
108
  },
104
109
  "files": [
105
110
  "dist",
111
+ "infra/phone-pairing/binding.mjs",
112
+ "infra/phone-pairing/machine.mjs",
113
+ "infra/phone-pairing/machine-config.mjs",
114
+ "infra/phone-pairing/machine-service.mjs",
115
+ "infra/phone-pairing/managed-install.mjs",
106
116
  "samples",
107
117
  "codex-plugin",
108
118
  "claude-plugin",
@@ -117,6 +127,7 @@
117
127
  "ws": "8.21.3"
118
128
  },
119
129
  "optionalDependencies": {
130
+ "@simplewebauthn/server": "14.1.0",
120
131
  "@napi-rs/keyring": "2.1.0"
121
132
  },
122
133
  "peerDependencies": {
@@ -1 +0,0 @@
1
- "use client";export{f as PagePreviewLayer}from"./chunk-L356S4EY.mjs";import"./chunk-KL5ODVJA.mjs";import"./chunk-AWWUJO3N.mjs";import"./chunk-Q6N77LIS.mjs";import"./chunk-ZVDKW7TO.mjs";import"./chunk-FHCKFQBY.mjs";import"./chunk-APP5IYTE.mjs";import"./chunk-TMSGNHXH.mjs";import"./chunk-53SKVMWR.mjs";import"./chunk-5IZHN3A7.mjs";import"./chunk-AOTDTBQO.mjs";import"./chunk-WP2SHSCG.mjs";import"./chunk-LH7HKUCK.mjs";import"./chunk-Q6C7ZA3H.mjs";import"./chunk-WJVRGXOS.mjs";import"./chunk-BEGAJYOY.mjs";import"./chunk-AGCS65LT.mjs";import"./chunk-SUAHDXJZ.mjs";import"./chunk-YGP6PPOZ.mjs";
@@ -1 +0,0 @@
1
- "use client";import{d as t,b as e,c as o,a as r}from"./chunk-GTVTUWGH.mjs";import"./chunk-SKM4ZXV5.mjs";import"./chunk-TXL2CR66.mjs";import{f as i}from"./chunk-WC7B5NU3.mjs";import"./chunk-ZHXTB5IN.mjs";import"./chunk-FYURSPM3.mjs";import"./chunk-43BZCDGL.mjs";import"./chunk-PH2MLB3T.mjs";import"./chunk-ZVDKW7TO.mjs";import"./chunk-XTOCFTVW.mjs";import"./chunk-KHDXOXYF.mjs";import"./chunk-SOGN7S54.mjs";import"./chunk-BJUSVIDN.mjs";import"./chunk-WNOLXY3Y.mjs";import{a as n}from"./chunk-JAMYVQFC.mjs";import{i as a,Y as s}from"./chunk-G6BN5TAZ.mjs";import"./chunk-B3RA4XAR.mjs";import"./chunk-DBCBG5J6.mjs";import"./chunk-G2ZHJXHZ.mjs";import"./chunk-TMSGNHXH.mjs";import"./chunk-53SKVMWR.mjs";import"./chunk-3LZQLRZ2.mjs";import"./chunk-RJWFSAKE.mjs";import"./chunk-P2WAXWAZ.mjs";import"./chunk-2F2BVGFH.mjs";import"./chunk-RWZ7SVMO.mjs";import"./chunk-RK6UROPO.mjs";import"./chunk-5IZHN3A7.mjs";import"./chunk-AOTDTBQO.mjs";import"./chunk-HAZXZ5TU.mjs";import"./chunk-TVIKC33M.mjs";import"./chunk-25EXQOPI.mjs";import"./chunk-VXRRHXUP.mjs";import"./chunk-WP2SHSCG.mjs";import{e as c,g as l,f as p}from"./chunk-AAMUU2QA.mjs";import"./chunk-LH7HKUCK.mjs";import{a as m}from"./chunk-3OGSLX4V.mjs";import{b as h,f as u,c as d,d as f}from"./chunk-3VOEPWRL.mjs";import{o as j}from"./chunk-QQPUMPKU.mjs";import"./chunk-X6I6KQDG.mjs";import"./chunk-ATLUO4G7.mjs";import"./chunk-JJRKR4X3.mjs";import"./chunk-C2ZSNUXQ.mjs";import"./chunk-TEXVTTWA.mjs";import"./chunk-Q6C7ZA3H.mjs";import"./chunk-EILBHZDX.mjs";import"./chunk-XJJDBMZI.mjs";import"./chunk-OREALBUO.mjs";import"./chunk-B4DYUYX4.mjs";import"./chunk-CK3CDA3L.mjs";import{c as k,a as g}from"./chunk-WJVRGXOS.mjs";import"./chunk-BEGAJYOY.mjs";import"./chunk-AGCS65LT.mjs";import{U as w}from"./chunk-OA63PYHZ.mjs";import"./chunk-6RMM7JB6.mjs";import{b as y}from"./chunk-SUAHDXJZ.mjs";import"./chunk-PRPXMDZ7.mjs";import"./chunk-A4GARXVQ.mjs";import"./chunk-YGP6PPOZ.mjs";import{useState as S,useSyncExternalStore as v,useEffect as I}from"react";import{jsx as P,jsxs as A}from"react/jsx-runtime";function O(t,i){let n,a={phase:"starting"},m=0,j=!1,k=!1,g=0,w=new Set,S=`popmelt-participant:${t.projectId}`,v=new h(t.url,t.projectId),I=t=>{if(!k){a=t;for(let t of w)t()}},P=()=>history.state?.popmeltGuestEntry===t.projectId,A=e=>history.replaceState({...history.state,popmeltGuestEntry:t.projectId},"",e),O=t=>fetch("/__popmelt/host",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify(t),redirect:"error"}),X=async(e={},o=!1,r)=>{if(y(t.url))return null;let i=await O(e);if(403===i.status){let e=i.headers.get("X-Popmelt-Host-Origin"),n=i.headers.get("X-Popmelt-Session"),a=new URL(location.href);if(!o||!n||window.top!==window||!["localhost","127.0.0.1","[::1]"].includes(a.hostname)||a.pathname.startsWith("/__popmelt/")||a.searchParams.has("__popmelt_code_preview")||a.hash.includes("popmelt-")||P())return null;let s=localStorage.getItem(`popmelt-admission:${t.projectId}`);if(s)try{if(JSON.parse(s)?.receipt)return null}catch{return null}if(e&&function(t,e){try{let o=new URL(t),r=new URL(e),i=["localhost","127.0.0.1","[::1]"];return o.origin===t&&r.origin===e&&t!==e&&["http:","https:"].includes(o.protocol)&&o.protocol===r.protocol&&o.port===r.port&&i.includes(o.hostname)&&i.includes(r.hostname)}catch{return!1}}(location.origin,e)){let t=await fetch(e+"/__popmelt/host",{method:"HEAD",credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(2e3)}).catch(()=>null);if(!k&&204===t?.status&&t.headers.get("X-Popmelt-Session")===n)throw a.host=new URL(e).host,location.replace(a.href),H;return null}let c=i.headers.get("X-Popmelt-Local-Port");if(!c||!/^[1-9]\d{0,4}$/.test(c)||Number(c)>65535)return null;let l=await fetch("http://127.0.0.1:"+c+"/",{method:"POST",headers:{"X-Popmelt-Session":n},credentials:"omit",cache:"no-store",redirect:"error",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(6500)}).catch(()=>null);if(!l?.ok||k)return null;let p=await l.json().catch(()=>null);if("string"!=typeof p?.proof||(i=await O({localProof:p.proof,previousId:r}),403===i.status))return null}if(!i.ok)throw new Error(`Host entry unavailable (${i.status}).`);let n=`popmelt-before-participants:${t.projectId}`;return null===localStorage.getItem(n)&&localStorage.setItem(n,JSON.stringify(Object.fromEntries(Object.values(s(t.projectId)).map(t=>[t,localStorage.getItem(t)])))),await i.json()},H=Symbol("navigating"),R=async(a,s=g)=>{if(k||s!==g)return;let m=await r({bridgeUrl:t.url,projectId:t.projectId,credential:a,runtimeStorage:sessionStorage,observedSource:{sourceId:t.projectId,revision:t.revision},loadOwnSource:i,prepareApplication:t.planeApps?async r=>{if(k||s!==g)throw H;let i=c(location.pathname);if(r.author.id===a.participantId&&"host"===r.author.relationship&&!y(t.url)){if("/"!==i){let t=new URL(location.href);throw t.pathname=p(t.pathname),location.replace(t.href),H}return("/"===r.ownWorkspace?.basePath?r.ownWorkspace.revision:void 0)??r.draft.source?.revision??t.revision}let n=await e(a,a.participantId,void 0,location.pathname);if(k||s!==g)throw H;let m=o(n.application);if(t.appVersion??(t.appVersion=n.application.version),m!==l(location.pathname)||t.appVersion&&t.appVersion!==n.application.version)throw localStorage.setItem(S,JSON.stringify(a)),location.replace(m+location.search+location.hash),H;return n.application.basis??t.revision}:void 0}).catch(t=>{if(t!==H)throw t});if(m){if(k||s!==g)return void m.dispose();try{localStorage.setItem(S,JSON.stringify(a))}catch(t){throw m.dispose(),t}if(n?.dispose(),P()){let t={...history.state};delete t.popmeltGuestEntry,history.replaceState(t,"")}n=m,I({phase:"connected",connection:m}),X({credential:a}).catch(()=>{})}},b=()=>{A(location.href),g++,n?.dispose(),n=void 0,function(t,e){t.removeItem(`popmelt-participant:${e}`);let o,r=`popmelt-admission:${e}`;try{o=JSON.parse(t.getItem(r)??"null")}catch{return void t.removeItem(r)}o&&"object"==typeof o&&t.setItem(r,JSON.stringify({name:o.name,colorIdentity:o.colorIdentity??o.receipt}))}(localStorage,t.projectId),I({phase:"entry",invitation:null})};return{client:v,getSnapshot:()=>a,subscribe:t=>(w.add(t),()=>{w.delete(t)}),retain(){if(k)throw new Error("Participant lifecycle is disposed");m++,j||(j=!0,(async()=>{let t=u(location.href),e=new URL(t.cleanUrl),o=new URLSearchParams(e.hash.slice(1)),r=o.get("popmelt-host");o.delete("popmelt-host"),r&&(e.hash=o.toString()),t.token?A(e.href):e.href!==location.href&&history.replaceState(history.state,"",e);let i=null;if(r){if(i=await X({token:r}),!i&&!t.token&&(i=await X({},!0)),!i)throw new Error("Host entry expired. Use the current private host link.")}else if(!t.token&&!P()){try{i=JSON.parse(localStorage.getItem(S)??"null")}catch{}i??(i=await X({},!0))}if(k)return;if(!i)return void I({phase:"entry",invitation:t.token??null});let n=g;for(let e=1;!k&&n===g;e++)try{return void await R(i,n)}catch(o){if(k||n!==g)return;if(d(o)){I({phase:"error",message:o.message}),await new Promise(t=>setTimeout(t,f(e)));continue}if("access_removed"===o.code)return void b();if(401!==o.status)throw o;let a=await X({},!r&&!t.token,i.participantId);return void(a?await R(a):b())}})().catch(t=>{t!==H&&I({phase:"error",message:t.message})}));let t=!1;return()=>{t||(t=!0,m--,queueMicrotask(()=>{m||k||(k=!0,g++,n?.dispose(),n=void 0,w.clear())}))}},removed:b,async join(e,o){if("entry"!==a.phase||!a.invitation||k)throw new Error("No active invitation");if(!o)throw new Error("Peer identity is not ready");let r=g,i=await v.joinOrRequestAdmission(a.invitation,e,o);if(!k&&r===g){if("admission"in i)return localStorage.setItem(`popmelt-admission:${t.projectId}`,JSON.stringify({name:i.admission.name,receipt:o,colorIdentity:o})),void I({phase:"entry",invitation:null});await R(i.joined.credential,r)}},admit:t=>R(t)}}function X({config:r,loadOwnSource:s,children:p}){let[h]=S(()=>O(r,s)),u=a(),d=v(h.subscribe,h.getSnapshot,h.getSnapshot);I(()=>h.retain(),[h]);let[f,X,H]=k(),R="connected"===d.phase?d.connection:null;if(I(()=>{if(!R||!r.planeApps)return;let t,i=new AbortController,n=R.isHost&&!y(r.url)&&"/"===c(location.pathname),a=n?void 0:r.appVersion,s=async()=>{try{let t=await e(R.credential,R.credential.participantId,i.signal,location.pathname);if(n&&"/"!==t.application.basePath)throw new Error("Host checkout unavailable");let s=o(t.application);if(a??(a=t.application.version),!i.signal.aborted&&(s!==l(location.pathname)||t.application.version!==a)){if(R.isHost&&!y(r.url)){let t=await fetch(s+location.search,{method:"HEAD",headers:{Accept:"text/html"},mode:"same-origin",cache:"no-store",signal:i.signal});if(!t.ok||!t.headers.get("content-type")?.includes("text/html")||l(new URL(t.url).pathname)!==s)throw new Error("Host plane document unavailable")}return await R.state.flush(),void(i.signal.aborted||(s===l(location.pathname)?location.reload():location.replace(s+location.search+location.hash)))}}catch{}i.signal.aborted||(t=setTimeout(s,1500))};return s(),()=>{i.abort(),clearTimeout(t)}},[r.planeApps,r.appVersion,r.url,R,u]),R)return P(t,{connection:R,codePreviewUrl:location.href,planeApps:r.planeApps,onAccessRemoved:h.removed,children:p});let b="starting"===d.phase||"error"===d.phase,U="entry"===d.phase?d.invitation:null;return P(n,{children:P("div",{"data-devtools":"participant-entry",style:{display:"contents",pointerEvents:"auto"},children:b?P(i,{entry:{theme:f,themePreference:H,onThemePreferenceChange:X,ariaLabel:"starting"===d.phase?"Popmelt connecting":"Popmelt disconnected",action:null,logoOnly:!0,connected:!1,connection:A("span",{"data-popmelt-entry-content":!0,role:"status",style:{...j(g[f],!1),cursor:"default"},children:[P(w,{size:14,strokeWidth:1.5,"aria-hidden":"true"}),"starting"===d.phase?"Connecting…":"Disconnected"]})}}):P(m,{showHostLinkHelp:window.top===window&&["localhost","127.0.0.1","[::1]"].includes(location.hostname)&&!y(r.url)&&"/"===c(location.pathname),client:h.client,storage:localStorage,storageKey:`popmelt-admission:${r.projectId}`,theme:f,themePreference:H,onThemePreferenceChange:X,onAdmitted:h.admit,onJoin:U?h.join:void 0},U??"request-access")})})}export{X as default};
@@ -1 +0,0 @@
1
- "use client";import{a as r,d as t}from"./chunk-GTVTUWGH.mjs";import"./chunk-SKM4ZXV5.mjs";import"./chunk-TXL2CR66.mjs";import"./chunk-KHDXOXYF.mjs";import"./chunk-SOGN7S54.mjs";import"./chunk-BJUSVIDN.mjs";import"./chunk-WNOLXY3Y.mjs";import"./chunk-G6BN5TAZ.mjs";import"./chunk-B3RA4XAR.mjs";import"./chunk-DBCBG5J6.mjs";import"./chunk-G2ZHJXHZ.mjs";import"./chunk-TMSGNHXH.mjs";import"./chunk-53SKVMWR.mjs";import"./chunk-3LZQLRZ2.mjs";import"./chunk-RJWFSAKE.mjs";import"./chunk-P2WAXWAZ.mjs";import"./chunk-2F2BVGFH.mjs";import"./chunk-RWZ7SVMO.mjs";import"./chunk-RK6UROPO.mjs";import"./chunk-5IZHN3A7.mjs";import"./chunk-AOTDTBQO.mjs";import"./chunk-HAZXZ5TU.mjs";import"./chunk-TVIKC33M.mjs";import"./chunk-25EXQOPI.mjs";import"./chunk-VXRRHXUP.mjs";import"./chunk-WP2SHSCG.mjs";import"./chunk-AAMUU2QA.mjs";import"./chunk-LH7HKUCK.mjs";import"./chunk-3VOEPWRL.mjs";import"./chunk-EILBHZDX.mjs";import"./chunk-XJJDBMZI.mjs";import"./chunk-OREALBUO.mjs";import"./chunk-B4DYUYX4.mjs";import"./chunk-CK3CDA3L.mjs";import"./chunk-WJVRGXOS.mjs";import{b as o}from"./chunk-BEGAJYOY.mjs";import{d as n,f as i,c as m,a as e}from"./chunk-AGCS65LT.mjs";import"./chunk-OA63PYHZ.mjs";import"./chunk-6RMM7JB6.mjs";import"./chunk-SUAHDXJZ.mjs";import"./chunk-PRPXMDZ7.mjs";import"./chunk-YGP6PPOZ.mjs";import{useState as c,useEffect as s,cloneElement as p}from"react";import{jsxs as h,jsx as u}from"react/jsx-runtime";function j({children:j,projectId:k,participantConfig:a}){let[l,d]=c(null),[A,I]=c("");if(s(()=>{let t,m,c=!1;return d(null),I(""),n(k).then(async n=>{if(c)return;let s=location.origin+e;m=i(s,n);let p=await o(s+"/status",{signal:AbortSignal.timeout(6e3)}),h=p.ok?await p.json():null;if(h?.projectId!==n.projectId)throw new Error("Phone access expired. Create a fresh pairing link in the project terminal.");if(!c){if(h.phoneParticipantId)t=await r({projectId:n.projectId,bridgeUrl:s,credential:{participantId:h.phoneParticipantId,token:""},runtimeStorage:sessionStorage,observedSource:{sourceId:n.projectId,revision:a?.revision??"unversioned"}});else if(a)throw new Error("This phone is not connected to the multiplayer host.");c?t?.dispose():d({bridgeUrl:s,projectId:n.projectId,connection:t})}}).catch(r=>{m?.(),c||I(r instanceof Error?r.message:"Phone pairing failed.")}),()=>{c=!0,t?.dispose(),m?.()}},[k,a]),A)return h("p",{role:"alert","data-devtools":"phone-pairing-error",children:[A," ",u("button",{type:"button",onClick:m,children:"Forget this pairing"})]});if(!l)return null;let X=p(j,{bridgeUrl:l.bridgeUrl,projectId:l.projectId});return l.connection?u(t,{connection:l.connection,onAccessRemoved:m,children:X}):X}export{j as PhoneHostGate};