thebird 1.2.45 → 1.2.47

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/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ### Added
4
+ - `docs/shell.js`: `createShell({ term, onPreviewWrite })` — POSIX shell + Node REPL using browser V8 eval + xstate v5 state machine. Dispatch table of built-ins: ls, cat, echo, pwd, cd, mkdir, rm, cp, mv, env, export, clear, help, node, npm install, exit. Pipe support via ` | ` split. `window.__debug.shell` exposes state, cwd, env, history, httpHandlers, nodeMode. `http.createServer` polyfill registers handlers in httpHandlers map.
5
+ - `docs/shell-node.js`: `createNodeEnv({ ctx, term })` — persistent V8 eval scope with process, console, require (IDB node_modules), Buffer shim, http.createServer polyfill, fetch, timers.
6
+ - `docs/vendor/xstate.js`: replaced broken stub with self-contained 46KB jsdelivr bundle (xstate@5.30.0) exporting createMachine, createActor — no external imports.
7
+
3
8
  ### Fixed
4
9
  - Gemini tool result wrapping: string results wrapped as `{ output: result }` to satisfy Gemini Struct requirement for `function_response.response`
5
10
  - Browser bundle rebuilt with fix
@@ -0,0 +1,22 @@
1
+ const SW_PATH = new URL('./preview-sw.js', import.meta.url).href;
2
+ const SCOPE = new URL('./preview/', import.meta.url).href;
3
+
4
+ window.__debug = window.__debug || {};
5
+ window.__debug.sw = { registered: false, error: null };
6
+
7
+ export async function registerPreviewSW() {
8
+ if (!('serviceWorker' in navigator)) {
9
+ window.__debug.sw.error = 'unsupported';
10
+ throw new Error('ServiceWorker not supported');
11
+ }
12
+ try {
13
+ const reg = await navigator.serviceWorker.register(SW_PATH, { scope: SCOPE });
14
+ await navigator.serviceWorker.ready;
15
+ window.__debug.sw.registered = true;
16
+ window.__debug.sw.registration = reg;
17
+ return reg;
18
+ } catch (err) {
19
+ window.__debug.sw.error = err.message;
20
+ throw err;
21
+ }
22
+ }
@@ -0,0 +1,48 @@
1
+ const MIME = {
2
+ '.html': 'text/html',
3
+ '.js': 'application/javascript',
4
+ '.css': 'text/css',
5
+ '.json': 'application/json',
6
+ '.txt': 'text/plain',
7
+ };
8
+
9
+ function getMime(key) {
10
+ const ext = key.slice(key.lastIndexOf('.'));
11
+ return MIME[ext] || 'application/octet-stream';
12
+ }
13
+
14
+ function openIDB() {
15
+ return new Promise((resolve, reject) => {
16
+ const req = indexedDB.open('thebird', 1);
17
+ req.onsuccess = () => resolve(req.result);
18
+ req.onerror = () => reject(req.error);
19
+ });
20
+ }
21
+
22
+ function getFS(db) {
23
+ return new Promise((resolve, reject) => {
24
+ const tx = db.transaction('fs', 'readonly');
25
+ const store = tx.objectStore('fs');
26
+ const req = store.get('thebird_fs_v2');
27
+ req.onsuccess = () => resolve(req.result ? JSON.parse(req.result) : {});
28
+ req.onerror = () => reject(req.error);
29
+ });
30
+ }
31
+
32
+ self.addEventListener('install', () => self.skipWaiting());
33
+ self.addEventListener('activate', e => e.waitUntil(self.clients.claim()));
34
+
35
+ self.addEventListener('fetch', e => {
36
+ const url = new URL(e.request.url);
37
+ const idx = url.pathname.indexOf('/preview/');
38
+ if (idx === -1) return;
39
+ const key = url.pathname.slice(idx + '/preview/'.length);
40
+ e.respondWith(
41
+ openIDB()
42
+ .then(db => getFS(db))
43
+ .then(fs => {
44
+ if (!(key in fs)) return new Response('not found: ' + key, { status: 404 });
45
+ return new Response(fs[key], { status: 200, headers: { 'Content-Type': getMime(key) } });
46
+ })
47
+ );
48
+ });
@@ -0,0 +1,54 @@
1
+ export function createNodeEnv({ ctx, term }) {
2
+ const scope = {
3
+ process: {
4
+ argv: [],
5
+ env: ctx.env,
6
+ cwd: () => ctx.cwd,
7
+ exit: code => term.write('[exit ' + code + ']\r\n'),
8
+ },
9
+ console: {
10
+ log: (...a) => term.write(a.map(String).join(' ') + '\r\n'),
11
+ error: (...a) => term.write('\x1b[31m' + a.map(String).join(' ') + '\x1b[0m\r\n'),
12
+ warn: (...a) => term.write('\x1b[33m' + a.map(String).join(' ') + '\x1b[0m\r\n'),
13
+ },
14
+ require: id => {
15
+ const key = 'node_modules/' + id + '/index.js';
16
+ const src = (window.__debug.idbSnapshot || {})[key];
17
+ if (src == null) throw new Error('module not found: ' + id);
18
+ const mod = { exports: {} };
19
+ new Function('module', 'exports', 'require', src)(mod, mod.exports, scope.require);
20
+ return mod.exports;
21
+ },
22
+ setTimeout, setInterval, clearTimeout, clearInterval, fetch,
23
+ Buffer: {
24
+ from: (s, enc) => enc === 'base64'
25
+ ? new Uint8Array(atob(s).split('').map(c => c.charCodeAt(0)))
26
+ : new TextEncoder().encode(s),
27
+ toString: (buf, enc) => enc === 'base64'
28
+ ? btoa(String.fromCharCode(...buf))
29
+ : new TextDecoder().decode(buf),
30
+ },
31
+ get __filename() { return ctx.cwd + '/repl'; },
32
+ get __dirname() { return ctx.cwd; },
33
+ http: {
34
+ createServer: handler => ({
35
+ listen: (port, cb) => {
36
+ window.__debug.shell.httpHandlers[port] = handler;
37
+ term.write('listening on :' + port + '\r\n');
38
+ cb?.();
39
+ },
40
+ }),
41
+ },
42
+ };
43
+
44
+ return async function nodeEval(code, filename) {
45
+ try {
46
+ const keys = Object.keys(scope);
47
+ const vals = Object.values(scope);
48
+ const fn = new Function(...keys, 'return (async () => {\n' + code + '\n})()');
49
+ await fn(...vals);
50
+ } catch (e) {
51
+ term.write('\x1b[31m' + (filename ? filename + ': ' : '') + e.message + '\x1b[0m\r\n');
52
+ }
53
+ };
54
+ }
package/docs/shell.js ADDED
@@ -0,0 +1,164 @@
1
+ import { createMachine, createActor } from './vendor/xstate.js';
2
+ import { createNodeEnv } from './shell-node.js';
3
+
4
+ function resolvePath(cwd, p) {
5
+ if (!p || p === '~') return '/';
6
+ if (p.startsWith('~/')) p = '/' + p.slice(2);
7
+ if (!p.startsWith('/')) p = cwd.replace(/\/$/, '') + '/' + p;
8
+ const parts = [];
9
+ for (const s of p.split('/')) {
10
+ if (s === '..') parts.pop();
11
+ else if (s && s !== '.') parts.push(s);
12
+ }
13
+ return '/' + parts.join('/');
14
+ }
15
+
16
+ function makeBuiltins(ctx) {
17
+ const snap = () => window.__debug.idbSnapshot || {};
18
+ const w = s => ctx.term.write(s);
19
+ const wl = s => w(s + '\r\n');
20
+ return {
21
+ ls: ([p]) => {
22
+ const prefix = resolvePath(ctx.cwd, p || '') + '/';
23
+ const keys = prefix === '//' ? Object.keys(snap()) : Object.keys(snap()).filter(k => k.startsWith(prefix === '//' ? '/' : prefix));
24
+ wl(keys.join('\r\n') || '(empty)');
25
+ },
26
+ cat: ([f]) => {
27
+ const c = snap()[resolvePath(ctx.cwd, f)];
28
+ if (c == null) throw new Error('no such file: ' + f);
29
+ wl(c);
30
+ },
31
+ echo: args => wl(args.join(' ')),
32
+ pwd: () => wl(ctx.cwd),
33
+ cd: ([p]) => { ctx.cwd = resolvePath(ctx.cwd, p || '~'); },
34
+ mkdir: ([p]) => {
35
+ window.__debug.idbSnapshot[resolvePath(ctx.cwd, p) + '/.keep'] = '';
36
+ window.__debug.idbPersist?.();
37
+ },
38
+ rm: ([f]) => {
39
+ delete window.__debug.idbSnapshot[resolvePath(ctx.cwd, f)];
40
+ window.__debug.idbPersist?.();
41
+ },
42
+ cp: ([s, d]) => {
43
+ window.__debug.idbSnapshot[resolvePath(ctx.cwd, d)] = snap()[resolvePath(ctx.cwd, s)];
44
+ window.__debug.idbPersist?.();
45
+ },
46
+ mv: ([s, d]) => {
47
+ const src = resolvePath(ctx.cwd, s), dst = resolvePath(ctx.cwd, d);
48
+ window.__debug.idbSnapshot[dst] = snap()[src];
49
+ delete window.__debug.idbSnapshot[src];
50
+ window.__debug.idbPersist?.();
51
+ },
52
+ env: () => wl(Object.entries(ctx.env).map(([k, v]) => k + '=' + v).join('\r\n')),
53
+ export: ([kv]) => { const [k, ...v] = (kv || '').split('='); ctx.env[k] = v.join('='); },
54
+ clear: () => ctx.term.clear(),
55
+ help: () => wl(Object.keys(makeBuiltins(ctx)).join(' ')),
56
+ exit: () => { if (ctx.nodeMode) { ctx.nodeMode = false; wl('[shell]'); } },
57
+ node: async ([file]) => {
58
+ if (!file) { ctx.nodeMode = true; wl('[node repl — type exit to return]'); return; }
59
+ const path = resolvePath(ctx.cwd, file);
60
+ const code = snap()[path];
61
+ if (code == null) throw new Error('no such file: ' + path);
62
+ await ctx.nodeEval(code, path);
63
+ },
64
+ npm: async args => {
65
+ if (args[0] !== 'install') throw new Error('only npm install supported');
66
+ const pkg = args[1];
67
+ if (!pkg) throw new Error('npm install <pkg>');
68
+ w('fetching ' + pkg + '...\r\n');
69
+ const r = await fetch('https://esm.sh/' + pkg);
70
+ if (!r.ok) throw new Error('fetch failed: ' + r.status);
71
+ const key = 'node_modules/' + pkg + '/index.js';
72
+ window.__debug.idbSnapshot[key] = await r.text();
73
+ window.__debug.idbPersist?.();
74
+ wl('installed ' + pkg);
75
+ },
76
+ };
77
+ }
78
+
79
+ const machine = createMachine({ id: 'shell', initial: 'idle', states: {
80
+ idle: { on: { RUN: 'executing' } },
81
+ executing: { on: { DONE: 'idle', ERROR: 'idle' } },
82
+ }});
83
+
84
+ export function createShell({ term, onPreviewWrite }) {
85
+ const ctx = { term, cwd: '/', env: {}, nodeMode: false, history: [], httpHandlers: {} };
86
+ const BUILTINS = makeBuiltins(ctx);
87
+ ctx.nodeEval = createNodeEnv({ ctx, term });
88
+
89
+ const actor = createActor(machine);
90
+ actor.start();
91
+
92
+ window.__debug = window.__debug || {};
93
+ window.__debug.shell = {
94
+ get state() { return actor.getSnapshot().value; },
95
+ get cwd() { return ctx.cwd; },
96
+ get env() { return ctx.env; },
97
+ get history() { return ctx.history; },
98
+ httpHandlers: ctx.httpHandlers,
99
+ get nodeMode() { return ctx.nodeMode; },
100
+ };
101
+
102
+ async function runCmd(line, capture) {
103
+ if (!line.trim()) return '';
104
+ const [cmd, ...args] = line.trim().split(/\s+/);
105
+ const fn = BUILTINS[cmd];
106
+ if (!capture) {
107
+ if (fn) await fn(args); else term.write('command not found: ' + cmd + '\r\n');
108
+ return '';
109
+ }
110
+ let out = '';
111
+ const orig = term.write.bind(term);
112
+ term.write = s => { out += s; };
113
+ try { if (fn) await fn(args); else out += 'command not found: ' + cmd + '\r\n'; }
114
+ finally { term.write = orig; }
115
+ return out;
116
+ }
117
+
118
+ async function run(line) {
119
+ if (!line.trim()) return;
120
+ ctx.history.push(line);
121
+ if (ctx.nodeMode && line.trim() !== 'exit') { await ctx.nodeEval(line); return; }
122
+ if (line.trim() === 'exit') { BUILTINS.exit([]); return; }
123
+ actor.send({ type: 'RUN' });
124
+ try {
125
+ const parts = line.split(' | ');
126
+ if (parts.length > 1) {
127
+ let buf = await runCmd(parts[0], true);
128
+ for (const p of parts.slice(1)) {
129
+ const [cmd, ...args] = p.trim().split(/\s+/);
130
+ const fn = BUILTINS[cmd];
131
+ if (fn) await fn([buf, ...args]); else term.write('command not found: ' + cmd + '\r\n');
132
+ buf = '';
133
+ }
134
+ } else {
135
+ await runCmd(line, false);
136
+ }
137
+ actor.send({ type: 'DONE' });
138
+ } catch (e) {
139
+ term.write('\x1b[31m' + e.message + '\x1b[0m\r\n');
140
+ actor.send({ type: 'ERROR' });
141
+ }
142
+ }
143
+
144
+ const prompt = () => term.write('\r\n\x1b[32m' + ctx.cwd + ' $ \x1b[0m');
145
+ let buf = '';
146
+ term.onData(async data => {
147
+ if (data === '\r') {
148
+ term.write('\r\n');
149
+ const line = buf;
150
+ buf = '';
151
+ await run(line);
152
+ prompt();
153
+ } else if (data === '\x7f') {
154
+ if (buf.length) { buf = buf.slice(0, -1); term.write('\x08 \x08'); }
155
+ } else {
156
+ buf += data;
157
+ term.write(data);
158
+ }
159
+ });
160
+
161
+ onPreviewWrite && (window.__debug.shell.onPreviewWrite = onPreviewWrite);
162
+ prompt();
163
+ return { run };
164
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0.
3
+ * Original file: /npm/xstate@5.30.0/dist/xstate.esm.js
4
+ *
5
+ * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
6
+ */
7
+ var t="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function e(){const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==t?t:void 0;if(e.__xstate__)return e.__xstate__}const s=t=>{if("undefined"==typeof window)return;const s=e();s&&s.register(t)};class n{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const o="xstate.init",i="xstate.stop";function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function c(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function a(t){return{type:o,input:t}}function u(t){setTimeout((()=>{throw t}))}const h="function"==typeof Symbol&&Symbol.observable||"@@observable";function f(t,e){const s=p(t),n=p(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every((t=>t in n&&f(s[t],n[t])))}function d(t){if(_(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function p(t){if(Lt(t))return t.value;if("string"!=typeof t)return t;return l(d(t))}function l(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}function y(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}function g(t){return _(t)?t:[t]}function v(t){return void 0===t?[]:g(t)}function m(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function _(t){return Array.isArray(t)}function b(t){return g(t).map((t=>void 0===t||"string"==typeof t?{target:t}:t))}function x(t){if(void 0!==t&&""!==t)return v(t)}function S(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function w(t,e){return`${e}.${t}`}function I(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[n]:i).src}function k(t){return[...new Set([...t._nodes.flatMap((t=>t.ownEvents))])]}function E(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}function $(t,e){return`${t.sessionId}.${e}`}let T=0;let O=!1;let j=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const A={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class N{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new n(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=j.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const s={...A,...e},{clock:o,logger:i,parent:r,syncSnapshot:c,id:a,systemId:h,inspect:f}=s;this.system=r?r.system:function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,r={},{clock:c,logger:a}=e,u={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},a=$(t,o);h._snapshot._scheduledEvents[a]=i;const u=c.setTimeout((()=>{delete r[a],delete h._snapshot._scheduledEvents[a],h._relay(t,e,s)}),n);r[a]=u},cancel:(t,e)=>{const s=$(t,e),n=r[s];delete r[s],delete h._snapshot._scheduledEvents[s],void 0!==n&&c.clearTimeout(n)},cancelAll:t=>{for(const e in h._snapshot._scheduledEvents){const s=h._snapshot._scheduledEvents[e];s.source===t&&u.cancel(t,s.id)}}},h={_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+T++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.delete(e),o.delete(t))},get:t=>n.get(t),getAll:()=>Object.fromEntries(n.entries()),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=S(t);return i.add(e),{unsubscribe(){i.delete(e)}}},_sendInspectionEvent:e=>{if(!i.size)return;const s={...e,rootId:t.sessionId};i.forEach((t=>t.next?.(s)))},_relay:(t,e,s)=>{h._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const t=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];u.schedule(s,n,o,i,r)}},_clock:c,_logger:a};return h}(this,{clock:o,logger:i}),f&&!r&&this.system.inspect(S(f)),this.sessionId=this.system._bookId(),this.id=a??this.sessionId,this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=r,this._syncSnapshot=c,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(!e&&!s)return;const n=[...e?e.values():[],...s?s.values():[]];for(const e of n)try{e(t)}catch(t){u(t)}},actionExecutor:t=>{const e=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:t.type,params:t.params}}),!t.exec)return;const e=O;try{O=!0,t.exec(t.info,t.params)}finally{O=e}};this._processingStatus===j.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),h&&(this.systemId=h,this.system._set(h,this)),this._initState(e?.snapshot??e?.state),h&&"active"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(t,e){let s;for(this._snapshot=t;s=this._deferred.shift();)try{s()}catch(e){this._deferred.length=0,this._snapshot={...t,status:"error",error:e}}switch(this._snapshot.status){case"active":for(const e of this.observers)try{e.next?.(t)}catch(t){u(t)}break;case"done":for(const e of this.observers)try{e.next?.(t)}catch(t){u(t)}this._stopProcedure(),this._complete(),this._doneEvent=(n=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:o,actorId:n}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var n,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const n=S(t,e,s);if(this._processingStatus!==j.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){u(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){u(t)}else u(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const n=e.bind(void 0);return s.add(n),{unsubscribe:()=>{s.delete(n)}}}select(t,e=Object.is){return{subscribe:s=>{const n=S(s),o=this.getSnapshot();let i=t(o);return this.subscribe((s=>{const o=t(s);e(i,o)||(i=o,n.next?.(o))}))},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===j.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.systemId&&this.system._set(this.systemId,this),this._processingStatus=j.Running;const t=a(this.options.input);this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t});switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._snapshot={...this._snapshot,status:"error",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(e,t),t.type===i&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===j.Stopped?this:(this.mailbox.clear(),this._processingStatus===j.NotStarted?(this._processingStatus=j.Stopped,this):(this.mailbox.enqueue({type:i}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){u(t)}this.observers.clear(),this.eventListeners.clear()}_reportError(t){if(!this.observers.size)return this._parent||u(t),void this.eventListeners.clear();let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){u(t)}}this.observers.clear(),this.eventListeners.clear(),e&&u(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,c(this.id,t))}_stopProcedure(){return this._processingStatus!==j.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new n(this._process.bind(this)),this._processingStatus=j.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==j.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:s)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[h](){return this}getSnapshot(){return this._snapshot}}function M(t,...[e]){return new N(t,e)}const P=M;function R(t,e,s,n,{sendId:o}){return[e,{sendId:"function"==typeof o?o(s,n):o},void 0]}function C(t,e){t.defer((()=>{t.system.scheduler.cancel(t.self,e.sendId)}))}function D(t){function e(t,e){}return e.type="xstate.cancel",e.sendId=t,e.resolve=R,e.execute=C,e}function V(t,e,s,n,{id:o,systemId:i,src:r,input:c,syncSnapshot:a}){const u="string"==typeof r?I(e.machine,r):r,h="function"==typeof o?o(s):o;let f,d;return u&&(d="function"==typeof c?c({context:e.context,event:s.event,self:t.self}):c,f=M(u,{id:h,src:r,parent:t.self,syncSnapshot:a,systemId:i,input:d})),[Gt(e,{children:{...e.children,[h]:f}}),{id:o,systemId:i,actorRef:f,src:r,input:d},void 0]}function J(t,{actorRef:e}){e&&t.defer((()=>{e._processingStatus!==j.Stopped&&e.start()}))}function L(...[t,{id:e,systemId:s,input:n,syncSnapshot:o=!1}={}]){function i(t,e){}return i.type="xstate.spawnChild",i.id=e,i.systemId=s,i.src=t,i.input=n,i.syncSnapshot=o,i.resolve=V,i.execute=J,i}function B(t,e,s,n,{actorRef:o}){const i="function"==typeof o?o(s,n):o,r="string"==typeof i?e.children[i]:i;let c=e.children;return r&&(c={...c},delete c[r.id]),[Gt(e,{children:c}),r,void 0]}function z(t,e){const s=e.getSnapshot();if(s&&"children"in s)for(const e of Object.values(s.children))z(t,e);t.system._unregister(e)}function W(t,e){e&&(z(t,e),e._processingStatus===j.Running?t.defer((()=>{t.stopChild(e)})):t.stopChild(e))}function q(t){function e(t,e){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=B,e.execute=W,e}const U=q;function Q(t,e,{stateValue:s}){if("string"==typeof s&&ut(s)){const e=t.machine.getStateNodeById(s);return t._nodes.some((t=>t===e))}return t.matches(s)}function G(t){function e(){return!1}return e.check=Q,e.stateValue=t,e}function F(t,{context:e,event:s},{guards:n}){return!tt(n[0],e,s,t)}function H(t){function e(t,e){return!1}return e.check=F,e.guards=[t],e}function K(t,{context:e,event:s},{guards:n}){return n.every((n=>tt(n,e,s,t)))}function X(t){function e(t,e){return!1}return e.check=K,e.guards=t,e}function Y(t,{context:e,event:s},{guards:n}){return n.some((n=>tt(n,e,s,t)))}function Z(t){function e(t,e){return!1}return e.check=Y,e.guards=t,e}function tt(t,e,s,n){const{machine:o}=n,i="function"==typeof t,r=i?t:o.implementations.guards["string"==typeof t?t:t.type];if(!i&&!r)throw new Error(`Guard '${"string"==typeof t?t:t.type}' is not implemented.'.`);if("function"!=typeof r)return tt(r,e,s,n);const c={context:e,event:s},a=i||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:e,event:s}):t.params:void 0;if(!("check"in r))return r(c,a);return r.check(n,c,r)}function et(t){return"atomic"===t.type||"final"===t.type}function st(t){return Object.values(t.states).filter((t=>"history"!==t.type))}function nt(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function ot(t){const e=new Set(t),s=rt(e);for(const t of e)if("compound"!==t.type||s.get(t)&&s.get(t).length){if("parallel"===t.type)for(const s of st(t))if("history"!==s.type&&!e.has(s)){const t=lt(s);for(const s of t)e.add(s)}}else lt(t).forEach((t=>e.add(t)));for(const t of e){let s=t.parent;for(;s;)e.add(s),s=s.parent}return e}function it(t,e){const s=e.get(t);if(!s)return{};if("compound"===t.type){const t=s[0];if(!t)return{};if(et(t))return t.key}const n={};for(const t of s)n[t.key]=it(t,e);return n}function rt(t){const e=new Map;for(const s of t)e.has(s)||e.set(s,[]),s.parent&&(e.has(s.parent)||e.set(s.parent,[]),e.get(s.parent).push(s));return e}function ct(t,e){return it(t,rt(ot(e)))}function at(t,e){return"compound"===e.type?st(e).some((e=>"final"===e.type&&t.has(e))):"parallel"===e.type?st(e).every((e=>at(t,e))):"final"===e.type}const ut=t=>"#"===t[0];function ht(t){const e=t.config.after;if(!e)return[];const s=Object.keys(e).flatMap((s=>{const n=e[s],o="string"==typeof n?{target:n}:n,i=Number.isNaN(+s)?s:+s,r=(e=>{const s=(n=e,o=t.id,{type:`xstate.after.${n}.${o}`});var n,o;const i=s.type;return t.entry.push(Yt(s,{id:i,delay:e})),t.exit.push(D(i)),i})(i);return v(o).map((t=>({...t,event:r,delay:i})))}));return s.map((e=>{const{delay:s}=e;return{...ft(t,e.event,e),delay:s}}))}function ft(t,e,s){const n=x(s.target),o=s.reenter??!1,i=function(t,e){if(void 0===e)return;return e.map((e=>{if("string"!=typeof e)return e;if(ut(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return vt(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`);try{return vt(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}}))}(t,n),r={...s,actions:v(s.actions),guard:s.guard,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map((t=>`#${t.id}`)):void 0})};return r}function dt(t){const e=x(t.config.target);return e?{target:e.map((e=>"string"==typeof e?vt(t.parent,e):e))}:t.parent.initial}function pt(t){return"history"===t.type}function lt(t){const e=yt(t);for(const s of e)for(const n of nt(s,t))e.add(n);return e}function yt(t){const e=new Set;return function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of st(s))t(e)}(t),e}function gt(t,e){if(ut(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function vt(t,e){if("string"==typeof e&&ut(e))try{return t.machine.getStateNodeById(e)}catch{}const s=d(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=gt(n,t)}return n}function mt(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=s.map((e=>gt(t,e))).filter(Boolean);return[t.machine.root,t].concat(n,s.reduce(((s,n)=>{const o=gt(t,n);if(!o)return s;const i=mt(o,e[n]);return s.concat(i)}),[]))}function _t(t,e,s,n){return"string"==typeof e?function(t,e,s,n){const o=gt(t,e).next(s,n);return o&&o.length?o:t.next(s,n)}(t,e,s,n):1===Object.keys(e).length?function(t,e,s,n){const o=Object.keys(e),i=_t(gt(t,o[0]),e[o[0]],s,n);return i&&i.length?i:t.next(s,n)}(t,e,s,n):function(t,e,s,n){const o=[];for(const i of Object.keys(e)){const r=e[i];if(!r)continue;const c=_t(gt(t,i),r,s,n);c&&o.push(...c)}return o.length?o:t.next(s,n)}(t,e,s,n)}function bt(t){return Object.keys(t.states).map((e=>t.states[e])).filter((t=>"history"===t.type))}function xt(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function St(t,e){const s=new Set(t),n=new Set(e);for(const t of s)if(n.has(t))return!0;for(const t of n)if(s.has(t))return!0;return!1}function wt(t,e,s){const n=new Set;for(const o of t){let t=!1;const i=new Set;for(const r of n)if(St(Et([o],e,s),Et([r],e,s))){if(!xt(o.source,r.source)){t=!0;break}i.add(r)}if(!t){for(const t of i)n.delete(t);n.add(o)}}return Array.from(n)}function It(t,e){if(!t.target)return[];const s=new Set;for(const n of t.target)if(pt(n))if(e[n.id])for(const t of e[n.id])s.add(t);else for(const t of It(dt(n),e))s.add(t);else s.add(n);return[...s]}function kt(t,e){const s=It(t,e);if(!s)return;if(!t.reenter&&s.every((e=>e===t.source||xt(e,t.source))))return t.source;const n=function(t){const[e,...s]=t;for(const t of nt(e,void 0))if(s.every((e=>xt(e,t))))return t}(s.concat(t.source));return n||(t.reenter?void 0:t.source.machine.root)}function Et(t,e,s){const n=new Set;for(const o of t)if(o.target?.length){const t=kt(o,s);o.reenter&&o.source===t&&n.add(t);for(const s of e)xt(s,t)&&n.add(s)}return[...n]}function $t(t,e,s,n,o){return Tt([{target:[...yt(t)],source:t,reenter:!0,actions:[],eventType:null,toJSON:null}],e,s,n,!0,o)}function Tt(t,e,s,n,o,i){const c=[];if(!t.length)return[e,c];const a=s.actionExecutor;s.actionExecutor=t=>{c.push(t),a(t)};try{const a=new Set(e._nodes);let u=e.historyValue;const h=wt(t,a,u);let f=e;o||([f,u]=function(t,e,s,n,o,i,r){let c=t;const a=Et(n,o,i);let u;a.sort(((t,e)=>e.order-t.order));for(const t of a)for(const e of bt(t)){let s;s="deep"===e.history?e=>et(e)&&xt(e,t):e=>e.parent===t,u??={...i},u[e.id]=Array.from(o).filter(s)}for(const t of a)c=Rt(c,e,s,[...t.exit,...t.invoke.map((t=>q(t.id)))],r,void 0),o.delete(t);return[c,u||i]}(f,n,s,h,a,u,i,s.actionExecutor)),f=Rt(f,n,s,h.flatMap((t=>t.actions)),i,void 0),f=function(t,e,s,n,o,i,c,a){let u=t;const h=new Set,f=new Set;(function(t,e,s,n){for(const o of t){const t=kt(o,e);for(const i of o.target||[])pt(i)||o.source===i&&o.source===t&&!o.reenter||(n.add(i),s.add(i)),jt(i,e,s,n);const i=It(o,e);for(const r of i){const i=nt(r,t);"parallel"===t?.type&&i.push(t),At(n,e,s,i,!o.source.parent&&o.reenter?void 0:t)}}})(n,c,f,h),a&&f.add(t.machine.root);const d=new Set;for(const t of[...h].sort(((t,e)=>t.order-e.order))){o.add(t);const n=[];n.push(...t.entry);for(const e of t.invoke)n.push(L(e.src,{...e,syncSnapshot:!!e.onSnapshot}));if(f.has(t)){const e=t.initial.actions;n.push(...e)}if(u=Rt(u,e,s,n,i,t.invoke.map((t=>t.id))),"final"===t.type){const n=t.parent;let c="parallel"===n?.type?n:n?.parent,a=c||t;for("compound"===n?.type&&i.push(r(n.id,void 0!==t.output?m(t.output,u.context,e,s.self):void 0));"parallel"===c?.type&&!d.has(c)&&at(o,c);)d.add(c),i.push(r(c.id)),a=c,c=c.parent;if(c)continue;u=Gt(u,{status:"done",output:Ot(u,e,s,u.machine.root,a)})}}return u}(f,n,s,h,a,i,u,o);const d=[...a];"done"===f.status&&(f=Rt(f,n,s,d.sort(((t,e)=>e.order-t.order)).flatMap((t=>t.exit)),i,void 0));try{return u===e.historyValue&&function(t,e){if(t.length!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}(e._nodes,a)?[f,c]:[Gt(f,{_nodes:d,historyValue:u}),c]}catch(t){throw t}}finally{s.actionExecutor=a}}function Ot(t,e,s,n,o){if(void 0===n.output)return;const i=r(o.id,void 0!==o.output&&o.parent?m(o.output,t.context,e,s.self):void 0);return m(n.output,t.context,i,s.self)}function jt(t,e,s,n){if(pt(t))if(e[t.id]){const o=e[t.id];for(const t of o)n.add(t),jt(t,e,s,n);for(const i of o)Nt(i,t.parent,n,e,s)}else{const o=dt(t);for(const i of o.target)n.add(i),o===t.parent?.initial&&s.add(t.parent),jt(i,e,s,n);for(const i of o.target)Nt(i,t.parent,n,e,s)}else if("compound"===t.type){const[o]=t.initial.target;pt(o)||(n.add(o),s.add(o)),jt(o,e,s,n),Nt(o,t,n,e,s)}else if("parallel"===t.type)for(const o of st(t).filter((t=>!pt(t))))[...n].some((t=>xt(t,o)))||(pt(o)||(n.add(o),s.add(o)),jt(o,e,s,n))}function At(t,e,s,n,o){for(const i of n)if(o&&!xt(i,o)||t.add(i),"parallel"===i.type)for(const n of st(i).filter((t=>!pt(t))))[...t].some((t=>xt(t,n)))||(t.add(n),jt(n,e,s,t))}function Nt(t,e,s,n,o){At(s,n,o,nt(t,e))}function Mt(t,e){return t.implementations.actions[e]}function Pt(t,e,s,n,o,i){const{machine:r}=t;let c=t;for(const t of n){const n="function"==typeof t,a=n?t:Mt(r,"string"==typeof t?t:t.type),u={context:c.context,event:e,self:s.self,system:s.system},h=n||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:c.context,event:e}):t.params:void 0;if(!a||!("resolve"in a)){s.actionExecutor({type:"string"==typeof t?t:"object"==typeof t?t.type:t.name||"(anonymous)",info:u,params:h,exec:a});continue}const f=a,[d,p,l]=f.resolve(s,c,u,h,a,o);c=d,"retryResolve"in f&&i?.push([f,p]),"execute"in f&&s.actionExecutor({type:f.type,info:u,params:p,exec:f.execute.bind(null,s,p)}),l&&(c=Pt(c,e,s,l,o,i))}return c}function Rt(t,e,s,n,o,i){const r=i?[]:void 0,c=Pt(t,e,s,n,{internalQueue:o,deferredActorIds:i},r);return r?.forEach((([t,e])=>{t.retryResolve(s,c,e)})),c}function Ct(t,e,s,n){let r=t;const c=[];function a(t,e,n){s.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:s.self,event:e,snapshot:t[0],_transitions:n}),c.push(t)}if(e.type===i)return r=Gt(Dt(r,e,s),{status:"stopped"}),a([r,[]],e,[]),{snapshot:r,microsteps:c};let u=e;if(u.type!==o){const e=u,o=function(t){return t.type.startsWith("xstate.error.actor")}(e),i=Vt(e,r);if(o&&!i.length)return r=Gt(t,{status:"error",error:e.error}),a([r,[]],e,[]),{snapshot:r,microsteps:c};const h=Tt(i,t,s,u,!1,n);r=h[0],a(h,e,i)}let h=!0;for(;"active"===r.status;){let t=h?Jt(r,u):[];const e=t.length?r:void 0;if(!t.length){if(!n.length)break;u=n.shift(),t=Vt(u,r)}const o=Tt(t,r,s,u,!1,n);r=o[0],h=r!==e,a(o,u,t)}return"active"!==r.status&&Dt(r,u,s),{snapshot:r,microsteps:c}}function Dt(t,e,s){return Rt(t,e,s,Object.values(t.children).map((t=>q(t))),[],void 0)}function Vt(t,e){return e.machine.getTransitionData(e,t)}function Jt(t,e){const s=new Set,n=t._nodes.filter(et);for(const o of n)t:for(const n of[o].concat(nt(o,void 0)))if(n.always)for(const o of n.always)if(void 0===o.guard||tt(o.guard,t.context,e,t)){s.add(o);break t}return wt(Array.from(s),new Set(t._nodes),t.historyValue)}function Lt(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const Bt=function(t){return f(t,this.value)},zt=function(t){return this.tags.has(t)},Wt=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some((t=>void 0!==t.target||t.actions.length))},qt=function(){const{_nodes:t,tags:e,machine:s,getMeta:n,toJSON:o,can:i,hasTag:r,matches:c,...a}=this;return{...a,tags:Array.from(e)}},Ut=function(){return this._nodes.reduce(((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t)),{})};function Qt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:ct(e.root,t._nodes),tags:new Set(t._nodes.flatMap((t=>t.tags))),children:t.children,historyValue:t.historyValue||{},matches:Bt,hasTag:zt,can:Wt,getMeta:Ut,toJSON:qt}}function Gt(t,e={}){return Qt({...t,...e},t.machine)}function Ft(t){if("object"!=typeof t||null===t)return{};const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map((t=>({id:t.id}))))}return e}function Ht(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:1,id:n.id};else{const o=Ht(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function Kt(t,e,s,n,{event:o,id:i,delay:r},{internalQueue:c}){const a=e.machine.implementations.delays;if("string"==typeof o)throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const u="function"==typeof o?o(s,n):o;let h;if("string"==typeof r){const t=a&&a[r];h="function"==typeof t?t(s,n):t}else h="function"==typeof r?r(s,n):r;return"number"!=typeof h&&c.push(u),[e,{event:u,id:i,delay:h},void 0]}function Xt(t,e){const{event:s,delay:n,id:o}=e;"number"!=typeof n||t.defer((()=>{const e=t.self;t.system.scheduler.schedule(e,e,s,n,o)}))}function Yt(t,e){function s(t,e){}return s.type="xstate.raise",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=Kt,s.execute=Xt,s}function Zt(t,e){return{config:t,transition:(e,s,n)=>({...e,context:t(e.context,s,n)}),getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof e?e({input:s}):e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}const te=new WeakMap;function ee(t){const e={config:t,start:(e,s)=>{const{self:n,system:o,emit:i}=s,r={receivers:void 0,dispose:void 0};te.set(n,r),r.dispose=t({input:e.input,system:o,self:n,sendBack:t=>{"stopped"!==n.getSnapshot().status&&n._parent&&o._relay(n,n._parent,t)},receive:t=>{r.receivers??=new Set,r.receivers.add(t)},emit:i})},transition:(t,e,s)=>{const n=te.get(s.self);return e.type===i?(t={...t,status:"stopped",error:void 0},te.delete(s.self),n.receivers?.clear(),n.dispose?.(),t):(n.receivers?.forEach((t=>t(e))),t)},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e}const se="xstate.observable.next",ne="xstate.observable.error",oe="xstate.observable.complete";function ie(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case se:return{...t,context:e.data};case ne:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case oe:return{...t,status:"done",input:void 0,_subscription:void 0};case i:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{n._relay(s,s,{type:se,data:t})},error:t=>{n._relay(s,s,{type:ne,data:t})},complete:()=>{n._relay(s,s,{type:oe})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e}function re(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case ne:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case oe:return{...t,status:"done",input:void 0,_subscription:void 0};case i:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{s._parent&&n._relay(s,s._parent,t)},error:t=>{n._relay(s,s,{type:ne,data:t})},complete:()=>{n._relay(s,s,{type:oe})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e}const ce="xstate.promise.resolve",ae="xstate.promise.reject",ue=new WeakMap;function he(t){const e={config:t,transition:(t,e,s)=>{if("active"!==t.status)return t;switch(e.type){case ce:{const s=e.data;return{...t,status:"done",output:s,input:void 0}}case ae:return{...t,status:"error",error:e.data,input:void 0};case i:return ue.get(s.self)?.abort(),ue.delete(s.self),{...t,status:"stopped",input:void 0};default:return t}},start:(e,{self:s,system:n,emit:o})=>{if("active"!==e.status)return;const i=new AbortController;ue.set(s,i);Promise.resolve(t({input:e.input,system:n,self:s,signal:i.signal,emit:o})).then((t=>{"active"===s.getSnapshot().status&&(ue.delete(s),n._relay(s,s,{type:ce,data:t}))}),(t=>{"active"===s.getSnapshot().status&&(ue.delete(s),n._relay(s,s,{type:ae,data:t}))}))},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e}const fe=Zt((t=>{}),void 0);function de(){return M(fe)}function pe(t,{machine:e,context:s},n,o){return(i,r)=>{const c=((i,r)=>{if("string"==typeof i){const c=I(e,i);if(!c)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const a=M(c,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,systemId:r?.systemId});return o[a.id]=a,a}return M(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[c.id]=c,t.defer((()=>{c._processingStatus!==j.Stopped&&c.start()})),c}}function le(t,e,s,n,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},r={context:e.context,event:s.event,spawn:pe(t,e,s.event,i),self:t.self,system:t.system};let c={};if("function"==typeof o)c=o(r,n);else for(const t of Object.keys(o)){const e=o[t];c[t]="function"==typeof e?e(r,n):e}return[Gt(e,{context:Object.assign({},e.context,c),children:Object.keys(i).length?{...e.children,...i}:e.children}),void 0,void 0]}function ye(t){function e(t,e){}return e.type="xstate.assign",e.assignment=t,e.resolve=le,e}const ge=new WeakMap;function ve(t,e,s){let n=ge.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},ge.set(t,n)),n[e]}const me={},_e=t=>"string"==typeof t?{type:t}:"function"==typeof t?"resolve"in t?{type:t.type}:{type:t.name}:t;class be{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?y(this.config.states,((t,e)=>new be(t,{_parent:this,_key:e,_machine:this.machine}))):me,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=v(this.config.entry).slice(),this.exit=v(this.config.exit).slice(),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=v(t.tags).slice()}_initialize(){this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,b(n).map((e=>ft(t,s,e))))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,b(t.config.onDone).map((e=>ft(t,s,e))))}for(const s of t.invoke){if(s.onDone){const n=`xstate.done.actor.${s.id}`;e.set(n,b(s.onDone).map((e=>ft(t,n,e))))}if(s.onError){const n=`xstate.error.actor.${s.id}`;e.set(n,b(s.onError).map((e=>ft(t,n,e))))}if(s.onSnapshot){const n=`xstate.snapshot.${s.id}`;e.set(n,b(s.onSnapshot).map((e=>ft(t,n,e))))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),this.config.always&&(this.always=b(this.config.always).map((t=>ft(this,"",t)))),Object.keys(this.states).forEach((t=>{this.states[t]._initialize()}))}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(_e),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map((t=>`#${t.id}`)),source:`#${this.id}`,actions:this.initial.actions.map(_e),eventType:null})}:void 0,history:this.history,states:y(this.states,(t=>t.definition)),on:this.on,transitions:[...this.transitions.values()].flat().map((t=>({...t,actions:t.actions.map(_e)}))),entry:this.entry.map(_e),exit:this.exit.map(_e),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return ve(this,"invoke",(()=>v(this.config.invoke).map(((t,e)=>{const{src:s,systemId:n}=t,o=t.id??w(this.id,e),i="string"==typeof s?s:`xstate.invoke.${w(this.id,e)}`;return{...t,src:i,id:o,systemId:n,toJSON(){const{onDone:e,onError:s,...n}=t;return{...n,type:"xstate.invoke",src:i,id:o}}}}))))}get on(){return ve(this,"on",(()=>[...this.transitions].flatMap((([t,e])=>e.map((e=>[t,e])))).reduce(((t,[e,s])=>(t[e]=t[e]||[],t[e].push(s),t)),{})))}get after(){return ve(this,"delayedTransitions",(()=>ht(this)))}get initial(){return ve(this,"initial",(()=>function(t,e){const s="string"==typeof e?t.states[e]:e?t.states[e.target]:void 0;if(!s&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const n={source:t,actions:e&&"string"!=typeof e?v(e.actions):[],eventType:null,reenter:!1,target:s?[s]:[],toJSON:()=>({...n,source:`#${t.id}`,target:s?[`#${s.id}`]:[]})};return n}(this,this.config.initial)))}next(t,e){const s=e.type,n=[];let o;const i=ve(this,`candidates-${s}`,(()=>{return e=s,(t=this).transitions.get(e)||[...t.transitions.keys()].filter((t=>E(e,t))).sort(((t,e)=>e.length-t.length)).flatMap((e=>t.transitions.get(e)));var t,e}));for(const r of i){const{guard:i}=r,c=t.context;let a=!1;try{a=!i||tt(i,c,e,t)}catch(t){const e="string"==typeof i?i:"object"==typeof i?i.type:void 0;throw new Error(`Unable to evaluate guard ${e?`'${e}' `:""}in transition for event '${s}' in state node '${this.id}':\n${t.message}`)}if(a){n.push(...r.actions),o=r;break}}return o?[o]:void 0}get events(){return ve(this,"events",(()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const n=t[s];if(n.states)for(const t of n.events)e.add(`${t}`)}return Array.from(e)}))}get ownEvents(){const t=Object.keys(Object.fromEntries(this.transitions)),e=new Set(t.filter((t=>this.transitions.get(t).some((t=>!(!t.target&&!t.actions.length&&!t.reenter))))));return Array.from(e)}}class xe{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:e?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards:e?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new be(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach((n=>{if(n.config.route&&n.config.id){const s=n.config.id,o=n.config.route.guard,i=(t,e)=>t.event.to===`#${s}`&&(!o||"function"!=typeof o||o(t,e)),r={...n.config.route,guard:i,target:`#${s}`};e.push(ft(t,"xstate.route",r))}n.states&&s(n.states)}))};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations;return new xe(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const e=(s=this.root,n=t.value,ct(s,[...ot(mt(s,n))]));var s,n;const o=ot(mt(this.root,e));return Qt({_nodes:[...o],context:t.context||{},children:{},status:at(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Ct(t,e,s,[]).snapshot}microstep(t,e,s){return Ct(t,e,s,[]).microsteps.map((([t])=>t))}getTransitionData(t,e){return _t(this.root,t.value,t,e)||[]}_getPreInitialState(t,e,s){const{context:n}=this.config,o=Qt({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){return Rt(o,e,t,[ye((({spawn:t,event:e,self:s})=>n({spawn:t,input:e.input,self:s})))],s,void 0)}return o}getInitialSnapshot(t,e){const s=a(e),n=[],o=this._getPreInitialState(t,s,n),[i]=$t(this.root,o,t,s,n),{snapshot:r}=Ct(i,s,t,n);return r}start(t){Object.values(t.children).forEach((t=>{"active"===t.getSnapshot().status&&t.start()}))}getStateNodeById(t){const e=d(t),s=e.slice(1),n=ut(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return vt(o,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,tags:n,machine:o,children:i,context:r,can:c,hasTag:a,matches:u,getMeta:h,toJSON:f,...d}=t,p={};for(const t in i){const s=i[t];p[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s.systemId,syncSnapshot:s._syncSnapshot}}return{...d,context:Ht(r),children:p,historyValue:Ft(d.historyValue)}}(t,e)}restoreSnapshot(t,e){const s={},n=t.children;function o(t,e){if(e instanceof be)return e;try{return t.machine.getStateNodeById(e.id)}catch{}}Object.keys(n).forEach((t=>{const o=n[t],i=o.snapshot,r=o.src,c="string"==typeof r?I(this,r):r;if(!c)return;const a=M(c,{id:t,parent:e.self,syncSnapshot:o.syncSnapshot,snapshot:i,src:r,systemId:o.systemId});s[t]=a}));const i=function(t,e){if(!e||"object"!=typeof e)return{};const s={};for(const n in e){const i=e[n];for(const e of i){const i=o(t,e);i&&(s[n]??=[],s[n].push(i))}}return s}(this.root,t.historyValue),r=Qt({...t,children:s,_nodes:Array.from(ot(mt(this.root,t.value))),historyValue:i},this),c=new Set;return function t(e,s){if(!c.has(e)){c.add(e);for(const n in e){const o=e[n];if(o&&"object"==typeof o){if("xstate$$type"in o&&1===o.xstate$$type){e[n]=s[o.id];continue}t(o,s)}}}}(r.context,s),r}}function Se(t,e,s,n,{event:o}){return[e,{event:"function"==typeof o?o(s,n):o},void 0]}function we(t,{event:e}){t.defer((()=>t.emit(e)))}function Ie(t){function e(t,e){}return e.type="xstate.emit",e.event=t,e.resolve=Se,e.execute=we,e}let ke=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function Ee(t,e,s,n,{to:o,event:i,id:r,delay:c},a){const u=e.machine.implementations.delays;if("string"==typeof i)throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${i}" }) instead`);const h="function"==typeof i?i(s,n):i;let f;if("string"==typeof c){const t=u&&u[c];f="function"==typeof t?t(s,n):t}else f="function"==typeof c?c(s,n):c;const d="function"==typeof o?o(s,n):o;let p;if("string"==typeof d){if(p=d===ke.Parent?t.self._parent:d===ke.Internal?t.self:d.startsWith("#_")?e.children[d.slice(2)]:a.deferredActorIds?.includes(d)?d:e.children[d],!p)throw new Error(`Unable to send event to actor '${d}' from machine '${e.machine.id}'.`)}else p=d||t.self;return[e,{to:p,targetId:"string"==typeof d?d:void 0,event:h,id:r,delay:f},void 0]}function $e(t,e,s){"string"==typeof s.to&&(s.to=e.children[s.to])}function Te(t,e){t.defer((()=>{const{to:s,event:n,delay:o,id:i}=e;"number"!=typeof o?t.system._relay(t.self,s,"xstate.error"===n.type?c(t.self.id,n.data):n):t.system.scheduler.schedule(t.self,s,n,o,i)}))}function Oe(t,e,s){function n(t,e){}return n.type="xstate.sendTo",n.to=t,n.event=e,n.id=s?.id,n.delay=s?.delay,n.resolve=Ee,n.retryResolve=$e,n.execute=Te,n}function je(t,e){return Oe(ke.Parent,t,e)}function Ae(t,e){return Oe(t,(({event:t})=>t),e)}function Ne(t,e,s,n,{collect:o}){const i=[],r=function(t){i.push(t)};return r.assign=(...t)=>{i.push(ye(...t))},r.cancel=(...t)=>{i.push(D(...t))},r.raise=(...t)=>{i.push(Yt(...t))},r.sendTo=(...t)=>{i.push(Oe(...t))},r.sendParent=(...t)=>{i.push(je(...t))},r.spawnChild=(...t)=>{i.push(L(...t))},r.stopChild=(...t)=>{i.push(q(...t))},r.emit=(...t)=>{i.push(Ie(...t))},o({context:s.context,event:s.event,enqueue:r,check:t=>tt(t,e.context,s.event,e),self:t.self,system:t.system},n),[e,void 0,i]}function Me(t){function e(t,e){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=Ne,e}function Pe(t,e,s,n,{value:o,label:i}){return[e,{value:"function"==typeof o?o(s,n):o,label:i},void 0]}function Re({logger:t},{value:e,label:s}){s?t(s,e):t(e)}function Ce(t=({context:t,event:e})=>({context:t,event:e}),e){function s(t,e){}return s.type="xstate.log",s.value=t,s.label=e,s.resolve=Pe,s.execute=Re,s}function De(t,e){const s=v(e);if(!s.some((e=>E(t.type,e)))){const e=1===s.length?`type matching "${s[0]}"`:`one of types matching "${s.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(t)} to have ${e}`)}}function Ve(t,e){return new xe(t,e)}function Je(t){const e=M(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{},actionExecutor:()=>{}}}function Le(t,...[e]){const s=Je(t);return t.getInitialSnapshot(s,e)}function Be(t,e,s){const n=Je(t);return n.self._snapshot=e,t.transition(e,s,n)}function ze({schemas:t,actors:e,actions:s,guards:n,delays:o}){return{assign:ye,sendTo:Oe,raise:Yt,log:Ce,cancel:D,stopChild:q,enqueueActions:Me,emit:Ie,spawnChild:L,createStateConfig:t=>t,createAction:t=>t,createMachine:i=>Ve({...i,schemas:t},{actors:e,actions:s,guards:n,delays:o}),extend:i=>ze({schemas:t,actors:e,actions:{...s,...i.actions},guards:{...n,...i.guards},delays:{...o,...i.delays}})}}class We{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){this._flushingInvalidated=this._flushing;const s=this.getId();return this.timeouts.set(s,{start:this.now(),timeout:e,fn:t}),s}clearTimeout(t){this._flushingInvalidated=this._flushing,this.timeouts.delete(t)}set(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()}flushTimeouts(){if(this._flushing)return void(this._flushingInvalidated=!0);this._flushing=!0;const t=[...this.timeouts].sort((([t,e],[s,n])=>{const o=e.start+e.timeout;return n.start+n.timeout>o?-1:1}));for(const[e,s]of t){if(this._flushingInvalidated)return this._flushingInvalidated=!1,this._flushing=!1,void this.flushTimeouts();this.now()-s.start>=s.timeout&&(this.timeouts.delete(e),s.fn.call(null))}this._flushing=!1}increment(t){this._now+=t,this.flushTimeouts()}}function qe(t){return new Promise(((e,s)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:s})}))}function Ue(t,e,s){const n=[],o=Je(t);o.actionExecutor=t=>{n.push(t)};return[t.transition(e,s,o),n]}function Qe(t,...[e]){const s=[],n=Je(t);n.actionExecutor=t=>{s.push(t)};return[t.getInitialSnapshot(n,e),s]}function Ge(t,e,s){const n=Je(t),{microsteps:o}=Ct(e,s,n,[]);return o}function Fe(t,...[e]){const s=Je(t),n=a(e),o=[],i=t._getPreInitialState(s,n,o),r=$t(t.root,i,s,n,o),{microsteps:c}=Ct(r[0],n,s,o);return[r,...c]}function He(t){const e=[],s=t._nodes.filter(et),n=new Set;for(const t of s)for(const s of[t].concat(nt(t,void 0)))if(!n.has(s.id)){n.add(s.id);for(const[,t]of s.transitions)e.push(...t);s.always&&e.push(...s.always)}return e}const Ke={timeout:1/0};function Xe(t,e,s){const n={...Ke,...s};return new Promise(((s,o)=>{const{signal:i}=n;if(i?.aborted)return void o(i.reason);let r=!1;const c=n.timeout===1/0?void 0:setTimeout((()=>{a(),o(new Error(`Timeout of ${n.timeout} ms exceeded`))}),n.timeout),a=()=>{clearTimeout(c),r=!0,f?.unsubscribe(),h&&i.removeEventListener("abort",h)};function u(t){e(t)&&(a(),s(t))}let h,f;u(t.getSnapshot()),r||(i&&(h=()=>{a(),o(i.reason)},i.addEventListener("abort",h)),f=t.subscribe({next:u,error:t=>{a(),o(t)},complete:()=>{a(),o(new Error("Actor terminated without satisfying predicate"))}}),r&&f.unsubscribe())}))}export{N as Actor,We as SimulatedClock,ke as SpecialTargets,xe as StateMachine,be as StateNode,k as __unsafe_getAllOwnEventDescriptors,X as and,De as assertEvent,ye as assign,D as cancel,M as createActor,de as createEmptyActor,Ve as createMachine,Ie as emit,Me as enqueueActions,Ae as forwardTo,ee as fromCallback,re as fromEventObservable,ie as fromObservable,he as fromPromise,Zt as fromTransition,Fe as getInitialMicrosteps,Le as getInitialSnapshot,Ge as getMicrosteps,Be as getNextSnapshot,He as getNextTransitions,mt as getStateNodes,Qe as initialTransition,P as interpret,Lt as isMachineSnapshot,Ce as log,f as matchesState,H as not,Z as or,l as pathToStateValue,Yt as raise,je as sendParent,Oe as sendTo,ze as setup,L as spawnChild,G as stateIn,U as stop,q as stopChild,S as toObserver,qe as toPromise,Ue as transition,Xe as waitFor};export default null;
8
+ //# sourceMappingURL=/sm/546728fff23412ec5415f09b28a984c4e349ecb65c6c1d0bbe0d0c5d24f3e486.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "thebird",
3
- "version": "1.2.45",
3
+ "version": "1.2.47",
4
4
  "description": "Anthropic SDK to Gemini streaming bridge — drop-in proxy that translates Anthropic message format and tool calls to Google Gemini",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",