@rxova/journey-devtools-bridge 0.6.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,9 +5,14 @@ Bridge that connects Journey machines to the browser devtools extension.
5
5
  ## Install
6
6
 
7
7
  ```bash
8
+ pnpm add @rxova/journey-devtools-bridge
9
+ yarn add @rxova/journey-devtools-bridge
8
10
  npm i @rxova/journey-devtools-bridge
11
+ bun add @rxova/journey-devtools-bridge
9
12
  ```
10
13
 
14
+ The bridge can run in Bun-based browser apps; explicit `enabled: true` remains the safest option when your bundler does not expose a dev/prod env signal.
15
+
11
16
  ## Usage
12
17
 
13
18
  ```ts
@@ -37,6 +42,8 @@ Snapshots include `history.timeline`, `history.index`, `currentStepId`, `visited
37
42
 
38
43
  ## Runtime Defaults
39
44
 
40
- - Enabled in non-production by default.
45
+ - Defaults use `import.meta.env.DEV` / `import.meta.env.PROD` when available, otherwise `process.env.NODE_ENV`.
46
+ - Enabled by default in non-production browser runtimes.
41
47
  - Disabled in production unless `enabled: true`.
42
48
  - Commands disabled in production unless `commandsEnabled: true`.
49
+ - If neither env source is available, bridge and commands default to disabled unless explicitly enabled.
package/dist/bridge.d.ts CHANGED
@@ -6,8 +6,17 @@ export type JourneyDevtoolsBridgeOptions = {
6
6
  appName?: string;
7
7
  commandsEnabled?: boolean;
8
8
  };
9
+ type JourneyImportMetaEnv = {
10
+ DEV?: unknown;
11
+ PROD?: unknown;
12
+ };
13
+ export declare const resolveNonProductionEnvironment: (options?: {
14
+ bundlerEnv?: JourneyImportMetaEnv | null | undefined;
15
+ nodeEnv?: string | undefined;
16
+ }) => boolean;
9
17
  /**
10
18
  * Attaches a journey machine to the browser devtools transport and returns
11
19
  * a detach function that unsubscribes listeners and unregisters the machine.
12
20
  */
13
21
  export declare const attachJourneyDevtools: <TContext, TStepId extends string, TEventType extends string, TPayloadMap extends JourneyEventPayloadMap<TEventType>, TStepMeta>(machine: JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>, options?: JourneyDevtoolsBridgeOptions) => (() => void);
22
+ export {};
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var J=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var P=(e,t)=>{for(var n in t)J(e,n,{get:t[n],enumerable:!0})},V=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of A(t))!Y.call(e,r)&&r!==n&&J(e,r,{get:()=>t[r],enumerable:!(o=U(t,r))||o.enumerable});return e};var j=e=>V(J({},"__esModule",{value:!0}),e);var te={};P(te,{JOURNEY_DEVTOOLS_BRIDGE_SOURCE:()=>c,JOURNEY_DEVTOOLS_CHANNEL:()=>g,JOURNEY_DEVTOOLS_EXTENSION_SOURCE:()=>E,JOURNEY_DEVTOOLS_PROTOCOL_VERSION:()=>m,attachJourneyDevtools:()=>C,isJourneyDevtoolsBridgeEnvelope:()=>O,isJourneyDevtoolsCommand:()=>D,isJourneyDevtoolsEnvelope:()=>v,isJourneyDevtoolsExtensionEnvelope:()=>T});module.exports=j(te);var m=3,g="__RXOVA_JOURNEY_DEVTOOLS__",c="rxova-journey-bridge",E="rxova-journey-extension",p=e=>typeof e=="object"&&e!==null,q=e=>e===c||e===E;var d=(e,t=0)=>{if(t>10)return!1;if(e==null||["string","number","boolean"].includes(typeof e))return!0;if(typeof e=="object"){try{if(JSON.stringify(e).length>5e5)return!1}catch{return!1}return Array.isArray(e)?e.every(o=>d(o,t+1)):Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null?!1:Object.values(e).every(o=>d(o,t+1))}return!1},b=e=>p(e)?e.channel===g&&e.version===3&&q(e.source)&&typeof e.kind=="string"&&typeof e.machineId=="string"&&typeof e.timestamp=="number":!1,z=e=>!p(e)||typeof e.type!="string"||e.type.length===0||e.type.length>100?!1:"payload"in e&&e.payload!==void 0?d(e.payload):!0,D=e=>{if(!p(e)||typeof e.type!="string"||e.type.length===0||e.type.length>50)return!1;switch(e.type){case"goToNextStep":case"terminateMachine":case"completeJourney":case"resetMachine":case"goToLastVisitedStep":return Object.keys(e).length===1;case"goToStepById":return typeof e.stepId=="string"&&e.stepId.length>0&&e.stepId.length<=100&&Object.keys(e).length===2;case"goToPreviousStep":return(e.steps===void 0||typeof e.steps=="number"&&Number.isInteger(e.steps)&&e.steps>=1&&e.steps<=1e4)&&Object.keys(e).length<=2;case"send":return z(e.event)&&Object.keys(e).length===2;case"updateStepMetadata":return typeof e.stepId=="string"&&e.stepId.length>0&&e.stepId.length<=100&&d(e.metadata)&&Object.keys(e).length===3;case"clearStepError":return(e.stepId===void 0||typeof e.stepId=="string"&&e.stepId.length<=100)&&Object.keys(e).length<=2;default:return!1}},O=e=>{if(!b(e)||e.source!==c)return!1;let t=e;switch(e.kind){case"register":return p(t.meta)&&p(t.snapshot)&&d(t.meta)&&d(t.snapshot);case"unregister":return!0;case"snapshot":return p(t.snapshot)&&d(t.snapshot);case"commandResult":return typeof t.requestId=="string"&&t.requestId.length>0&&t.requestId.length<=100&&p(t.snapshot)&&d(t.snapshot);case"commandError":return typeof t.requestId=="string"&&t.requestId.length>0&&t.requestId.length<=100&&p(t.error);default:return!1}},T=e=>{if(!b(e)||e.source!==E||e.kind!=="command")return!1;let t=e;return typeof t.requestId=="string"&&t.requestId.length>0&&t.requestId.length<=100&&D(t.command)},v=e=>O(e)||T(e);var X="Journey Machine",G=e=>typeof e=="object"&&e!==null,H=e=>e==="idle"||e==="evaluating-when"||e==="running-effect"||e==="error",W=()=>{let e=typeof process<"u"?process.env?.NODE_ENV:void 0;return typeof e!="string"?!1:e!=="production"},K=()=>{let e=typeof process<"u"?process.env?.NODE_ENV:void 0;return typeof e!="string"?!1:e!=="production"},$=()=>typeof window>"u"||window.location.origin==="null"?"*":window.location.origin,F=e=>{if(e.length===0||typeof window>"u")return!1;let t=window.location.origin;return t==="null"?e==="null":e===t},Z=()=>`journey-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,_=class{constructor(t=100,n=1e4){this.commandTimestamps=[];this.maxCommandsPerWindow=t,this.windowMs=n}isAllowed(){let t=Date.now(),n=t-this.windowMs;return this.commandTimestamps=this.commandTimestamps.filter(o=>o>n),this.commandTimestamps.length>=this.maxCommandsPerWindow?!1:(this.commandTimestamps.push(t),!0)}reset(){this.commandTimestamps=[]}},S=e=>{if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}let t=new WeakSet;try{let n=JSON.stringify(e,(o,r)=>{if(typeof r=="bigint")return r.toString();if(typeof r=="function")return`[Function ${r.name||"anonymous"}]`;if(typeof r=="symbol")return r.toString();if(typeof r=="object"&&r!==null){if(t.has(r))return"[Circular]";t.add(r)}return r});return n===void 0?void 0:JSON.parse(n)}catch{return String(e)}},I=e=>{if(e instanceof Error){let t="cause"in e&&e.cause!==void 0?e.cause:null;return{name:e.name,message:e.message,stack:typeof e.stack=="string"?e.stack:null,cause:S(t)}}return{name:null,message:typeof e=="string"?e:"Unknown error",stack:null,cause:S(e)}},h=e=>{let t={};for(let[n,o]of Object.entries(e.async.byStep))G(o)&&(t[n]={phase:H(o.phase)?o.phase:"idle",eventType:typeof o.eventType=="string"?o.eventType:null,transitionId:typeof o.transitionId=="string"?o.transitionId:null,error:o.error===null?null:S(o.error)});return{currentStepId:String(e.currentStepId),context:S(e.context),history:{timeline:e.history.timeline.map(n=>String(n)),index:e.history.index},visited:Object.fromEntries(Object.entries(e.visited).map(([n,o])=>[String(n),o===!0])),stepMeta:S(e.stepMeta),status:e.status,async:{isLoading:e.async.isLoading,byStep:t}}},Q=(e,t)=>t in e.stepMeta,w=(e,t,n)=>{if(!Q(e.getSnapshot(),t))throw new Error(`Unknown stepId "${t}" for "${n}" command.`);return t},ee=async(e,t)=>{switch(t.type){case"goToNextStep":case"completeJourney":{let n=await e.send({type:t.type});return{snapshot:n.snapshot,transitioned:n.transitioned,...n.transitionId?{transitionId:n.transitionId}:{}}}case"terminateMachine":{let n=await e.send({type:"terminateJourney"});return{snapshot:n.snapshot,transitioned:n.transitioned,...n.transitionId?{transitionId:n.transitionId}:{}}}case"goToStepById":{let n=w(e,t.stepId,t.type),o=await e.send({type:"goToStepById",stepId:n});return{snapshot:o.snapshot,transitioned:o.transitioned,...o.transitionId?{transitionId:o.transitionId}:{}}}case"goToPreviousStep":{let n=await e.goToPreviousStep(t.steps);return{snapshot:n.snapshot,transitioned:n.transitioned,...n.transitionId?{transitionId:n.transitionId}:{}}}case"goToLastVisitedStep":{let n=await e.goToLastVisitedStep();return{snapshot:n.snapshot,transitioned:n.transitioned,...n.transitionId?{transitionId:n.transitionId}:{}}}case"send":{let n=t.event.payload===void 0?{type:t.event.type}:{type:t.event.type,payload:t.event.payload},o=await e.send(n);return{snapshot:o.snapshot,transitioned:o.transitioned,...o.transitionId?{transitionId:o.transitionId}:{}}}case"updateStepMetadata":{let n=w(e,t.stepId,t.type);return{snapshot:e.updateStepMetadata(n,()=>t.metadata)}}case"resetMachine":return{snapshot:e.resetMachine()};case"clearStepError":{let n=t.stepId===void 0?void 0:w(e,t.stepId,t.type);return{snapshot:e.clearStepError(n)}}}},C=(e,t={})=>{if(!(t.enabled??W())||typeof window>"u")return()=>{};let o=t.commandsEnabled??K(),r=t.machineId?.trim()||Z(),N={machineId:r,label:t.label?.trim()||X,appName:t.appName?.trim()||(typeof document<"u"?document.title:"")||null,commandsEnabled:o},B=$(),u=s=>({channel:g,version:3,source:c,kind:s,machineId:r,timestamp:Date.now()}),l=s=>{window.postMessage(s,B)},M=s=>{let a={...u("snapshot"),snapshot:h(s)};l(a)},y=!1,R=new _,x=s=>{if(s.source!==window||!F(s.origin)||y||!v(s.data)||s.data.source!==E||s.data.kind!=="command")return;let a=s.data;if(a.machineId!==r)return;if(!R.isAllowed()){let i={...u("commandError"),requestId:a.requestId,error:I("Command rate limit exceeded. Too many commands in a short time window.")};l(i);return}if(!o){let i={...u("commandError"),requestId:a.requestId,error:I("Bridge commands are disabled by configuration.")};l(i);return}(async()=>{try{let i=await ee(e,a.command);if(y)return;let f={...u("commandResult"),requestId:a.requestId,snapshot:h(i.snapshot),...i.transitioned!==void 0?{transitioned:i.transitioned}:{},...i.transitionId?{transitionId:i.transitionId}:{}};l(f)}catch(i){if(y)return;let f={...u("commandError"),requestId:a.requestId,error:I(i)};l(f)}})()};window.addEventListener("message",x);let k=e.subscribe(()=>{y||M(e.getSnapshot())}),L={...u("register"),meta:N,snapshot:h(e.getSnapshot())};return l(L),()=>{if(y)return;y=!0,R.reset(),k(),window.removeEventListener("message",x);let s={...u("unregister")};l(s)}};0&&(module.exports={JOURNEY_DEVTOOLS_BRIDGE_SOURCE,JOURNEY_DEVTOOLS_CHANNEL,JOURNEY_DEVTOOLS_EXTENSION_SOURCE,JOURNEY_DEVTOOLS_PROTOCOL_VERSION,attachJourneyDevtools,isJourneyDevtoolsBridgeEnvelope,isJourneyDevtoolsCommand,isJourneyDevtoolsEnvelope,isJourneyDevtoolsExtensionEnvelope});
1
+ "use strict";var x=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var W=Object.prototype.hasOwnProperty;var $=(e,t)=>{for(var n in t)x(e,n,{get:t[n],enumerable:!0})},Z=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of F(t))!W.call(e,a)&&a!==n&&x(e,a,{get:()=>t[a],enumerable:!(o=K(t,a))||o.enumerable});return e};var Q=e=>Z(x({},"__esModule",{value:!0}),e);var ye={};$(ye,{JOURNEY_DEVTOOLS_BRIDGE_SOURCE:()=>S,JOURNEY_DEVTOOLS_CHANNEL:()=>v,JOURNEY_DEVTOOLS_EXTENSION_SOURCE:()=>g,JOURNEY_DEVTOOLS_PROTOCOL_VERSION:()=>D,attachJourneyDevtools:()=>Y,isJourneyDevtoolsBridgeEnvelope:()=>b,isJourneyDevtoolsCommand:()=>_,isJourneyDevtoolsEnvelope:()=>O,isJourneyDevtoolsExtensionEnvelope:()=>C});module.exports=Q(ye);var D=3,v="__RXOVA_JOURNEY_DEVTOOLS__",S="rxova-journey-bridge",g="rxova-journey-extension",p=e=>typeof e=="object"&&e!==null,ee=e=>e===S||e===g;var E=e=>{try{let t=JSON.stringify(e);if(t!==void 0&&t.length>5e5)return!1}catch{return!1}return R(e,0)},R=(e,t)=>t>10?!1:e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:typeof e!="object"?!1:Array.isArray(e)?e.every(n=>R(n,t+1)):Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null?!1:Object.values(e).every(n=>R(n,t+1)),A=e=>p(e)?e.channel===v&&e.version===3&&ee(e.source)&&typeof e.kind=="string"&&typeof e.machineId=="string"&&typeof e.timestamp=="number":!1,te=e=>!p(e)||typeof e.type!="string"||e.type.length===0||e.type.length>100?!1:"payload"in e&&e.payload!==void 0?E(e.payload):!0,_=e=>{if(!p(e)||typeof e.type!="string"||e.type.length===0||e.type.length>50)return!1;switch(e.type){case"goToNextStep":case"terminateMachine":case"completeJourney":case"resetMachine":case"goToLastVisitedStep":return Object.keys(e).length===1;case"goToStepById":return typeof e.stepId=="string"&&e.stepId.length>0&&e.stepId.length<=100&&Object.keys(e).length===2;case"goToPreviousStep":return(e.steps===void 0||typeof e.steps=="number"&&Number.isInteger(e.steps)&&e.steps>=1&&e.steps<=1e4)&&Object.keys(e).length<=2;case"send":return te(e.event)&&Object.keys(e).length===2;case"updateStepMetadata":return typeof e.stepId=="string"&&e.stepId.length>0&&e.stepId.length<=100&&E(e.metadata)&&Object.keys(e).length===3;case"clearStepError":return(e.stepId===void 0||typeof e.stepId=="string"&&e.stepId.length<=100)&&Object.keys(e).length<=2;default:return!1}},b=e=>{if(!A(e)||e.source!==S)return!1;let t=e;switch(e.kind){case"register":return p(t.meta)&&p(t.snapshot)&&E(t.meta)&&E(t.snapshot);case"unregister":return!0;case"snapshot":return p(t.snapshot)&&E(t.snapshot);case"commandResult":return typeof t.requestId=="string"&&t.requestId.length>0&&t.requestId.length<=100&&p(t.snapshot)&&E(t.snapshot)&&(!("error"in t)||p(t.error));case"commandError":return typeof t.requestId=="string"&&t.requestId.length>0&&t.requestId.length<=100&&p(t.error);default:return!1}},C=e=>{if(!A(e)||e.source!==g||e.kind!=="command")return!1;let t=e;return typeof t.requestId=="string"&&t.requestId.length>0&&t.requestId.length<=100&&_(t.command)},O=e=>b(e)||C(e);var le={},ne="Journey Machine",V=e=>typeof e=="object"&&e!==null,oe=e=>e==="idle"||e==="evaluating-when"||e==="running-effect"||e==="error",re=e=>V(e)?e.PROD===!0?!1:e.DEV===!0?!0:null:null,se=e=>typeof e!="string"?null:e!=="production",P=(e={})=>{let t="bundlerEnv"in e?e.bundlerEnv:le.env,n="nodeEnv"in e?e.nodeEnv:typeof process<"u"?process.env?.NODE_ENV:void 0;return re(t)??se(n)??!1},ie=()=>typeof window>"u"||window.location.origin==="null"?"*":window.location.origin,ae=e=>{if(e.length===0||typeof window>"u")return!1;let t=window.location.origin;return t==="null"?e==="null":e===t},pe=()=>`journey-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,B=class{constructor(t=100,n=1e4){this.commandTimestamps=[];this.maxCommandsPerWindow=t,this.windowMs=n}isAllowed(){let t=Date.now(),n=t-this.windowMs;return this.commandTimestamps=this.commandTimestamps.filter(o=>o>n),this.commandTimestamps.length>=this.maxCommandsPerWindow?!1:(this.commandTimestamps.push(t),!0)}reset(){this.commandTimestamps=[]}},f=e=>{let t=typeof structuredClone=="function"?(()=>{try{return structuredClone(e)}catch{return e}})():e,n=new WeakSet;try{let o=JSON.stringify(t,(a,s)=>{if(typeof s=="bigint")return s.toString();if(typeof s=="function")return`[Function ${s.name||"anonymous"}]`;if(typeof s=="symbol")return s.toString();if(typeof s=="object"&&s!==null){if(n.has(s))return"[Circular]";n.add(s)}return s});return o===void 0?void 0:JSON.parse(o)}catch{return String(e)}},T=e=>{if(e instanceof Error){let t="cause"in e&&e.cause!==void 0?e.cause:null;return{name:e.name,message:e.message,stack:typeof e.stack=="string"?e.stack:null,cause:f(t)}}return{name:null,message:typeof e=="string"?e:"Unknown error",stack:null,cause:f(e)}},M=e=>{let t={};for(let[n,o]of Object.entries(e.async.byStep))V(o)&&(t[n]={phase:oe(o.phase)?o.phase:"idle",eventType:typeof o.eventType=="string"?o.eventType:null,transitionId:typeof o.transitionId=="string"?o.transitionId:null,error:o.error===null?null:f(o.error)});return{currentStepId:String(e.currentStepId),context:f(e.context),history:{timeline:e.history.timeline.map(n=>String(n)),index:e.history.index},visited:Object.fromEntries(Object.entries(e.visited).map(([n,o])=>[String(n),o===!0])),stepMeta:f(e.stepMeta),status:e.status,async:{isLoading:e.async.isLoading,byStep:t}}},de=(e,t)=>t in e.stepMeta,N=(e,t,n)=>{if(!de(e.getSnapshot(),t))throw new Error(`Unknown stepId "${t}" for "${n}" command.`);return t},m=e=>({snapshot:e.snapshot,transitioned:e.transitioned,...e.transitionId?{transitionId:e.transitionId}:{},..."error"in e?{error:T(e.error)}:{}}),ue=async(e,t)=>{switch(t.type){case"goToNextStep":case"completeJourney":{let n=await e.send({type:t.type});return m(n)}case"terminateMachine":{let n=await e.send({type:"terminateJourney"});return m(n)}case"goToStepById":{let n=N(e,t.stepId,t.type),o=await e.send({type:"goToStepById",stepId:n});return m(o)}case"goToPreviousStep":{let n=await e.goToPreviousStep(t.steps);return m(n)}case"goToLastVisitedStep":{let n=await e.goToLastVisitedStep();return m(n)}case"send":{let n=t.event.payload===void 0?{type:t.event.type}:{type:t.event.type,payload:t.event.payload},o=await e.send(n);return m(o)}case"updateStepMetadata":{let n=N(e,t.stepId,t.type);return{snapshot:e.updateStepMetadata(n,()=>t.metadata)}}case"resetMachine":return{snapshot:e.resetMachine()};case"clearStepError":{let n=t.stepId===void 0?void 0:N(e,t.stepId,t.type);return{snapshot:e.clearStepError(n)}}}},Y=(e,t={})=>{if(!(t.enabled??P())||typeof window>"u")return()=>{};let o=t.commandsEnabled??P(),a=t.machineId?.trim()||pe(),s={machineId:a,label:t.label?.trim()||ne,appName:t.appName?.trim()||(typeof document<"u"?document.title:"")||null,commandsEnabled:o},j=ie(),u=r=>({channel:v,version:3,source:S,kind:r,machineId:a,timestamp:Date.now()}),l=r=>{try{window.postMessage(r,j)}catch{}},q=r=>{let d={...u("snapshot"),snapshot:M(r)};l(d)},y=!1,k=new B,h=null,c=null,J=null,I=()=>{h=null,c=null,J=null},L=()=>{let r=h;I(),!(!r||y)&&q(r)},z=r=>{if(h=r,c===null){if(typeof window.requestAnimationFrame=="function"){J="raf",c=window.requestAnimationFrame(()=>{L()});return}J="timeout",c=globalThis.setTimeout(()=>{L()},0)}},X=()=>{if(c===null){I();return}J==="raf"&&typeof window.cancelAnimationFrame=="function"?window.cancelAnimationFrame(c):globalThis.clearTimeout(c),I()},U=r=>{if(r.source!==window||!ae(r.origin)||y||!O(r.data)||r.data.source!==g||r.data.kind!=="command")return;let d=r.data;if(d.machineId!==a)return;if(!k.isAllowed()){let i={...u("commandError"),requestId:d.requestId,error:T("Command rate limit exceeded. Too many commands in a short time window.")};l(i);return}if(!o){let i={...u("commandError"),requestId:d.requestId,error:T("Bridge commands are disabled by configuration.")};l(i);return}(async()=>{try{let i=await ue(e,d.command);if(y)return;let w={...u("commandResult"),requestId:d.requestId,snapshot:M(i.snapshot),...i.transitioned!==void 0?{transitioned:i.transitioned}:{},...i.transitionId?{transitionId:i.transitionId}:{},..."error"in i?{error:i.error}:{}};l(w)}catch(i){if(y)return;let w={...u("commandError"),requestId:d.requestId,error:T(i)};l(w)}})()};window.addEventListener("message",U);let G=e.subscribe(()=>{y||z(e.getSnapshot())}),H={...u("register"),meta:s,snapshot:M(e.getSnapshot())};return l(H),()=>{if(y)return;y=!0,k.reset(),G(),window.removeEventListener("message",U),X();let r={...u("unregister")};l(r)}};0&&(module.exports={JOURNEY_DEVTOOLS_BRIDGE_SOURCE,JOURNEY_DEVTOOLS_CHANNEL,JOURNEY_DEVTOOLS_EXTENSION_SOURCE,JOURNEY_DEVTOOLS_PROTOCOL_VERSION,attachJourneyDevtools,isJourneyDevtoolsBridgeEnvelope,isJourneyDevtoolsCommand,isJourneyDevtoolsEnvelope,isJourneyDevtoolsExtensionEnvelope});
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/protocol.ts", "../src/bridge.ts"],
4
- "sourcesContent": ["export { attachJourneyDevtools, type JourneyDevtoolsBridgeOptions } from \"./bridge\";\n\nexport {\n JOURNEY_DEVTOOLS_CHANNEL,\n JOURNEY_DEVTOOLS_PROTOCOL_VERSION,\n JOURNEY_DEVTOOLS_BRIDGE_SOURCE,\n JOURNEY_DEVTOOLS_EXTENSION_SOURCE,\n isJourneyDevtoolsCommand,\n isJourneyDevtoolsEnvelope,\n isJourneyDevtoolsBridgeEnvelope,\n isJourneyDevtoolsExtensionEnvelope,\n type JourneyDevtoolsBridgeCommandErrorEnvelope,\n type JourneyDevtoolsBridgeCommandResultEnvelope,\n type JourneyDevtoolsBridgeEnvelope,\n type JourneyDevtoolsBridgeRegisterEnvelope,\n type JourneyDevtoolsBridgeSnapshotEnvelope,\n type JourneyDevtoolsBridgeUnregisterEnvelope,\n type JourneyDevtoolsCommand,\n type JourneyDevtoolsEnvelope,\n type JourneyDevtoolsExtensionEnvelope,\n type JourneyDevtoolsExtensionCommandEnvelope,\n type JourneyDevtoolsMachineMeta,\n type JourneyDevtoolsSerializableSnapshot,\n type JourneyDevtoolsSerializedError\n} from \"./protocol\";\n", "import type { JourneySnapshot, JourneyStepAsyncState } from \"@rxova/journey-core\";\n\nexport const JOURNEY_DEVTOOLS_PROTOCOL_VERSION = 3 as const;\nexport const JOURNEY_DEVTOOLS_CHANNEL = \"__RXOVA_JOURNEY_DEVTOOLS__\" as const;\n\nexport const JOURNEY_DEVTOOLS_BRIDGE_SOURCE = \"rxova-journey-bridge\" as const;\nexport const JOURNEY_DEVTOOLS_EXTENSION_SOURCE = \"rxova-journey-extension\" as const;\n\nexport type JourneyDevtoolsSource =\n | typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE\n | typeof JOURNEY_DEVTOOLS_EXTENSION_SOURCE;\n\nexport type JourneyDevtoolsStepAsyncState = JourneyStepAsyncState;\n\nexport type JourneyDevtoolsSerializableSnapshot = JourneySnapshot<unknown, string>;\n\nexport type JourneyDevtoolsMachineMeta = {\n machineId: string;\n label: string;\n appName: string | null;\n commandsEnabled?: boolean;\n};\n\nexport type JourneyDevtoolsSerializedError = {\n name: string | null;\n message: string;\n stack: string | null;\n cause: unknown;\n};\n\nexport type JourneyDevtoolsCommand =\n | { type: \"goToNextStep\" }\n | { type: \"terminateMachine\" }\n | { type: \"completeJourney\" }\n | { type: \"goToStepById\"; stepId: string }\n | { type: \"goToPreviousStep\"; steps?: number }\n | { type: \"goToLastVisitedStep\" }\n | { type: \"send\"; event: { type: string; payload?: unknown } }\n | { type: \"updateStepMetadata\"; stepId: string; metadata: unknown }\n | { type: \"resetMachine\" }\n | { type: \"clearStepError\"; stepId?: string };\n\nexport type JourneyDevtoolsEnvelopeBase = {\n channel: typeof JOURNEY_DEVTOOLS_CHANNEL;\n version: typeof JOURNEY_DEVTOOLS_PROTOCOL_VERSION;\n source: JourneyDevtoolsSource;\n kind: string;\n machineId: string;\n timestamp: number;\n};\n\nexport type JourneyDevtoolsBridgeRegisterEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"register\";\n meta: JourneyDevtoolsMachineMeta;\n snapshot: JourneyDevtoolsSerializableSnapshot;\n};\n\nexport type JourneyDevtoolsBridgeUnregisterEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"unregister\";\n};\n\nexport type JourneyDevtoolsBridgeSnapshotEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"snapshot\";\n snapshot: JourneyDevtoolsSerializableSnapshot;\n};\n\nexport type JourneyDevtoolsBridgeCommandResultEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"commandResult\";\n requestId: string;\n snapshot: JourneyDevtoolsSerializableSnapshot;\n transitioned?: boolean;\n transitionId?: string;\n};\n\nexport type JourneyDevtoolsBridgeCommandErrorEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"commandError\";\n requestId: string;\n error: JourneyDevtoolsSerializedError;\n};\n\nexport type JourneyDevtoolsExtensionCommandEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_EXTENSION_SOURCE;\n kind: \"command\";\n requestId: string;\n command: JourneyDevtoolsCommand;\n};\n\nexport type JourneyDevtoolsBridgeEnvelope =\n | JourneyDevtoolsBridgeRegisterEnvelope\n | JourneyDevtoolsBridgeUnregisterEnvelope\n | JourneyDevtoolsBridgeSnapshotEnvelope\n | JourneyDevtoolsBridgeCommandResultEnvelope\n | JourneyDevtoolsBridgeCommandErrorEnvelope;\n\nexport type JourneyDevtoolsExtensionEnvelope = JourneyDevtoolsExtensionCommandEnvelope;\n\nexport type JourneyDevtoolsEnvelope =\n | JourneyDevtoolsBridgeEnvelope\n | JourneyDevtoolsExtensionEnvelope;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isKnownSource = (value: unknown): value is JourneyDevtoolsSource =>\n value === JOURNEY_DEVTOOLS_BRIDGE_SOURCE || value === JOURNEY_DEVTOOLS_EXTENSION_SOURCE;\n\n/**\n * Maximum depth for nested object validation.\n * Prevents stack overflow and excessive processing from deeply nested malicious payloads.\n */\nconst MAX_PAYLOAD_DEPTH = 10;\n\n/**\n * Maximum size (in JSON string length) for serialized payloads.\n * Prevents memory exhaustion from extremely large payloads.\n */\nconst MAX_PAYLOAD_SIZE = 500_000; // 500KB\n\n/**\n * Validates that a value is safe for transport.\n * Checks depth and size constraints to prevent malicious payloads.\n */\nconst isSafePayload = (value: unknown, depth = 0): boolean => {\n if (depth > MAX_PAYLOAD_DEPTH) {\n return false;\n }\n\n if (value === null || value === undefined) {\n return true;\n }\n\n const primitiveTypes = [\"string\", \"number\", \"boolean\"];\n if (primitiveTypes.includes(typeof value)) {\n return true;\n }\n\n if (typeof value === \"object\") {\n // Check JSON serialization size\n try {\n const serialized = JSON.stringify(value);\n if (serialized.length > MAX_PAYLOAD_SIZE) {\n return false;\n }\n } catch {\n // Circular references or non-serializable objects are not safe\n return false;\n }\n\n // Recursively validate nested objects and arrays\n if (Array.isArray(value)) {\n return value.every((item) => isSafePayload(item, depth + 1));\n }\n\n // Validate plain objects (guard against prototype pollution)\n if (\n Object.getPrototypeOf(value) !== Object.prototype &&\n Object.getPrototypeOf(value) !== null\n ) {\n return false;\n }\n\n return Object.values(value).every((prop) => isSafePayload(prop, depth + 1));\n }\n\n // Reject functions, symbols, and other non-serializable types\n return false;\n};\n\nconst hasBaseEnvelopeShape = (value: unknown): value is JourneyDevtoolsEnvelopeBase => {\n if (!isRecord(value)) {\n return false;\n }\n\n return (\n value.channel === JOURNEY_DEVTOOLS_CHANNEL &&\n value.version === JOURNEY_DEVTOOLS_PROTOCOL_VERSION &&\n isKnownSource(value.source) &&\n typeof value.kind === \"string\" &&\n typeof value.machineId === \"string\" &&\n typeof value.timestamp === \"number\"\n );\n};\n\nconst isSendEvent = (value: unknown): value is { type: string; payload?: unknown } => {\n if (!isRecord(value)) {\n return false;\n }\n\n if (typeof value.type !== \"string\" || value.type.length === 0 || value.type.length > 100) {\n return false;\n }\n\n // Validate payload if present\n if (\"payload\" in value && value.payload !== undefined) {\n return isSafePayload(value.payload);\n }\n\n return true;\n};\n\n/**\n * Validates whether an unknown value is a supported devtools command payload.\n */\nexport const isJourneyDevtoolsCommand = (value: unknown): value is JourneyDevtoolsCommand => {\n if (!isRecord(value) || typeof value.type !== \"string\") {\n return false;\n }\n\n // Validate command type is within reasonable length\n if (value.type.length === 0 || value.type.length > 50) {\n return false;\n }\n\n switch (value.type) {\n case \"goToNextStep\":\n case \"terminateMachine\":\n case \"completeJourney\":\n case \"resetMachine\":\n case \"goToLastVisitedStep\":\n // These commands should have no extra properties beyond type\n return Object.keys(value).length === 1;\n case \"goToStepById\":\n return (\n typeof value.stepId === \"string\" &&\n value.stepId.length > 0 &&\n value.stepId.length <= 100 &&\n Object.keys(value).length === 2\n );\n case \"goToPreviousStep\":\n return (\n (value.steps === undefined ||\n (typeof value.steps === \"number\" &&\n Number.isInteger(value.steps) &&\n value.steps >= 1 &&\n value.steps <= 10000)) &&\n Object.keys(value).length <= 2\n );\n case \"send\":\n return isSendEvent(value.event) && Object.keys(value).length === 2;\n case \"updateStepMetadata\":\n return (\n typeof value.stepId === \"string\" &&\n value.stepId.length > 0 &&\n value.stepId.length <= 100 &&\n isSafePayload(value.metadata) &&\n Object.keys(value).length === 3\n );\n case \"clearStepError\":\n return (\n (value.stepId === undefined ||\n (typeof value.stepId === \"string\" && value.stepId.length <= 100)) &&\n Object.keys(value).length <= 2\n );\n default:\n return false;\n }\n};\n\n/**\n * Validates whether an unknown value is a bridge-origin envelope.\n */\nexport const isJourneyDevtoolsBridgeEnvelope = (\n value: unknown\n): value is JourneyDevtoolsBridgeEnvelope => {\n if (!hasBaseEnvelopeShape(value) || value.source !== JOURNEY_DEVTOOLS_BRIDGE_SOURCE) {\n return false;\n }\n\n const envelope = value as Record<string, unknown>;\n\n switch (value.kind) {\n case \"register\":\n return (\n isRecord(envelope.meta) &&\n isRecord(envelope.snapshot) &&\n isSafePayload(envelope.meta) &&\n isSafePayload(envelope.snapshot)\n );\n case \"unregister\":\n return true;\n case \"snapshot\":\n return isRecord(envelope.snapshot) && isSafePayload(envelope.snapshot);\n case \"commandResult\":\n return (\n typeof envelope.requestId === \"string\" &&\n envelope.requestId.length > 0 &&\n envelope.requestId.length <= 100 &&\n isRecord(envelope.snapshot) &&\n isSafePayload(envelope.snapshot)\n );\n case \"commandError\":\n return (\n typeof envelope.requestId === \"string\" &&\n envelope.requestId.length > 0 &&\n envelope.requestId.length <= 100 &&\n isRecord(envelope.error)\n );\n default:\n return false;\n }\n};\n\n/**\n * Validates whether an unknown value is an extension-origin command envelope.\n */\nexport const isJourneyDevtoolsExtensionEnvelope = (\n value: unknown\n): value is JourneyDevtoolsExtensionEnvelope => {\n if (!hasBaseEnvelopeShape(value) || value.source !== JOURNEY_DEVTOOLS_EXTENSION_SOURCE) {\n return false;\n }\n\n if (value.kind !== \"command\") {\n return false;\n }\n\n const envelope = value as Record<string, unknown>;\n return (\n typeof envelope.requestId === \"string\" &&\n envelope.requestId.length > 0 &&\n envelope.requestId.length <= 100 &&\n isJourneyDevtoolsCommand(envelope.command)\n );\n};\n\n/**\n * Validates whether an unknown value matches either supported devtools envelope shape.\n */\nexport const isJourneyDevtoolsEnvelope = (value: unknown): value is JourneyDevtoolsEnvelope =>\n isJourneyDevtoolsBridgeEnvelope(value) || isJourneyDevtoolsExtensionEnvelope(value);\n", "import type {\n JourneyEventPayloadMap,\n JourneyMachine,\n JourneySendResult,\n JourneySnapshot\n} from \"@rxova/journey-core\";\nimport {\n JOURNEY_DEVTOOLS_BRIDGE_SOURCE,\n JOURNEY_DEVTOOLS_CHANNEL,\n JOURNEY_DEVTOOLS_EXTENSION_SOURCE,\n JOURNEY_DEVTOOLS_PROTOCOL_VERSION,\n isJourneyDevtoolsEnvelope,\n type JourneyDevtoolsBridgeCommandErrorEnvelope,\n type JourneyDevtoolsBridgeCommandResultEnvelope,\n type JourneyDevtoolsBridgeEnvelope,\n type JourneyDevtoolsBridgeRegisterEnvelope,\n type JourneyDevtoolsBridgeSnapshotEnvelope,\n type JourneyDevtoolsBridgeUnregisterEnvelope,\n type JourneyDevtoolsCommand,\n type JourneyDevtoolsExtensionCommandEnvelope,\n type JourneyDevtoolsMachineMeta,\n type JourneyDevtoolsSerializableSnapshot,\n type JourneyDevtoolsSerializedError\n} from \"./protocol\";\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nexport type JourneyDevtoolsBridgeOptions = {\n machineId?: string;\n label?: string;\n enabled?: boolean;\n appName?: string;\n commandsEnabled?: boolean;\n};\n\ntype SendOutcome<TContext, TStepId extends string, TStepMeta> = {\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>;\n transitioned?: boolean;\n transitionId?: string;\n};\n\nconst DEFAULT_MACHINE_LABEL = \"Journey Machine\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isJourneyAsyncPhase = (\n value: unknown\n): value is JourneyDevtoolsSerializableSnapshot[\"async\"][\"byStep\"][string][\"phase\"] =>\n value === \"idle\" ||\n value === \"evaluating-when\" ||\n value === \"running-effect\" ||\n value === \"error\";\n\nconst resolveDefaultEnabled = (): boolean => {\n const nodeEnv = typeof process !== \"undefined\" ? process.env?.NODE_ENV : undefined;\n if (typeof nodeEnv !== \"string\") {\n return false;\n }\n\n return nodeEnv !== \"production\";\n};\n\nconst resolveDefaultCommandsEnabled = (): boolean => {\n const nodeEnv = typeof process !== \"undefined\" ? process.env?.NODE_ENV : undefined;\n if (typeof nodeEnv !== \"string\") {\n return false;\n }\n\n return nodeEnv !== \"production\";\n};\n\nconst resolveWindowTargetOrigin = (): string => {\n if (typeof window === \"undefined\") {\n return \"*\";\n }\n\n return window.location.origin === \"null\" ? \"*\" : window.location.origin;\n};\n\n// No session token infrastructure needed\n\n/**\n * Validates that the message origin matches the current window origin.\n * This prevents messages from other origins from being processed.\n *\n * Note: This is part of defense-in-depth but not a hard security boundary.\n * Code running in the same origin can still send messages.\n */\nconst isExpectedWindowOrigin = (origin: string): boolean => {\n if (origin.length === 0) {\n return false;\n }\n\n if (typeof window === \"undefined\") {\n return false;\n }\n\n const expected = window.location.origin;\n if (expected === \"null\") {\n // For file:// or sandboxed contexts where origin is \"null\"\n return origin === \"null\";\n }\n\n // Strict equality check - no wildcard matching\n return origin === expected;\n};\n\nconst createMachineId = (): string =>\n `journey-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n\n/**\n * Simple rate limiter to prevent command abuse.\n * Tracks command timestamps and enforces a maximum rate.\n */\nclass CommandRateLimiter {\n private commandTimestamps: number[] = [];\n private readonly maxCommandsPerWindow: number;\n private readonly windowMs: number;\n\n constructor(maxCommandsPerWindow = 100, windowMs = 10000) {\n this.maxCommandsPerWindow = maxCommandsPerWindow;\n this.windowMs = windowMs;\n }\n\n /**\n * Checks if a command is allowed based on rate limits.\n * Returns true if allowed, false if rate limit exceeded.\n */\n isAllowed(): boolean {\n const now = Date.now();\n const windowStart = now - this.windowMs;\n\n // Remove old timestamps outside the window\n this.commandTimestamps = this.commandTimestamps.filter((ts) => ts > windowStart);\n\n if (this.commandTimestamps.length >= this.maxCommandsPerWindow) {\n return false;\n }\n\n this.commandTimestamps.push(now);\n return true;\n }\n\n reset(): void {\n this.commandTimestamps = [];\n }\n}\n\nconst cloneForTransport = (value: unknown): unknown => {\n if (typeof structuredClone === \"function\") {\n try {\n return structuredClone(value);\n } catch {\n // Fall through to the JSON serializer below.\n }\n }\n\n const seen = new WeakSet<object>();\n\n try {\n const serialized = JSON.stringify(value, (_key, currentValue) => {\n if (typeof currentValue === \"bigint\") {\n return currentValue.toString();\n }\n if (typeof currentValue === \"function\") {\n return `[Function ${currentValue.name || \"anonymous\"}]`;\n }\n if (typeof currentValue === \"symbol\") {\n return currentValue.toString();\n }\n if (typeof currentValue === \"object\" && currentValue !== null) {\n if (seen.has(currentValue)) {\n return \"[Circular]\";\n }\n seen.add(currentValue);\n }\n return currentValue;\n });\n\n if (serialized === undefined) {\n return undefined;\n }\n\n return JSON.parse(serialized) as unknown;\n } catch {\n return String(value);\n }\n};\n\nconst serializeError = (error: unknown): JourneyDevtoolsSerializedError => {\n if (error instanceof Error) {\n const cause =\n \"cause\" in error && (error as { cause?: unknown }).cause !== undefined\n ? (error as { cause?: unknown }).cause\n : null;\n return {\n name: error.name,\n message: error.message,\n stack: typeof error.stack === \"string\" ? error.stack : null,\n cause: cloneForTransport(cause)\n };\n }\n\n return {\n name: null,\n message: typeof error === \"string\" ? error : \"Unknown error\",\n stack: null,\n cause: cloneForTransport(error)\n };\n};\n\nconst serializeSnapshot = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>\n): JourneyDevtoolsSerializableSnapshot => {\n const byStep: Record<string, JourneyDevtoolsSerializableSnapshot[\"async\"][\"byStep\"][string]> = {};\n\n for (const [stepId, stepState] of Object.entries(\n snapshot.async.byStep as Record<string, unknown>\n )) {\n if (!isRecord(stepState)) {\n continue;\n }\n\n byStep[stepId] = {\n phase: isJourneyAsyncPhase(stepState.phase) ? stepState.phase : \"idle\",\n eventType: typeof stepState.eventType === \"string\" ? stepState.eventType : null,\n transitionId: typeof stepState.transitionId === \"string\" ? stepState.transitionId : null,\n error: stepState.error === null ? null : cloneForTransport(stepState.error)\n };\n }\n\n return {\n currentStepId: String(snapshot.currentStepId),\n context: cloneForTransport(snapshot.context),\n history: {\n timeline: snapshot.history.timeline.map((stepId) => String(stepId)),\n index: snapshot.history.index\n },\n visited: Object.fromEntries(\n Object.entries(snapshot.visited as Record<string, boolean>).map(([stepId, isVisited]) => [\n String(stepId),\n isVisited === true\n ])\n ),\n stepMeta: cloneForTransport(snapshot.stepMeta) as Record<string, unknown>,\n status: snapshot.status,\n async: {\n isLoading: snapshot.async.isLoading,\n byStep\n }\n };\n};\n\nconst isKnownStepId = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n stepId: string\n): stepId is TStepId => stepId in snapshot.stepMeta;\n\nconst assertKnownStepId = <TContext, TStepId extends string, TStepMeta>(\n machine: JourneyMachine<TContext, TStepId, string, Record<never, never>, TStepMeta>,\n stepId: string,\n commandType: JourneyDevtoolsCommand[\"type\"]\n): TStepId => {\n if (!isKnownStepId(machine.getSnapshot(), stepId)) {\n throw new Error(`Unknown stepId \"${stepId}\" for \"${commandType}\" command.`);\n }\n return stepId;\n};\n\nconst runCommand = async <TContext, TStepId extends string, TStepMeta>(\n machine: JourneyMachine<TContext, TStepId, string, Record<never, never>, TStepMeta>,\n command: JourneyDevtoolsCommand\n): Promise<SendOutcome<TContext, TStepId, TStepMeta>> => {\n switch (command.type) {\n case \"goToNextStep\":\n case \"completeJourney\": {\n const result = await machine.send({ type: command.type });\n return {\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {})\n };\n }\n case \"terminateMachine\": {\n const result = await machine.send({ type: \"terminateJourney\" });\n return {\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {})\n };\n }\n case \"goToStepById\": {\n const stepId = assertKnownStepId(machine, command.stepId, command.type);\n const result = await machine.send({\n type: \"goToStepById\",\n stepId\n });\n return {\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {})\n };\n }\n case \"goToPreviousStep\": {\n const result = await machine.goToPreviousStep(command.steps);\n return {\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {})\n };\n }\n case \"goToLastVisitedStep\": {\n const result = await machine.goToLastVisitedStep();\n return {\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {})\n };\n }\n case \"send\": {\n const sendEvent =\n command.event.payload === undefined\n ? { type: command.event.type }\n : { type: command.event.type, payload: command.event.payload };\n const result: JourneySendResult<TContext, TStepId, TStepMeta> = await machine.send(sendEvent);\n return {\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {})\n };\n }\n case \"updateStepMetadata\": {\n const stepId = assertKnownStepId(machine, command.stepId, command.type);\n return {\n snapshot: machine.updateStepMetadata(stepId, () => command.metadata as TStepMeta)\n };\n }\n case \"resetMachine\":\n return {\n snapshot: machine.resetMachine()\n };\n case \"clearStepError\": {\n const stepId =\n command.stepId === undefined\n ? undefined\n : assertKnownStepId(machine, command.stepId, command.type);\n return {\n snapshot: machine.clearStepError(stepId)\n };\n }\n }\n};\n\n/**\n * Attaches a journey machine to the browser devtools transport and returns\n * a detach function that unsubscribes listeners and unregisters the machine.\n */\nexport const attachJourneyDevtools = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TStepMeta\n>(\n machine: JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>,\n options: JourneyDevtoolsBridgeOptions = {}\n): (() => void) => {\n const enabled = options.enabled ?? resolveDefaultEnabled();\n if (!enabled || typeof window === \"undefined\") {\n return () => {};\n }\n const commandsEnabled = options.commandsEnabled ?? resolveDefaultCommandsEnabled();\n\n const machineId = options.machineId?.trim() || createMachineId();\n const meta: JourneyDevtoolsMachineMeta = {\n machineId,\n label: options.label?.trim() || DEFAULT_MACHINE_LABEL,\n appName:\n options.appName?.trim() || (typeof document !== \"undefined\" ? document.title : \"\") || null,\n commandsEnabled\n };\n const targetOrigin = resolveWindowTargetOrigin();\n\n const createBaseEnvelope = <TKind extends JourneyDevtoolsBridgeEnvelope[\"kind\"]>(\n kind: TKind\n ) => ({\n channel: JOURNEY_DEVTOOLS_CHANNEL,\n version: JOURNEY_DEVTOOLS_PROTOCOL_VERSION,\n source: JOURNEY_DEVTOOLS_BRIDGE_SOURCE,\n kind,\n machineId,\n timestamp: Date.now()\n });\n\n const post = (envelope: JourneyDevtoolsBridgeEnvelope) => {\n window.postMessage(envelope, targetOrigin);\n };\n\n const postSnapshot = (snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>) => {\n const envelope: JourneyDevtoolsBridgeSnapshotEnvelope = {\n ...createBaseEnvelope(\"snapshot\"),\n snapshot: serializeSnapshot(snapshot)\n };\n post(envelope);\n };\n\n let isDetached = false;\n const rateLimiter = new CommandRateLimiter();\n\n const onMessage = (event: MessageEvent<unknown>) => {\n if (\n event.source !== window ||\n !isExpectedWindowOrigin(event.origin) ||\n isDetached ||\n !isJourneyDevtoolsEnvelope(event.data)\n ) {\n return;\n }\n\n if (event.data.source !== JOURNEY_DEVTOOLS_EXTENSION_SOURCE || event.data.kind !== \"command\") {\n return;\n }\n\n const commandEnvelope: JourneyDevtoolsExtensionCommandEnvelope = event.data;\n if (commandEnvelope.machineId !== machineId) {\n return;\n }\n\n // Rate limiting to prevent command abuse\n if (!rateLimiter.isAllowed()) {\n const errorEnvelope: JourneyDevtoolsBridgeCommandErrorEnvelope = {\n ...createBaseEnvelope(\"commandError\"),\n requestId: commandEnvelope.requestId,\n error: serializeError(\n \"Command rate limit exceeded. Too many commands in a short time window.\"\n )\n };\n post(errorEnvelope);\n return;\n }\n\n if (!commandsEnabled) {\n const errorEnvelope: JourneyDevtoolsBridgeCommandErrorEnvelope = {\n ...createBaseEnvelope(\"commandError\"),\n requestId: commandEnvelope.requestId,\n error: serializeError(\"Bridge commands are disabled by configuration.\")\n };\n post(errorEnvelope);\n return;\n }\n\n const run = async () => {\n try {\n const outcome = await runCommand(\n machine as JourneyMachine<TContext, TStepId, string, Record<never, never>, TStepMeta>,\n commandEnvelope.command\n );\n if (isDetached) {\n return;\n }\n\n const resultEnvelope: JourneyDevtoolsBridgeCommandResultEnvelope = {\n ...createBaseEnvelope(\"commandResult\"),\n requestId: commandEnvelope.requestId,\n snapshot: serializeSnapshot(outcome.snapshot),\n ...(outcome.transitioned !== undefined ? { transitioned: outcome.transitioned } : {}),\n ...(outcome.transitionId ? { transitionId: outcome.transitionId } : {})\n };\n post(resultEnvelope);\n } catch (error) {\n if (isDetached) {\n return;\n }\n\n const errorEnvelope: JourneyDevtoolsBridgeCommandErrorEnvelope = {\n ...createBaseEnvelope(\"commandError\"),\n requestId: commandEnvelope.requestId,\n error: serializeError(error)\n };\n post(errorEnvelope);\n }\n };\n\n void run();\n };\n\n window.addEventListener(\"message\", onMessage);\n\n const unsubscribe = machine.subscribe(() => {\n if (isDetached) {\n return;\n }\n postSnapshot(machine.getSnapshot());\n });\n\n const registerEnvelope: JourneyDevtoolsBridgeRegisterEnvelope = {\n ...createBaseEnvelope(\"register\"),\n meta,\n snapshot: serializeSnapshot(machine.getSnapshot())\n };\n post(registerEnvelope);\n\n return () => {\n if (isDetached) {\n return;\n }\n\n isDetached = true;\n rateLimiter.reset();\n unsubscribe();\n window.removeEventListener(\"message\", onMessage);\n\n const unregisterEnvelope: JourneyDevtoolsBridgeUnregisterEnvelope = {\n ...createBaseEnvelope(\"unregister\")\n };\n post(unregisterEnvelope);\n };\n};\n"],
5
- "mappings": "yaAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,oCAAAE,EAAA,6BAAAC,EAAA,sCAAAC,EAAA,sCAAAC,EAAA,0BAAAC,EAAA,oCAAAC,EAAA,6BAAAC,EAAA,8BAAAC,EAAA,uCAAAC,IAAA,eAAAC,EAAAX,ICEO,IAAMY,EAAoC,EACpCC,EAA2B,6BAE3BC,EAAiC,uBACjCC,EAAoC,0BAmG3CC,EAAYC,GAChB,OAAOA,GAAU,UAAYA,IAAU,KAEnCC,EAAiBD,GACrBA,IAAUH,GAAkCG,IAAUF,EAkBxD,IAAMI,EAAgB,CAACC,EAAgBC,EAAQ,IAAe,CAC5D,GAAIA,EAAQ,GACV,MAAO,GAQT,GALID,GAAU,MAIS,CAAC,SAAU,SAAU,SAAS,EAClC,SAAS,OAAOA,CAAK,EACtC,MAAO,GAGT,GAAI,OAAOA,GAAU,SAAU,CAE7B,GAAI,CAEF,GADmB,KAAK,UAAUA,CAAK,EACxB,OAAS,IACtB,MAAO,EAEX,MAAQ,CAEN,MAAO,EACT,CAGA,OAAI,MAAM,QAAQA,CAAK,EACdA,EAAM,MAAOE,GAASH,EAAcG,EAAMD,EAAQ,CAAC,CAAC,EAK3D,OAAO,e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B,EAAmB,YAAY,CACpC,EACAI,EAAKe,CAAkB,CACzB,CACF",
6
- "names": ["index_exports", "__export", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "JOURNEY_DEVTOOLS_CHANNEL", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "JOURNEY_DEVTOOLS_PROTOCOL_VERSION", "attachJourneyDevtools", "isJourneyDevtoolsBridgeEnvelope", "isJourneyDevtoolsCommand", "isJourneyDevtoolsEnvelope", "isJourneyDevtoolsExtensionEnvelope", "__toCommonJS", "JOURNEY_DEVTOOLS_PROTOCOL_VERSION", "JOURNEY_DEVTOOLS_CHANNEL", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "isRecord", "value", "isKnownSource", "isSafePayload", "value", "depth", "item", "prop", "hasBaseEnvelopeShape", "isRecord", "JOURNEY_DEVTOOLS_CHANNEL", "isKnownSource", "isSendEvent", "isJourneyDevtoolsCommand", "isJourneyDevtoolsBridgeEnvelope", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "envelope", "isJourneyDevtoolsExtensionEnvelope", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "isJourneyDevtoolsEnvelope", "DEFAULT_MACHINE_LABEL", "isRecord", "value", "isJourneyAsyncPhase", "resolveDefaultEnabled", "nodeEnv", "resolveDefaultCommandsEnabled", "resolveWindowTargetOrigin", "isExpectedWindowOrigin", "origin", "expected", "createMachineId", "CommandRateLimiter", "maxCommandsPerWindow", "windowMs", "now", "windowStart", "ts", "cloneForTransport", "seen", "serialized", "_key", "currentValue", "serializeError", "error", "cause", "serializeSnapshot", "snapshot", "byStep", "stepId", "stepState", "isVisited", "isKnownStepId", "assertKnownStepId", "machine", "commandType", "runCommand", "command", "result", "sendEvent", "attachJourneyDevtools", "options", "commandsEnabled", "machineId", "meta", "targetOrigin", "createBaseEnvelope", "kind", "JOURNEY_DEVTOOLS_CHANNEL", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "post", "envelope", "postSnapshot", "isDetached", "rateLimiter", "onMessage", "event", "isJourneyDevtoolsEnvelope", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "commandEnvelope", "errorEnvelope", "outcome", "resultEnvelope", "unsubscribe", "registerEnvelope", "unregisterEnvelope"]
4
+ "sourcesContent": ["export { attachJourneyDevtools, type JourneyDevtoolsBridgeOptions } from \"./bridge\";\n\nexport {\n JOURNEY_DEVTOOLS_CHANNEL,\n JOURNEY_DEVTOOLS_PROTOCOL_VERSION,\n JOURNEY_DEVTOOLS_BRIDGE_SOURCE,\n JOURNEY_DEVTOOLS_EXTENSION_SOURCE,\n isJourneyDevtoolsCommand,\n isJourneyDevtoolsEnvelope,\n isJourneyDevtoolsBridgeEnvelope,\n isJourneyDevtoolsExtensionEnvelope,\n type JourneyDevtoolsBridgeCommandErrorEnvelope,\n type JourneyDevtoolsBridgeCommandResultEnvelope,\n type JourneyDevtoolsBridgeEnvelope,\n type JourneyDevtoolsBridgeRegisterEnvelope,\n type JourneyDevtoolsBridgeSnapshotEnvelope,\n type JourneyDevtoolsBridgeUnregisterEnvelope,\n type JourneyDevtoolsCommand,\n type JourneyDevtoolsEnvelope,\n type JourneyDevtoolsExtensionEnvelope,\n type JourneyDevtoolsExtensionCommandEnvelope,\n type JourneyDevtoolsMachineMeta,\n type JourneyDevtoolsSerializableSnapshot,\n type JourneyDevtoolsSerializedError\n} from \"./protocol\";\n", "import type { JourneySnapshot, JourneyStepAsyncState } from \"@rxova/journey-core\";\n\nexport const JOURNEY_DEVTOOLS_PROTOCOL_VERSION = 3 as const;\nexport const JOURNEY_DEVTOOLS_CHANNEL = \"__RXOVA_JOURNEY_DEVTOOLS__\" as const;\n\nexport const JOURNEY_DEVTOOLS_BRIDGE_SOURCE = \"rxova-journey-bridge\" as const;\nexport const JOURNEY_DEVTOOLS_EXTENSION_SOURCE = \"rxova-journey-extension\" as const;\n\nexport type JourneyDevtoolsSource =\n | typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE\n | typeof JOURNEY_DEVTOOLS_EXTENSION_SOURCE;\n\nexport type JourneyDevtoolsStepAsyncState = JourneyStepAsyncState;\n\nexport type JourneyDevtoolsSerializableSnapshot = JourneySnapshot<unknown, string>;\n\nexport type JourneyDevtoolsMachineMeta = {\n machineId: string;\n label: string;\n appName: string | null;\n commandsEnabled?: boolean;\n};\n\nexport type JourneyDevtoolsSerializedError = {\n name: string | null;\n message: string;\n stack: string | null;\n cause: unknown;\n};\n\nexport type JourneyDevtoolsCommand =\n | { type: \"goToNextStep\" }\n | { type: \"terminateMachine\" }\n | { type: \"completeJourney\" }\n | { type: \"goToStepById\"; stepId: string }\n | { type: \"goToPreviousStep\"; steps?: number }\n | { type: \"goToLastVisitedStep\" }\n | { type: \"send\"; event: { type: string; payload?: unknown } }\n | { type: \"updateStepMetadata\"; stepId: string; metadata: unknown }\n | { type: \"resetMachine\" }\n | { type: \"clearStepError\"; stepId?: string };\n\nexport type JourneyDevtoolsEnvelopeBase = {\n channel: typeof JOURNEY_DEVTOOLS_CHANNEL;\n version: typeof JOURNEY_DEVTOOLS_PROTOCOL_VERSION;\n source: JourneyDevtoolsSource;\n kind: string;\n machineId: string;\n timestamp: number;\n};\n\nexport type JourneyDevtoolsBridgeRegisterEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"register\";\n meta: JourneyDevtoolsMachineMeta;\n snapshot: JourneyDevtoolsSerializableSnapshot;\n};\n\nexport type JourneyDevtoolsBridgeUnregisterEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"unregister\";\n};\n\nexport type JourneyDevtoolsBridgeSnapshotEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"snapshot\";\n snapshot: JourneyDevtoolsSerializableSnapshot;\n};\n\nexport type JourneyDevtoolsBridgeCommandResultEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"commandResult\";\n requestId: string;\n snapshot: JourneyDevtoolsSerializableSnapshot;\n transitioned?: boolean;\n transitionId?: string;\n error?: JourneyDevtoolsSerializedError;\n};\n\nexport type JourneyDevtoolsBridgeCommandErrorEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"commandError\";\n requestId: string;\n error: JourneyDevtoolsSerializedError;\n};\n\nexport type JourneyDevtoolsExtensionCommandEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_EXTENSION_SOURCE;\n kind: \"command\";\n requestId: string;\n command: JourneyDevtoolsCommand;\n};\n\nexport type JourneyDevtoolsBridgeEnvelope =\n | JourneyDevtoolsBridgeRegisterEnvelope\n | JourneyDevtoolsBridgeUnregisterEnvelope\n | JourneyDevtoolsBridgeSnapshotEnvelope\n | JourneyDevtoolsBridgeCommandResultEnvelope\n | JourneyDevtoolsBridgeCommandErrorEnvelope;\n\nexport type JourneyDevtoolsExtensionEnvelope = JourneyDevtoolsExtensionCommandEnvelope;\n\nexport type JourneyDevtoolsEnvelope =\n | JourneyDevtoolsBridgeEnvelope\n | JourneyDevtoolsExtensionEnvelope;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isKnownSource = (value: unknown): value is JourneyDevtoolsSource =>\n value === JOURNEY_DEVTOOLS_BRIDGE_SOURCE || value === JOURNEY_DEVTOOLS_EXTENSION_SOURCE;\n\n/**\n * Maximum depth for nested object validation.\n * Prevents stack overflow and excessive processing from deeply nested malicious payloads.\n */\nconst MAX_PAYLOAD_DEPTH = 10;\n\n/**\n * Maximum size (in JSON string length) for serialized payloads.\n * Prevents memory exhaustion from extremely large payloads.\n */\nconst MAX_PAYLOAD_SIZE = 500_000; // 500KB\n\n/**\n * Validates that a value is safe for transport.\n * Checks size via a single serialization pass, then validates\n * depth, types, and prototype safety via a structure walk.\n */\nconst isSafePayload = (value: unknown): boolean => {\n try {\n const serialized = JSON.stringify(value);\n if (serialized !== undefined && serialized.length > MAX_PAYLOAD_SIZE) {\n return false;\n }\n } catch {\n return false;\n }\n\n return isStructureSafe(value, 0);\n};\n\nconst isStructureSafe = (value: unknown, depth: number): boolean => {\n if (depth > MAX_PAYLOAD_DEPTH) {\n return false;\n }\n\n if (value === null || value === undefined) {\n return true;\n }\n\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return true;\n }\n\n if (typeof value !== \"object\") {\n return false;\n }\n\n if (Array.isArray(value)) {\n return value.every((item) => isStructureSafe(item, depth + 1));\n }\n\n if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {\n return false;\n }\n\n return Object.values(value).every((prop) => isStructureSafe(prop, depth + 1));\n};\n\nconst hasBaseEnvelopeShape = (value: unknown): value is JourneyDevtoolsEnvelopeBase => {\n if (!isRecord(value)) {\n return false;\n }\n\n return (\n value.channel === JOURNEY_DEVTOOLS_CHANNEL &&\n value.version === JOURNEY_DEVTOOLS_PROTOCOL_VERSION &&\n isKnownSource(value.source) &&\n typeof value.kind === \"string\" &&\n typeof value.machineId === \"string\" &&\n typeof value.timestamp === \"number\"\n );\n};\n\nconst isSendEvent = (value: unknown): value is { type: string; payload?: unknown } => {\n if (!isRecord(value)) {\n return false;\n }\n\n if (typeof value.type !== \"string\" || value.type.length === 0 || value.type.length > 100) {\n return false;\n }\n\n // Validate payload if present\n if (\"payload\" in value && value.payload !== undefined) {\n return isSafePayload(value.payload);\n }\n\n return true;\n};\n\n/**\n * Validates whether an unknown value is a supported devtools command payload.\n */\nexport const isJourneyDevtoolsCommand = (value: unknown): value is JourneyDevtoolsCommand => {\n if (!isRecord(value) || typeof value.type !== \"string\") {\n return false;\n }\n\n // Validate command type is within reasonable length\n if (value.type.length === 0 || value.type.length > 50) {\n return false;\n }\n\n switch (value.type) {\n case \"goToNextStep\":\n case \"terminateMachine\":\n case \"completeJourney\":\n case \"resetMachine\":\n case \"goToLastVisitedStep\":\n // These commands should have no extra properties beyond type\n return Object.keys(value).length === 1;\n case \"goToStepById\":\n return (\n typeof value.stepId === \"string\" &&\n value.stepId.length > 0 &&\n value.stepId.length <= 100 &&\n Object.keys(value).length === 2\n );\n case \"goToPreviousStep\":\n return (\n (value.steps === undefined ||\n (typeof value.steps === \"number\" &&\n Number.isInteger(value.steps) &&\n value.steps >= 1 &&\n value.steps <= 10000)) &&\n Object.keys(value).length <= 2\n );\n case \"send\":\n return isSendEvent(value.event) && Object.keys(value).length === 2;\n case \"updateStepMetadata\":\n return (\n typeof value.stepId === \"string\" &&\n value.stepId.length > 0 &&\n value.stepId.length <= 100 &&\n isSafePayload(value.metadata) &&\n Object.keys(value).length === 3\n );\n case \"clearStepError\":\n return (\n (value.stepId === undefined ||\n (typeof value.stepId === \"string\" && value.stepId.length <= 100)) &&\n Object.keys(value).length <= 2\n );\n default:\n return false;\n }\n};\n\n/**\n * Validates whether an unknown value is a bridge-origin envelope.\n */\nexport const isJourneyDevtoolsBridgeEnvelope = (\n value: unknown\n): value is JourneyDevtoolsBridgeEnvelope => {\n if (!hasBaseEnvelopeShape(value) || value.source !== JOURNEY_DEVTOOLS_BRIDGE_SOURCE) {\n return false;\n }\n\n const envelope = value as Record<string, unknown>;\n\n switch (value.kind) {\n case \"register\":\n return (\n isRecord(envelope.meta) &&\n isRecord(envelope.snapshot) &&\n isSafePayload(envelope.meta) &&\n isSafePayload(envelope.snapshot)\n );\n case \"unregister\":\n return true;\n case \"snapshot\":\n return isRecord(envelope.snapshot) && isSafePayload(envelope.snapshot);\n case \"commandResult\":\n return (\n typeof envelope.requestId === \"string\" &&\n envelope.requestId.length > 0 &&\n envelope.requestId.length <= 100 &&\n isRecord(envelope.snapshot) &&\n isSafePayload(envelope.snapshot) &&\n (!(\"error\" in envelope) || isRecord(envelope.error))\n );\n case \"commandError\":\n return (\n typeof envelope.requestId === \"string\" &&\n envelope.requestId.length > 0 &&\n envelope.requestId.length <= 100 &&\n isRecord(envelope.error)\n );\n default:\n return false;\n }\n};\n\n/**\n * Validates whether an unknown value is an extension-origin command envelope.\n */\nexport const isJourneyDevtoolsExtensionEnvelope = (\n value: unknown\n): value is JourneyDevtoolsExtensionEnvelope => {\n if (!hasBaseEnvelopeShape(value) || value.source !== JOURNEY_DEVTOOLS_EXTENSION_SOURCE) {\n return false;\n }\n\n if (value.kind !== \"command\") {\n return false;\n }\n\n const envelope = value as Record<string, unknown>;\n return (\n typeof envelope.requestId === \"string\" &&\n envelope.requestId.length > 0 &&\n envelope.requestId.length <= 100 &&\n isJourneyDevtoolsCommand(envelope.command)\n );\n};\n\n/**\n * Validates whether an unknown value matches either supported devtools envelope shape.\n */\nexport const isJourneyDevtoolsEnvelope = (value: unknown): value is JourneyDevtoolsEnvelope =>\n isJourneyDevtoolsBridgeEnvelope(value) || isJourneyDevtoolsExtensionEnvelope(value);\n", "import type {\n JourneyEventPayloadMap,\n JourneyMachine,\n JourneySendResult,\n JourneySnapshot\n} from \"@rxova/journey-core\";\nimport {\n JOURNEY_DEVTOOLS_BRIDGE_SOURCE,\n JOURNEY_DEVTOOLS_CHANNEL,\n JOURNEY_DEVTOOLS_EXTENSION_SOURCE,\n JOURNEY_DEVTOOLS_PROTOCOL_VERSION,\n isJourneyDevtoolsEnvelope,\n type JourneyDevtoolsBridgeCommandErrorEnvelope,\n type JourneyDevtoolsBridgeCommandResultEnvelope,\n type JourneyDevtoolsBridgeEnvelope,\n type JourneyDevtoolsBridgeRegisterEnvelope,\n type JourneyDevtoolsBridgeSnapshotEnvelope,\n type JourneyDevtoolsBridgeUnregisterEnvelope,\n type JourneyDevtoolsCommand,\n type JourneyDevtoolsExtensionCommandEnvelope,\n type JourneyDevtoolsMachineMeta,\n type JourneyDevtoolsSerializableSnapshot,\n type JourneyDevtoolsSerializedError\n} from \"./protocol\";\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nexport type JourneyDevtoolsBridgeOptions = {\n machineId?: string;\n label?: string;\n enabled?: boolean;\n appName?: string;\n commandsEnabled?: boolean;\n};\n\ntype SendOutcome<TContext, TStepId extends string, TStepMeta> = {\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>;\n transitioned?: boolean;\n transitionId?: string;\n error?: JourneyDevtoolsSerializedError;\n};\n\ntype SnapshotScheduleKind = \"raf\" | \"timeout\";\n\nconst DEFAULT_MACHINE_LABEL = \"Journey Machine\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isJourneyAsyncPhase = (\n value: unknown\n): value is JourneyDevtoolsSerializableSnapshot[\"async\"][\"byStep\"][string][\"phase\"] =>\n value === \"idle\" ||\n value === \"evaluating-when\" ||\n value === \"running-effect\" ||\n value === \"error\";\n\ntype JourneyImportMetaEnv = {\n DEV?: unknown;\n PROD?: unknown;\n};\n\nconst resolveImportMetaEnvironment = (\n bundlerEnv: JourneyImportMetaEnv | null | undefined\n): boolean | null => {\n if (!isRecord(bundlerEnv)) {\n return null;\n }\n\n if (bundlerEnv.PROD === true) {\n return false;\n }\n\n if (bundlerEnv.DEV === true) {\n return true;\n }\n\n return null;\n};\n\nconst resolveNodeEnvironment = (nodeEnv: string | undefined): boolean | null => {\n if (typeof nodeEnv !== \"string\") {\n return null;\n }\n\n return nodeEnv !== \"production\";\n};\n\nexport const resolveNonProductionEnvironment = (\n options: {\n bundlerEnv?: JourneyImportMetaEnv | null | undefined;\n nodeEnv?: string | undefined;\n } = {}\n): boolean => {\n const resolvedBundlerEnv =\n \"bundlerEnv\" in options\n ? options.bundlerEnv\n : (import.meta as ImportMeta & { env?: JourneyImportMetaEnv }).env;\n const resolvedNodeEnv =\n \"nodeEnv\" in options\n ? options.nodeEnv\n : typeof process !== \"undefined\"\n ? process.env?.NODE_ENV\n : undefined;\n\n return (\n resolveImportMetaEnvironment(resolvedBundlerEnv) ??\n resolveNodeEnvironment(resolvedNodeEnv) ??\n false\n );\n};\n\nconst resolveWindowTargetOrigin = (): string => {\n if (typeof window === \"undefined\") {\n return \"*\";\n }\n\n return window.location.origin === \"null\" ? \"*\" : window.location.origin;\n};\n\n// No session token infrastructure needed\n\n/**\n * Validates that the message origin matches the current window origin.\n * This prevents messages from other origins from being processed.\n *\n * Note: This is part of defense-in-depth but not a hard security boundary.\n * Code running in the same origin can still send messages.\n */\nconst isExpectedWindowOrigin = (origin: string): boolean => {\n if (origin.length === 0) {\n return false;\n }\n\n if (typeof window === \"undefined\") {\n return false;\n }\n\n const expected = window.location.origin;\n if (expected === \"null\") {\n // For file:// or sandboxed contexts where origin is \"null\"\n return origin === \"null\";\n }\n\n // Strict equality check - no wildcard matching\n return origin === expected;\n};\n\nconst createMachineId = (): string =>\n `journey-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n\n/**\n * Simple rate limiter to prevent command abuse.\n * Tracks command timestamps and enforces a maximum rate.\n */\nclass CommandRateLimiter {\n private commandTimestamps: number[] = [];\n private readonly maxCommandsPerWindow: number;\n private readonly windowMs: number;\n\n constructor(maxCommandsPerWindow = 100, windowMs = 10000) {\n this.maxCommandsPerWindow = maxCommandsPerWindow;\n this.windowMs = windowMs;\n }\n\n /**\n * Checks if a command is allowed based on rate limits.\n * Returns true if allowed, false if rate limit exceeded.\n */\n isAllowed(): boolean {\n const now = Date.now();\n const windowStart = now - this.windowMs;\n\n // Remove old timestamps outside the window\n this.commandTimestamps = this.commandTimestamps.filter((ts) => ts > windowStart);\n\n if (this.commandTimestamps.length >= this.maxCommandsPerWindow) {\n return false;\n }\n\n this.commandTimestamps.push(now);\n return true;\n }\n\n reset(): void {\n this.commandTimestamps = [];\n }\n}\n\nconst cloneForTransport = (value: unknown): unknown => {\n const transportValue =\n typeof structuredClone === \"function\"\n ? (() => {\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n })()\n : value;\n const seen = new WeakSet<object>();\n\n try {\n const serialized = JSON.stringify(transportValue, (_key, currentValue) => {\n if (typeof currentValue === \"bigint\") {\n return currentValue.toString();\n }\n if (typeof currentValue === \"function\") {\n return `[Function ${currentValue.name || \"anonymous\"}]`;\n }\n if (typeof currentValue === \"symbol\") {\n return currentValue.toString();\n }\n if (typeof currentValue === \"object\" && currentValue !== null) {\n if (seen.has(currentValue)) {\n return \"[Circular]\";\n }\n seen.add(currentValue);\n }\n return currentValue;\n });\n\n if (serialized === undefined) {\n return undefined;\n }\n\n return JSON.parse(serialized) as unknown;\n } catch {\n return String(value);\n }\n};\n\nconst serializeError = (error: unknown): JourneyDevtoolsSerializedError => {\n if (error instanceof Error) {\n const cause =\n \"cause\" in error && (error as { cause?: unknown }).cause !== undefined\n ? (error as { cause?: unknown }).cause\n : null;\n return {\n name: error.name,\n message: error.message,\n stack: typeof error.stack === \"string\" ? error.stack : null,\n cause: cloneForTransport(cause)\n };\n }\n\n return {\n name: null,\n message: typeof error === \"string\" ? error : \"Unknown error\",\n stack: null,\n cause: cloneForTransport(error)\n };\n};\n\nconst serializeSnapshot = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>\n): JourneyDevtoolsSerializableSnapshot => {\n const byStep: Record<string, JourneyDevtoolsSerializableSnapshot[\"async\"][\"byStep\"][string]> = {};\n\n for (const [stepId, stepState] of Object.entries(\n snapshot.async.byStep as Record<string, unknown>\n )) {\n if (!isRecord(stepState)) {\n continue;\n }\n\n byStep[stepId] = {\n phase: isJourneyAsyncPhase(stepState.phase) ? stepState.phase : \"idle\",\n eventType: typeof stepState.eventType === \"string\" ? stepState.eventType : null,\n transitionId: typeof stepState.transitionId === \"string\" ? stepState.transitionId : null,\n error: stepState.error === null ? null : cloneForTransport(stepState.error)\n };\n }\n\n return {\n currentStepId: String(snapshot.currentStepId),\n context: cloneForTransport(snapshot.context),\n history: {\n timeline: snapshot.history.timeline.map((stepId) => String(stepId)),\n index: snapshot.history.index\n },\n visited: Object.fromEntries(\n Object.entries(snapshot.visited as Record<string, boolean>).map(([stepId, isVisited]) => [\n String(stepId),\n isVisited === true\n ])\n ),\n stepMeta: cloneForTransport(snapshot.stepMeta) as Record<string, unknown>,\n status: snapshot.status,\n async: {\n isLoading: snapshot.async.isLoading,\n byStep\n }\n };\n};\n\nconst isKnownStepId = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n stepId: string\n): stepId is TStepId => stepId in snapshot.stepMeta;\n\nconst assertKnownStepId = <TContext, TStepId extends string, TStepMeta>(\n machine: JourneyMachine<TContext, TStepId, string, Record<never, never>, TStepMeta>,\n stepId: string,\n commandType: JourneyDevtoolsCommand[\"type\"]\n): TStepId => {\n if (!isKnownStepId(machine.getSnapshot(), stepId)) {\n throw new Error(`Unknown stepId \"${stepId}\" for \"${commandType}\" command.`);\n }\n return stepId;\n};\n\nconst toSendOutcome = <TContext, TStepId extends string, TStepMeta>(\n result: JourneySendResult<TContext, TStepId, TStepMeta>\n): SendOutcome<TContext, TStepId, TStepMeta> => ({\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {}),\n ...(\"error\" in result ? { error: serializeError(result.error) } : {})\n});\n\nconst runCommand = async <TContext, TStepId extends string, TStepMeta>(\n machine: JourneyMachine<TContext, TStepId, string, Record<never, never>, TStepMeta>,\n command: JourneyDevtoolsCommand\n): Promise<SendOutcome<TContext, TStepId, TStepMeta>> => {\n switch (command.type) {\n case \"goToNextStep\":\n case \"completeJourney\": {\n const result = await machine.send({ type: command.type });\n return toSendOutcome(result);\n }\n case \"terminateMachine\": {\n const result = await machine.send({ type: \"terminateJourney\" });\n return toSendOutcome(result);\n }\n case \"goToStepById\": {\n const stepId = assertKnownStepId(machine, command.stepId, command.type);\n const result = await machine.send({\n type: \"goToStepById\",\n stepId\n });\n return toSendOutcome(result);\n }\n case \"goToPreviousStep\": {\n const result = await machine.goToPreviousStep(command.steps);\n return toSendOutcome(result);\n }\n case \"goToLastVisitedStep\": {\n const result = await machine.goToLastVisitedStep();\n return toSendOutcome(result);\n }\n case \"send\": {\n const sendEvent =\n command.event.payload === undefined\n ? { type: command.event.type }\n : { type: command.event.type, payload: command.event.payload };\n const result: JourneySendResult<TContext, TStepId, TStepMeta> = await machine.send(sendEvent);\n return toSendOutcome(result);\n }\n case \"updateStepMetadata\": {\n const stepId = assertKnownStepId(machine, command.stepId, command.type);\n return {\n snapshot: machine.updateStepMetadata(stepId, () => command.metadata as TStepMeta)\n };\n }\n case \"resetMachine\":\n return {\n snapshot: machine.resetMachine()\n };\n case \"clearStepError\": {\n const stepId =\n command.stepId === undefined\n ? undefined\n : assertKnownStepId(machine, command.stepId, command.type);\n return {\n snapshot: machine.clearStepError(stepId)\n };\n }\n }\n};\n\n/**\n * Attaches a journey machine to the browser devtools transport and returns\n * a detach function that unsubscribes listeners and unregisters the machine.\n */\nexport const attachJourneyDevtools = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TStepMeta\n>(\n machine: JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>,\n options: JourneyDevtoolsBridgeOptions = {}\n): (() => void) => {\n const enabled = options.enabled ?? resolveNonProductionEnvironment();\n if (!enabled || typeof window === \"undefined\") {\n return () => {};\n }\n const commandsEnabled = options.commandsEnabled ?? resolveNonProductionEnvironment();\n\n const machineId = options.machineId?.trim() || createMachineId();\n const meta: JourneyDevtoolsMachineMeta = {\n machineId,\n label: options.label?.trim() || DEFAULT_MACHINE_LABEL,\n appName:\n options.appName?.trim() || (typeof document !== \"undefined\" ? document.title : \"\") || null,\n commandsEnabled\n };\n const targetOrigin = resolveWindowTargetOrigin();\n\n const createBaseEnvelope = <TKind extends JourneyDevtoolsBridgeEnvelope[\"kind\"]>(\n kind: TKind\n ) => ({\n channel: JOURNEY_DEVTOOLS_CHANNEL,\n version: JOURNEY_DEVTOOLS_PROTOCOL_VERSION,\n source: JOURNEY_DEVTOOLS_BRIDGE_SOURCE,\n kind,\n machineId,\n timestamp: Date.now()\n });\n\n const post = (envelope: JourneyDevtoolsBridgeEnvelope) => {\n try {\n window.postMessage(envelope, targetOrigin);\n } catch {\n // Swallow transport failures so bridge lifecycle and commands remain non-throwing.\n }\n };\n\n const postSnapshot = (snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>) => {\n const envelope: JourneyDevtoolsBridgeSnapshotEnvelope = {\n ...createBaseEnvelope(\"snapshot\"),\n snapshot: serializeSnapshot(snapshot)\n };\n post(envelope);\n };\n\n let isDetached = false;\n const rateLimiter = new CommandRateLimiter();\n let pendingSnapshot: JourneySnapshot<TContext, TStepId, TStepMeta> | null = null;\n let scheduledSnapshotHandle: number | ReturnType<typeof globalThis.setTimeout> | null = null;\n let scheduledSnapshotKind: SnapshotScheduleKind | null = null;\n\n const clearScheduledSnapshotState = () => {\n pendingSnapshot = null;\n scheduledSnapshotHandle = null;\n scheduledSnapshotKind = null;\n };\n\n const flushScheduledSnapshot = () => {\n const snapshot = pendingSnapshot;\n clearScheduledSnapshotState();\n\n if (!snapshot || isDetached) {\n return;\n }\n\n postSnapshot(snapshot);\n };\n\n const scheduleSnapshotPost = (snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>) => {\n pendingSnapshot = snapshot;\n if (scheduledSnapshotHandle !== null) {\n return;\n }\n\n if (typeof window.requestAnimationFrame === \"function\") {\n scheduledSnapshotKind = \"raf\";\n scheduledSnapshotHandle = window.requestAnimationFrame(() => {\n flushScheduledSnapshot();\n });\n return;\n }\n\n scheduledSnapshotKind = \"timeout\";\n scheduledSnapshotHandle = globalThis.setTimeout(() => {\n flushScheduledSnapshot();\n }, 0);\n };\n\n const cancelScheduledSnapshot = () => {\n if (scheduledSnapshotHandle === null) {\n clearScheduledSnapshotState();\n return;\n }\n\n if (scheduledSnapshotKind === \"raf\" && typeof window.cancelAnimationFrame === \"function\") {\n window.cancelAnimationFrame(scheduledSnapshotHandle as number);\n } else {\n globalThis.clearTimeout(scheduledSnapshotHandle);\n }\n\n clearScheduledSnapshotState();\n };\n\n const onMessage = (event: MessageEvent<unknown>) => {\n if (\n event.source !== window ||\n !isExpectedWindowOrigin(event.origin) ||\n isDetached ||\n !isJourneyDevtoolsEnvelope(event.data)\n ) {\n return;\n }\n\n if (event.data.source !== JOURNEY_DEVTOOLS_EXTENSION_SOURCE || event.data.kind !== \"command\") {\n return;\n }\n\n const commandEnvelope: JourneyDevtoolsExtensionCommandEnvelope = event.data;\n if (commandEnvelope.machineId !== machineId) {\n return;\n }\n\n // Rate limiting to prevent command abuse\n if (!rateLimiter.isAllowed()) {\n const errorEnvelope: JourneyDevtoolsBridgeCommandErrorEnvelope = {\n ...createBaseEnvelope(\"commandError\"),\n requestId: commandEnvelope.requestId,\n error: serializeError(\n \"Command rate limit exceeded. Too many commands in a short time window.\"\n )\n };\n post(errorEnvelope);\n return;\n }\n\n if (!commandsEnabled) {\n const errorEnvelope: JourneyDevtoolsBridgeCommandErrorEnvelope = {\n ...createBaseEnvelope(\"commandError\"),\n requestId: commandEnvelope.requestId,\n error: serializeError(\"Bridge commands are disabled by configuration.\")\n };\n post(errorEnvelope);\n return;\n }\n\n const run = async () => {\n try {\n const outcome = await runCommand(\n machine as JourneyMachine<TContext, TStepId, string, Record<never, never>, TStepMeta>,\n commandEnvelope.command\n );\n if (isDetached) {\n return;\n }\n\n const resultEnvelope: JourneyDevtoolsBridgeCommandResultEnvelope = {\n ...createBaseEnvelope(\"commandResult\"),\n requestId: commandEnvelope.requestId,\n snapshot: serializeSnapshot(outcome.snapshot),\n ...(outcome.transitioned !== undefined ? { transitioned: outcome.transitioned } : {}),\n ...(outcome.transitionId ? { transitionId: outcome.transitionId } : {}),\n ...(\"error\" in outcome ? { error: outcome.error } : {})\n };\n post(resultEnvelope);\n } catch (error) {\n if (isDetached) {\n return;\n }\n\n const errorEnvelope: JourneyDevtoolsBridgeCommandErrorEnvelope = {\n ...createBaseEnvelope(\"commandError\"),\n requestId: commandEnvelope.requestId,\n error: serializeError(error)\n };\n post(errorEnvelope);\n }\n };\n\n void run();\n };\n\n window.addEventListener(\"message\", onMessage);\n\n const unsubscribe = machine.subscribe(() => {\n if (isDetached) {\n return;\n }\n scheduleSnapshotPost(machine.getSnapshot());\n });\n\n const registerEnvelope: JourneyDevtoolsBridgeRegisterEnvelope = {\n ...createBaseEnvelope(\"register\"),\n meta,\n snapshot: serializeSnapshot(machine.getSnapshot())\n };\n post(registerEnvelope);\n\n return () => {\n if (isDetached) {\n return;\n }\n\n isDetached = true;\n rateLimiter.reset();\n unsubscribe();\n window.removeEventListener(\"message\", onMessage);\n cancelScheduledSnapshot();\n\n const unregisterEnvelope: JourneyDevtoolsBridgeUnregisterEnvelope = {\n ...createBaseEnvelope(\"unregister\")\n };\n post(unregisterEnvelope);\n };\n};\n"],
5
+ "mappings": "yaAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,oCAAAE,EAAA,6BAAAC,EAAA,sCAAAC,EAAA,sCAAAC,EAAA,0BAAAC,EAAA,oCAAAC,EAAA,6BAAAC,EAAA,8BAAAC,EAAA,uCAAAC,IAAA,eAAAC,EAAAX,ICEO,IAAMY,EAAoC,EACpCC,EAA2B,6BAE3BC,EAAiC,uBACjCC,EAAoC,0BAoG3CC,EAAYC,GAChB,OAAOA,GAAU,UAAYA,IAAU,KAEnCC,GAAiBD,GACrBA,IAAUH,GAAkCG,IAAUF,EAmBxD,IAAMI,EAAiBC,GAA4B,CACjD,GAAI,CACF,IAAMC,EAAa,KAAK,UAAUD,CAAK,EACvC,GAAIC,IAAe,QAAaA,EAAW,OAAS,IAClD,MAAO,EAEX,MAAQ,CACN,MAAO,EACT,CAEA,OAAOC,EAAgBF,EAAO,CAAC,CACjC,EAEME,EAAkB,CAACF,EAAgBG,IACnCA,EAAQ,GACH,GAGLH,GAAU,MAIV,OAAOA,GAAU,UAAY,OAAOA,GAAU,UAAY,OAAOA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,eAAiB,OAAY,CAAE,aAAcA,EAAQ,YAAa,EAAI,CAAC,EACnF,GAAIA,EAAQ,aAAe,CAAE,aAAcA,EAAQ,YAAa,EAAI,CAAC,EACrE,GAAI,UAAWA,EAAU,CAAE,MAAOA,EAAQ,KAAM,EAAI,CAAC,CACvD,EACAlB,EAAKmB,CAAc,CACrB,OAAS7C,EAAO,CACd,GAAI6B,EACF,OAGF,IAAMc,EAA2D,CAC/D,GAAGrB,EAAmB,cAAc,EACpC,UAAWoB,EAAgB,UAC3B,MAAO3C,EAAeC,CAAK,CAC7B,EACA0B,EAAKiB,CAAa,CACpB,CACF,GAES,CACX,EAEA,OAAO,iBAAiB,UAAWL,CAAS,EAE5C,IAAMQ,EAAcpC,EAAQ,UAAU,IAAM,CACtCmB,GAGJO,EAAqB1B,EAAQ,YAAY,CAAC,CAC5C,CAAC,EAEKqC,EAA0D,CAC9D,GAAGzB,EAAmB,UAAU,EAChC,KAAAF,EACA,SAAUlB,EAAkBQ,EAAQ,YAAY,CAAC,CACnD,EACA,OAAAgB,EAAKqB,CAAgB,EAEd,IAAM,CACX,GAAIlB,EACF,OAGFA,EAAa,GACbC,EAAY,MAAM,EAClBgB,EAAY,EACZ,OAAO,oBAAoB,UAAWR,CAAS,EAC/CD,EAAwB,EAExB,IAAMW,EAA8D,CAClE,GAAG1B,EAAmB,YAAY,CACpC,EACAI,EAAKsB,CAAkB,CACzB,CACF",
6
+ "names": ["index_exports", "__export", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "JOURNEY_DEVTOOLS_CHANNEL", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "JOURNEY_DEVTOOLS_PROTOCOL_VERSION", "attachJourneyDevtools", "isJourneyDevtoolsBridgeEnvelope", "isJourneyDevtoolsCommand", "isJourneyDevtoolsEnvelope", "isJourneyDevtoolsExtensionEnvelope", "__toCommonJS", "JOURNEY_DEVTOOLS_PROTOCOL_VERSION", "JOURNEY_DEVTOOLS_CHANNEL", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "isRecord", "value", "isKnownSource", "isSafePayload", "value", "serialized", "isStructureSafe", "depth", "item", "prop", "hasBaseEnvelopeShape", "isRecord", "JOURNEY_DEVTOOLS_CHANNEL", "isKnownSource", "isSendEvent", "isJourneyDevtoolsCommand", "isJourneyDevtoolsBridgeEnvelope", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "envelope", "isJourneyDevtoolsExtensionEnvelope", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "isJourneyDevtoolsEnvelope", "import_meta", "DEFAULT_MACHINE_LABEL", "isRecord", "value", "isJourneyAsyncPhase", "resolveImportMetaEnvironment", "bundlerEnv", "resolveNodeEnvironment", "nodeEnv", "resolveNonProductionEnvironment", "options", "resolvedBundlerEnv", "resolvedNodeEnv", "resolveWindowTargetOrigin", "isExpectedWindowOrigin", "origin", "expected", "createMachineId", "CommandRateLimiter", "maxCommandsPerWindow", "windowMs", "now", "windowStart", "ts", "cloneForTransport", "transportValue", "seen", "serialized", "_key", "currentValue", "serializeError", "error", "cause", "serializeSnapshot", "snapshot", "byStep", "stepId", "stepState", "isVisited", "isKnownStepId", "assertKnownStepId", "machine", "commandType", "toSendOutcome", "result", "runCommand", "command", "sendEvent", "attachJourneyDevtools", "commandsEnabled", "machineId", "meta", "targetOrigin", "createBaseEnvelope", "kind", "JOURNEY_DEVTOOLS_CHANNEL", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "post", "envelope", "postSnapshot", "isDetached", "rateLimiter", "pendingSnapshot", "scheduledSnapshotHandle", "scheduledSnapshotKind", "clearScheduledSnapshotState", "flushScheduledSnapshot", "scheduleSnapshotPost", "cancelScheduledSnapshot", "onMessage", "event", "isJourneyDevtoolsEnvelope", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "commandEnvelope", "errorEnvelope", "outcome", "resultEnvelope", "unsubscribe", "registerEnvelope", "unregisterEnvelope"]
7
7
  }
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var v=3,S="__RXOVA_JOURNEY_DEVTOOLS__",c="rxova-journey-bridge",E="rxova-journey-extension",p=e=>typeof e=="object"&&e!==null,k=e=>e===c||e===E;var d=(e,t=0)=>{if(t>10)return!1;if(e==null||["string","number","boolean"].includes(typeof e))return!0;if(typeof e=="object"){try{if(JSON.stringify(e).length>5e5)return!1}catch{return!1}return Array.isArray(e)?e.every(o=>d(o,t+1)):Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null?!1:Object.values(e).every(o=>d(o,t+1))}return!1},w=e=>p(e)?e.channel===S&&e.version===3&&k(e.source)&&typeof e.kind=="string"&&typeof e.machineId=="string"&&typeof e.timestamp=="number":!1,L=e=>!p(e)||typeof e.type!="string"||e.type.length===0||e.type.length>100?!1:"payload"in e&&e.payload!==void 0?d(e.payload):!0,_=e=>{if(!p(e)||typeof e.type!="string"||e.type.length===0||e.type.length>50)return!1;switch(e.type){case"goToNextStep":case"terminateMachine":case"completeJourney":case"resetMachine":case"goToLastVisitedStep":return Object.keys(e).length===1;case"goToStepById":return typeof e.stepId=="string"&&e.stepId.length>0&&e.stepId.length<=100&&Object.keys(e).length===2;case"goToPreviousStep":return(e.steps===void 0||typeof e.steps=="number"&&Number.isInteger(e.steps)&&e.steps>=1&&e.steps<=1e4)&&Object.keys(e).length<=2;case"send":return L(e.event)&&Object.keys(e).length===2;case"updateStepMetadata":return typeof e.stepId=="string"&&e.stepId.length>0&&e.stepId.length<=100&&d(e.metadata)&&Object.keys(e).length===3;case"clearStepError":return(e.stepId===void 0||typeof e.stepId=="string"&&e.stepId.length<=100)&&Object.keys(e).length<=2;default:return!1}},R=e=>{if(!w(e)||e.source!==c)return!1;let t=e;switch(e.kind){case"register":return p(t.meta)&&p(t.snapshot)&&d(t.meta)&&d(t.snapshot);case"unregister":return!0;case"snapshot":return p(t.snapshot)&&d(t.snapshot);case"commandResult":return typeof t.requestId=="string"&&t.requestId.length>0&&t.requestId.length<=100&&p(t.snapshot)&&d(t.snapshot);case"commandError":return typeof t.requestId=="string"&&t.requestId.length>0&&t.requestId.length<=100&&p(t.error);default:return!1}},x=e=>{if(!w(e)||e.source!==E||e.kind!=="command")return!1;let t=e;return typeof t.requestId=="string"&&t.requestId.length>0&&t.requestId.length<=100&&_(t.command)},f=e=>R(e)||x(e);var U="Journey Machine",A=e=>typeof e=="object"&&e!==null,Y=e=>e==="idle"||e==="evaluating-when"||e==="running-effect"||e==="error",P=()=>{let e=typeof process<"u"?process.env?.NODE_ENV:void 0;return typeof e!="string"?!1:e!=="production"},V=()=>{let e=typeof process<"u"?process.env?.NODE_ENV:void 0;return typeof e!="string"?!1:e!=="production"},j=()=>typeof window>"u"||window.location.origin==="null"?"*":window.location.origin,q=e=>{if(e.length===0||typeof window>"u")return!1;let t=window.location.origin;return t==="null"?e==="null":e===t},z=()=>`journey-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,T=class{constructor(t=100,n=1e4){this.commandTimestamps=[];this.maxCommandsPerWindow=t,this.windowMs=n}isAllowed(){let t=Date.now(),n=t-this.windowMs;return this.commandTimestamps=this.commandTimestamps.filter(o=>o>n),this.commandTimestamps.length>=this.maxCommandsPerWindow?!1:(this.commandTimestamps.push(t),!0)}reset(){this.commandTimestamps=[]}},g=e=>{if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}let t=new WeakSet;try{let n=JSON.stringify(e,(o,r)=>{if(typeof r=="bigint")return r.toString();if(typeof r=="function")return`[Function ${r.name||"anonymous"}]`;if(typeof r=="symbol")return r.toString();if(typeof r=="object"&&r!==null){if(t.has(r))return"[Circular]";t.add(r)}return r});return n===void 0?void 0:JSON.parse(n)}catch{return String(e)}},J=e=>{if(e instanceof Error){let t="cause"in e&&e.cause!==void 0?e.cause:null;return{name:e.name,message:e.message,stack:typeof e.stack=="string"?e.stack:null,cause:g(t)}}return{name:null,message:typeof e=="string"?e:"Unknown error",stack:null,cause:g(e)}},D=e=>{let t={};for(let[n,o]of Object.entries(e.async.byStep))A(o)&&(t[n]={phase:Y(o.phase)?o.phase:"idle",eventType:typeof o.eventType=="string"?o.eventType:null,transitionId:typeof o.transitionId=="string"?o.transitionId:null,error:o.error===null?null:g(o.error)});return{currentStepId:String(e.currentStepId),context:g(e.context),history:{timeline:e.history.timeline.map(n=>String(n)),index:e.history.index},visited:Object.fromEntries(Object.entries(e.visited).map(([n,o])=>[String(n),o===!0])),stepMeta:g(e.stepMeta),status:e.status,async:{isLoading:e.async.isLoading,byStep:t}}},X=(e,t)=>t in e.stepMeta,O=(e,t,n)=>{if(!X(e.getSnapshot(),t))throw new Error(`Unknown stepId "${t}" for "${n}" command.`);return t},G=async(e,t)=>{switch(t.type){case"goToNextStep":case"completeJourney":{let n=await e.send({type:t.type});return{snapshot:n.snapshot,transitioned:n.transitioned,...n.transitionId?{transitionId:n.transitionId}:{}}}case"terminateMachine":{let n=await e.send({type:"terminateJourney"});return{snapshot:n.snapshot,transitioned:n.transitioned,...n.transitionId?{transitionId:n.transitionId}:{}}}case"goToStepById":{let n=O(e,t.stepId,t.type),o=await e.send({type:"goToStepById",stepId:n});return{snapshot:o.snapshot,transitioned:o.transitioned,...o.transitionId?{transitionId:o.transitionId}:{}}}case"goToPreviousStep":{let n=await e.goToPreviousStep(t.steps);return{snapshot:n.snapshot,transitioned:n.transitioned,...n.transitionId?{transitionId:n.transitionId}:{}}}case"goToLastVisitedStep":{let n=await e.goToLastVisitedStep();return{snapshot:n.snapshot,transitioned:n.transitioned,...n.transitionId?{transitionId:n.transitionId}:{}}}case"send":{let n=t.event.payload===void 0?{type:t.event.type}:{type:t.event.type,payload:t.event.payload},o=await e.send(n);return{snapshot:o.snapshot,transitioned:o.transitioned,...o.transitionId?{transitionId:o.transitionId}:{}}}case"updateStepMetadata":{let n=O(e,t.stepId,t.type);return{snapshot:e.updateStepMetadata(n,()=>t.metadata)}}case"resetMachine":return{snapshot:e.resetMachine()};case"clearStepError":{let n=t.stepId===void 0?void 0:O(e,t.stepId,t.type);return{snapshot:e.clearStepError(n)}}}},H=(e,t={})=>{if(!(t.enabled??P())||typeof window>"u")return()=>{};let o=t.commandsEnabled??V(),r=t.machineId?.trim()||z(),b={machineId:r,label:t.label?.trim()||U,appName:t.appName?.trim()||(typeof document<"u"?document.title:"")||null,commandsEnabled:o},C=j(),u=s=>({channel:S,version:3,source:c,kind:s,machineId:r,timestamp:Date.now()}),l=s=>{window.postMessage(s,C)},N=s=>{let a={...u("snapshot"),snapshot:D(s)};l(a)},y=!1,I=new T,h=s=>{if(s.source!==window||!q(s.origin)||y||!f(s.data)||s.data.source!==E||s.data.kind!=="command")return;let a=s.data;if(a.machineId!==r)return;if(!I.isAllowed()){let i={...u("commandError"),requestId:a.requestId,error:J("Command rate limit exceeded. Too many commands in a short time window.")};l(i);return}if(!o){let i={...u("commandError"),requestId:a.requestId,error:J("Bridge commands are disabled by configuration.")};l(i);return}(async()=>{try{let i=await G(e,a.command);if(y)return;let m={...u("commandResult"),requestId:a.requestId,snapshot:D(i.snapshot),...i.transitioned!==void 0?{transitioned:i.transitioned}:{},...i.transitionId?{transitionId:i.transitionId}:{}};l(m)}catch(i){if(y)return;let m={...u("commandError"),requestId:a.requestId,error:J(i)};l(m)}})()};window.addEventListener("message",h);let B=e.subscribe(()=>{y||N(e.getSnapshot())}),M={...u("register"),meta:b,snapshot:D(e.getSnapshot())};return l(M),()=>{if(y)return;y=!0,I.reset(),B(),window.removeEventListener("message",h);let s={...u("unregister")};l(s)}};export{c as JOURNEY_DEVTOOLS_BRIDGE_SOURCE,S as JOURNEY_DEVTOOLS_CHANNEL,E as JOURNEY_DEVTOOLS_EXTENSION_SOURCE,v as JOURNEY_DEVTOOLS_PROTOCOL_VERSION,H as attachJourneyDevtools,R as isJourneyDevtoolsBridgeEnvelope,_ as isJourneyDevtoolsCommand,f as isJourneyDevtoolsEnvelope,x as isJourneyDevtoolsExtensionEnvelope};
1
+ var w=3,J="__RXOVA_JOURNEY_DEVTOOLS__",S="rxova-journey-bridge",g="rxova-journey-extension",a=e=>typeof e=="object"&&e!==null,G=e=>e===S||e===g;var c=e=>{try{let t=JSON.stringify(e);if(t!==void 0&&t.length>5e5)return!1}catch{return!1}return I(e,0)},I=(e,t)=>t>10?!1:e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:typeof e!="object"?!1:Array.isArray(e)?e.every(n=>I(n,t+1)):Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null?!1:Object.values(e).every(n=>I(n,t+1)),B=e=>a(e)?e.channel===J&&e.version===3&&G(e.source)&&typeof e.kind=="string"&&typeof e.machineId=="string"&&typeof e.timestamp=="number":!1,H=e=>!a(e)||typeof e.type!="string"||e.type.length===0||e.type.length>100?!1:"payload"in e&&e.payload!==void 0?c(e.payload):!0,k=e=>{if(!a(e)||typeof e.type!="string"||e.type.length===0||e.type.length>50)return!1;switch(e.type){case"goToNextStep":case"terminateMachine":case"completeJourney":case"resetMachine":case"goToLastVisitedStep":return Object.keys(e).length===1;case"goToStepById":return typeof e.stepId=="string"&&e.stepId.length>0&&e.stepId.length<=100&&Object.keys(e).length===2;case"goToPreviousStep":return(e.steps===void 0||typeof e.steps=="number"&&Number.isInteger(e.steps)&&e.steps>=1&&e.steps<=1e4)&&Object.keys(e).length<=2;case"send":return H(e.event)&&Object.keys(e).length===2;case"updateStepMetadata":return typeof e.stepId=="string"&&e.stepId.length>0&&e.stepId.length<=100&&c(e.metadata)&&Object.keys(e).length===3;case"clearStepError":return(e.stepId===void 0||typeof e.stepId=="string"&&e.stepId.length<=100)&&Object.keys(e).length<=2;default:return!1}},L=e=>{if(!B(e)||e.source!==S)return!1;let t=e;switch(e.kind){case"register":return a(t.meta)&&a(t.snapshot)&&c(t.meta)&&c(t.snapshot);case"unregister":return!0;case"snapshot":return a(t.snapshot)&&c(t.snapshot);case"commandResult":return typeof t.requestId=="string"&&t.requestId.length>0&&t.requestId.length<=100&&a(t.snapshot)&&c(t.snapshot)&&(!("error"in t)||a(t.error));case"commandError":return typeof t.requestId=="string"&&t.requestId.length>0&&t.requestId.length<=100&&a(t.error);default:return!1}},U=e=>{if(!B(e)||e.source!==g||e.kind!=="command")return!1;let t=e;return typeof t.requestId=="string"&&t.requestId.length>0&&t.requestId.length<=100&&k(t.command)},x=e=>L(e)||U(e);var K="Journey Machine",P=e=>typeof e=="object"&&e!==null,F=e=>e==="idle"||e==="evaluating-when"||e==="running-effect"||e==="error",W=e=>P(e)?e.PROD===!0?!1:e.DEV===!0?!0:null:null,$=e=>typeof e!="string"?null:e!=="production",A=(e={})=>{let t="bundlerEnv"in e?e.bundlerEnv:import.meta.env,n="nodeEnv"in e?e.nodeEnv:typeof process<"u"?process.env?.NODE_ENV:void 0;return W(t)??$(n)??!1},Z=()=>typeof window>"u"||window.location.origin==="null"?"*":window.location.origin,Q=e=>{if(e.length===0||typeof window>"u")return!1;let t=window.location.origin;return t==="null"?e==="null":e===t},ee=()=>`journey-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,b=class{constructor(t=100,n=1e4){this.commandTimestamps=[];this.maxCommandsPerWindow=t,this.windowMs=n}isAllowed(){let t=Date.now(),n=t-this.windowMs;return this.commandTimestamps=this.commandTimestamps.filter(o=>o>n),this.commandTimestamps.length>=this.maxCommandsPerWindow?!1:(this.commandTimestamps.push(t),!0)}reset(){this.commandTimestamps=[]}},m=e=>{let t=typeof structuredClone=="function"?(()=>{try{return structuredClone(e)}catch{return e}})():e,n=new WeakSet;try{let o=JSON.stringify(t,(v,s)=>{if(typeof s=="bigint")return s.toString();if(typeof s=="function")return`[Function ${s.name||"anonymous"}]`;if(typeof s=="symbol")return s.toString();if(typeof s=="object"&&s!==null){if(n.has(s))return"[Circular]";n.add(s)}return s});return o===void 0?void 0:JSON.parse(o)}catch{return String(e)}},D=e=>{if(e instanceof Error){let t="cause"in e&&e.cause!==void 0?e.cause:null;return{name:e.name,message:e.message,stack:typeof e.stack=="string"?e.stack:null,cause:m(t)}}return{name:null,message:typeof e=="string"?e:"Unknown error",stack:null,cause:m(e)}},R=e=>{let t={};for(let[n,o]of Object.entries(e.async.byStep))P(o)&&(t[n]={phase:F(o.phase)?o.phase:"idle",eventType:typeof o.eventType=="string"?o.eventType:null,transitionId:typeof o.transitionId=="string"?o.transitionId:null,error:o.error===null?null:m(o.error)});return{currentStepId:String(e.currentStepId),context:m(e.context),history:{timeline:e.history.timeline.map(n=>String(n)),index:e.history.index},visited:Object.fromEntries(Object.entries(e.visited).map(([n,o])=>[String(n),o===!0])),stepMeta:m(e.stepMeta),status:e.status,async:{isLoading:e.async.isLoading,byStep:t}}},te=(e,t)=>t in e.stepMeta,_=(e,t,n)=>{if(!te(e.getSnapshot(),t))throw new Error(`Unknown stepId "${t}" for "${n}" command.`);return t},E=e=>({snapshot:e.snapshot,transitioned:e.transitioned,...e.transitionId?{transitionId:e.transitionId}:{},..."error"in e?{error:D(e.error)}:{}}),ne=async(e,t)=>{switch(t.type){case"goToNextStep":case"completeJourney":{let n=await e.send({type:t.type});return E(n)}case"terminateMachine":{let n=await e.send({type:"terminateJourney"});return E(n)}case"goToStepById":{let n=_(e,t.stepId,t.type),o=await e.send({type:"goToStepById",stepId:n});return E(o)}case"goToPreviousStep":{let n=await e.goToPreviousStep(t.steps);return E(n)}case"goToLastVisitedStep":{let n=await e.goToLastVisitedStep();return E(n)}case"send":{let n=t.event.payload===void 0?{type:t.event.type}:{type:t.event.type,payload:t.event.payload},o=await e.send(n);return E(o)}case"updateStepMetadata":{let n=_(e,t.stepId,t.type);return{snapshot:e.updateStepMetadata(n,()=>t.metadata)}}case"resetMachine":return{snapshot:e.resetMachine()};case"clearStepError":{let n=t.stepId===void 0?void 0:_(e,t.stepId,t.type);return{snapshot:e.clearStepError(n)}}}},oe=(e,t={})=>{if(!(t.enabled??A())||typeof window>"u")return()=>{};let o=t.commandsEnabled??A(),v=t.machineId?.trim()||ee(),s={machineId:v,label:t.label?.trim()||K,appName:t.appName?.trim()||(typeof document<"u"?document.title:"")||null,commandsEnabled:o},V=Z(),d=r=>({channel:J,version:3,source:S,kind:r,machineId:v,timestamp:Date.now()}),u=r=>{try{window.postMessage(r,V)}catch{}},Y=r=>{let p={...d("snapshot"),snapshot:R(r)};u(p)},l=!1,C=new b,O=null,y=null,f=null,T=()=>{O=null,y=null,f=null},M=()=>{let r=O;T(),!(!r||l)&&Y(r)},j=r=>{if(O=r,y===null){if(typeof window.requestAnimationFrame=="function"){f="raf",y=window.requestAnimationFrame(()=>{M()});return}f="timeout",y=globalThis.setTimeout(()=>{M()},0)}},q=()=>{if(y===null){T();return}f==="raf"&&typeof window.cancelAnimationFrame=="function"?window.cancelAnimationFrame(y):globalThis.clearTimeout(y),T()},N=r=>{if(r.source!==window||!Q(r.origin)||l||!x(r.data)||r.data.source!==g||r.data.kind!=="command")return;let p=r.data;if(p.machineId!==v)return;if(!C.isAllowed()){let i={...d("commandError"),requestId:p.requestId,error:D("Command rate limit exceeded. Too many commands in a short time window.")};u(i);return}if(!o){let i={...d("commandError"),requestId:p.requestId,error:D("Bridge commands are disabled by configuration.")};u(i);return}(async()=>{try{let i=await ne(e,p.command);if(l)return;let h={...d("commandResult"),requestId:p.requestId,snapshot:R(i.snapshot),...i.transitioned!==void 0?{transitioned:i.transitioned}:{},...i.transitionId?{transitionId:i.transitionId}:{},..."error"in i?{error:i.error}:{}};u(h)}catch(i){if(l)return;let h={...d("commandError"),requestId:p.requestId,error:D(i)};u(h)}})()};window.addEventListener("message",N);let z=e.subscribe(()=>{l||j(e.getSnapshot())}),X={...d("register"),meta:s,snapshot:R(e.getSnapshot())};return u(X),()=>{if(l)return;l=!0,C.reset(),z(),window.removeEventListener("message",N),q();let r={...d("unregister")};u(r)}};export{S as JOURNEY_DEVTOOLS_BRIDGE_SOURCE,J as JOURNEY_DEVTOOLS_CHANNEL,g as JOURNEY_DEVTOOLS_EXTENSION_SOURCE,w as JOURNEY_DEVTOOLS_PROTOCOL_VERSION,oe as attachJourneyDevtools,L as isJourneyDevtoolsBridgeEnvelope,k as isJourneyDevtoolsCommand,x as isJourneyDevtoolsEnvelope,U as isJourneyDevtoolsExtensionEnvelope};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/protocol.ts", "../src/bridge.ts"],
4
- "sourcesContent": ["import type { JourneySnapshot, JourneyStepAsyncState } from \"@rxova/journey-core\";\n\nexport const JOURNEY_DEVTOOLS_PROTOCOL_VERSION = 3 as const;\nexport const JOURNEY_DEVTOOLS_CHANNEL = \"__RXOVA_JOURNEY_DEVTOOLS__\" as const;\n\nexport const JOURNEY_DEVTOOLS_BRIDGE_SOURCE = \"rxova-journey-bridge\" as const;\nexport const JOURNEY_DEVTOOLS_EXTENSION_SOURCE = \"rxova-journey-extension\" as const;\n\nexport type JourneyDevtoolsSource =\n | typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE\n | typeof JOURNEY_DEVTOOLS_EXTENSION_SOURCE;\n\nexport type JourneyDevtoolsStepAsyncState = JourneyStepAsyncState;\n\nexport type JourneyDevtoolsSerializableSnapshot = JourneySnapshot<unknown, string>;\n\nexport type JourneyDevtoolsMachineMeta = {\n machineId: string;\n label: string;\n appName: string | null;\n commandsEnabled?: boolean;\n};\n\nexport type JourneyDevtoolsSerializedError = {\n name: string | null;\n message: string;\n stack: string | null;\n cause: unknown;\n};\n\nexport type JourneyDevtoolsCommand =\n | { type: \"goToNextStep\" }\n | { type: \"terminateMachine\" }\n | { type: \"completeJourney\" }\n | { type: \"goToStepById\"; stepId: string }\n | { type: \"goToPreviousStep\"; steps?: number }\n | { type: \"goToLastVisitedStep\" }\n | { type: \"send\"; event: { type: string; payload?: unknown } }\n | { type: \"updateStepMetadata\"; stepId: string; metadata: unknown }\n | { type: \"resetMachine\" }\n | { type: \"clearStepError\"; stepId?: string };\n\nexport type JourneyDevtoolsEnvelopeBase = {\n channel: typeof JOURNEY_DEVTOOLS_CHANNEL;\n version: typeof JOURNEY_DEVTOOLS_PROTOCOL_VERSION;\n source: JourneyDevtoolsSource;\n kind: string;\n machineId: string;\n timestamp: number;\n};\n\nexport type JourneyDevtoolsBridgeRegisterEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"register\";\n meta: JourneyDevtoolsMachineMeta;\n snapshot: JourneyDevtoolsSerializableSnapshot;\n};\n\nexport type JourneyDevtoolsBridgeUnregisterEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"unregister\";\n};\n\nexport type JourneyDevtoolsBridgeSnapshotEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"snapshot\";\n snapshot: JourneyDevtoolsSerializableSnapshot;\n};\n\nexport type JourneyDevtoolsBridgeCommandResultEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"commandResult\";\n requestId: string;\n snapshot: JourneyDevtoolsSerializableSnapshot;\n transitioned?: boolean;\n transitionId?: string;\n};\n\nexport type JourneyDevtoolsBridgeCommandErrorEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"commandError\";\n requestId: string;\n error: JourneyDevtoolsSerializedError;\n};\n\nexport type JourneyDevtoolsExtensionCommandEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_EXTENSION_SOURCE;\n kind: \"command\";\n requestId: string;\n command: JourneyDevtoolsCommand;\n};\n\nexport type JourneyDevtoolsBridgeEnvelope =\n | JourneyDevtoolsBridgeRegisterEnvelope\n | JourneyDevtoolsBridgeUnregisterEnvelope\n | JourneyDevtoolsBridgeSnapshotEnvelope\n | JourneyDevtoolsBridgeCommandResultEnvelope\n | JourneyDevtoolsBridgeCommandErrorEnvelope;\n\nexport type JourneyDevtoolsExtensionEnvelope = JourneyDevtoolsExtensionCommandEnvelope;\n\nexport type JourneyDevtoolsEnvelope =\n | JourneyDevtoolsBridgeEnvelope\n | JourneyDevtoolsExtensionEnvelope;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isKnownSource = (value: unknown): value is JourneyDevtoolsSource =>\n value === JOURNEY_DEVTOOLS_BRIDGE_SOURCE || value === JOURNEY_DEVTOOLS_EXTENSION_SOURCE;\n\n/**\n * Maximum depth for nested object validation.\n * Prevents stack overflow and excessive processing from deeply nested malicious payloads.\n */\nconst MAX_PAYLOAD_DEPTH = 10;\n\n/**\n * Maximum size (in JSON string length) for serialized payloads.\n * Prevents memory exhaustion from extremely large payloads.\n */\nconst MAX_PAYLOAD_SIZE = 500_000; // 500KB\n\n/**\n * Validates that a value is safe for transport.\n * Checks depth and size constraints to prevent malicious payloads.\n */\nconst isSafePayload = (value: unknown, depth = 0): boolean => {\n if (depth > MAX_PAYLOAD_DEPTH) {\n return false;\n }\n\n if (value === null || value === undefined) {\n return true;\n }\n\n const primitiveTypes = [\"string\", \"number\", \"boolean\"];\n if (primitiveTypes.includes(typeof value)) {\n return true;\n }\n\n if (typeof value === \"object\") {\n // Check JSON serialization size\n try {\n const serialized = JSON.stringify(value);\n if (serialized.length > MAX_PAYLOAD_SIZE) {\n return false;\n }\n } catch {\n // Circular references or non-serializable objects are not safe\n return false;\n }\n\n // Recursively validate nested objects and arrays\n if (Array.isArray(value)) {\n return value.every((item) => isSafePayload(item, depth + 1));\n }\n\n // Validate plain objects (guard against prototype pollution)\n if (\n Object.getPrototypeOf(value) !== Object.prototype &&\n Object.getPrototypeOf(value) !== null\n ) {\n return false;\n }\n\n return Object.values(value).every((prop) => isSafePayload(prop, depth + 1));\n }\n\n // Reject functions, symbols, and other non-serializable types\n return false;\n};\n\nconst hasBaseEnvelopeShape = (value: unknown): value is JourneyDevtoolsEnvelopeBase => {\n if (!isRecord(value)) {\n return false;\n }\n\n return (\n value.channel === JOURNEY_DEVTOOLS_CHANNEL &&\n value.version === JOURNEY_DEVTOOLS_PROTOCOL_VERSION &&\n isKnownSource(value.source) &&\n typeof value.kind === \"string\" &&\n typeof value.machineId === \"string\" &&\n typeof value.timestamp === \"number\"\n );\n};\n\nconst isSendEvent = (value: unknown): value is { type: string; payload?: unknown } => {\n if (!isRecord(value)) {\n return false;\n }\n\n if (typeof value.type !== \"string\" || value.type.length === 0 || value.type.length > 100) {\n return false;\n }\n\n // Validate payload if present\n if (\"payload\" in value && value.payload !== undefined) {\n return isSafePayload(value.payload);\n }\n\n return true;\n};\n\n/**\n * Validates whether an unknown value is a supported devtools command payload.\n */\nexport const isJourneyDevtoolsCommand = (value: unknown): value is JourneyDevtoolsCommand => {\n if (!isRecord(value) || typeof value.type !== \"string\") {\n return false;\n }\n\n // Validate command type is within reasonable length\n if (value.type.length === 0 || value.type.length > 50) {\n return false;\n }\n\n switch (value.type) {\n case \"goToNextStep\":\n case \"terminateMachine\":\n case \"completeJourney\":\n case \"resetMachine\":\n case \"goToLastVisitedStep\":\n // These commands should have no extra properties beyond type\n return Object.keys(value).length === 1;\n case \"goToStepById\":\n return (\n typeof value.stepId === \"string\" &&\n value.stepId.length > 0 &&\n value.stepId.length <= 100 &&\n Object.keys(value).length === 2\n );\n case \"goToPreviousStep\":\n return (\n (value.steps === undefined ||\n (typeof value.steps === \"number\" &&\n Number.isInteger(value.steps) &&\n value.steps >= 1 &&\n value.steps <= 10000)) &&\n Object.keys(value).length <= 2\n );\n case \"send\":\n return isSendEvent(value.event) && Object.keys(value).length === 2;\n case \"updateStepMetadata\":\n return (\n typeof value.stepId === \"string\" &&\n value.stepId.length > 0 &&\n value.stepId.length <= 100 &&\n isSafePayload(value.metadata) &&\n Object.keys(value).length === 3\n );\n case \"clearStepError\":\n return (\n (value.stepId === undefined ||\n (typeof value.stepId === \"string\" && value.stepId.length <= 100)) &&\n Object.keys(value).length <= 2\n );\n default:\n return false;\n }\n};\n\n/**\n * Validates whether an unknown value is a bridge-origin envelope.\n */\nexport const isJourneyDevtoolsBridgeEnvelope = (\n value: unknown\n): value is JourneyDevtoolsBridgeEnvelope => {\n if (!hasBaseEnvelopeShape(value) || value.source !== JOURNEY_DEVTOOLS_BRIDGE_SOURCE) {\n return false;\n }\n\n const envelope = value as Record<string, unknown>;\n\n switch (value.kind) {\n case \"register\":\n return (\n isRecord(envelope.meta) &&\n isRecord(envelope.snapshot) &&\n isSafePayload(envelope.meta) &&\n isSafePayload(envelope.snapshot)\n );\n case \"unregister\":\n return true;\n case \"snapshot\":\n return isRecord(envelope.snapshot) && isSafePayload(envelope.snapshot);\n case \"commandResult\":\n return (\n typeof envelope.requestId === \"string\" &&\n envelope.requestId.length > 0 &&\n envelope.requestId.length <= 100 &&\n isRecord(envelope.snapshot) &&\n isSafePayload(envelope.snapshot)\n );\n case \"commandError\":\n return (\n typeof envelope.requestId === \"string\" &&\n envelope.requestId.length > 0 &&\n envelope.requestId.length <= 100 &&\n isRecord(envelope.error)\n );\n default:\n return false;\n }\n};\n\n/**\n * Validates whether an unknown value is an extension-origin command envelope.\n */\nexport const isJourneyDevtoolsExtensionEnvelope = (\n value: unknown\n): value is JourneyDevtoolsExtensionEnvelope => {\n if (!hasBaseEnvelopeShape(value) || value.source !== JOURNEY_DEVTOOLS_EXTENSION_SOURCE) {\n return false;\n }\n\n if (value.kind !== \"command\") {\n return false;\n }\n\n const envelope = value as Record<string, unknown>;\n return (\n typeof envelope.requestId === \"string\" &&\n envelope.requestId.length > 0 &&\n envelope.requestId.length <= 100 &&\n isJourneyDevtoolsCommand(envelope.command)\n );\n};\n\n/**\n * Validates whether an unknown value matches either supported devtools envelope shape.\n */\nexport const isJourneyDevtoolsEnvelope = (value: unknown): value is JourneyDevtoolsEnvelope =>\n isJourneyDevtoolsBridgeEnvelope(value) || isJourneyDevtoolsExtensionEnvelope(value);\n", "import type {\n JourneyEventPayloadMap,\n JourneyMachine,\n JourneySendResult,\n JourneySnapshot\n} from \"@rxova/journey-core\";\nimport {\n JOURNEY_DEVTOOLS_BRIDGE_SOURCE,\n JOURNEY_DEVTOOLS_CHANNEL,\n JOURNEY_DEVTOOLS_EXTENSION_SOURCE,\n JOURNEY_DEVTOOLS_PROTOCOL_VERSION,\n isJourneyDevtoolsEnvelope,\n type JourneyDevtoolsBridgeCommandErrorEnvelope,\n type JourneyDevtoolsBridgeCommandResultEnvelope,\n type JourneyDevtoolsBridgeEnvelope,\n type JourneyDevtoolsBridgeRegisterEnvelope,\n type JourneyDevtoolsBridgeSnapshotEnvelope,\n type JourneyDevtoolsBridgeUnregisterEnvelope,\n type JourneyDevtoolsCommand,\n type JourneyDevtoolsExtensionCommandEnvelope,\n type JourneyDevtoolsMachineMeta,\n type JourneyDevtoolsSerializableSnapshot,\n type JourneyDevtoolsSerializedError\n} from \"./protocol\";\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nexport type JourneyDevtoolsBridgeOptions = {\n machineId?: string;\n label?: string;\n enabled?: boolean;\n appName?: string;\n commandsEnabled?: boolean;\n};\n\ntype SendOutcome<TContext, TStepId extends string, TStepMeta> = {\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>;\n transitioned?: boolean;\n transitionId?: string;\n};\n\nconst DEFAULT_MACHINE_LABEL = \"Journey Machine\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isJourneyAsyncPhase = (\n value: unknown\n): value is JourneyDevtoolsSerializableSnapshot[\"async\"][\"byStep\"][string][\"phase\"] =>\n value === \"idle\" ||\n value === \"evaluating-when\" ||\n value === \"running-effect\" ||\n value === \"error\";\n\nconst resolveDefaultEnabled = (): boolean => {\n const nodeEnv = typeof process !== \"undefined\" ? process.env?.NODE_ENV : undefined;\n if (typeof nodeEnv !== \"string\") {\n return false;\n }\n\n return nodeEnv !== \"production\";\n};\n\nconst resolveDefaultCommandsEnabled = (): boolean => {\n const nodeEnv = typeof process !== \"undefined\" ? process.env?.NODE_ENV : undefined;\n if (typeof nodeEnv !== \"string\") {\n return false;\n }\n\n return nodeEnv !== \"production\";\n};\n\nconst resolveWindowTargetOrigin = (): string => {\n if (typeof window === \"undefined\") {\n return \"*\";\n }\n\n return window.location.origin === \"null\" ? \"*\" : window.location.origin;\n};\n\n// No session token infrastructure needed\n\n/**\n * Validates that the message origin matches the current window origin.\n * This prevents messages from other origins from being processed.\n *\n * Note: This is part of defense-in-depth but not a hard security boundary.\n * Code running in the same origin can still send messages.\n */\nconst isExpectedWindowOrigin = (origin: string): boolean => {\n if (origin.length === 0) {\n return false;\n }\n\n if (typeof window === \"undefined\") {\n return false;\n }\n\n const expected = window.location.origin;\n if (expected === \"null\") {\n // For file:// or sandboxed contexts where origin is \"null\"\n return origin === \"null\";\n }\n\n // Strict equality check - no wildcard matching\n return origin === expected;\n};\n\nconst createMachineId = (): string =>\n `journey-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n\n/**\n * Simple rate limiter to prevent command abuse.\n * Tracks command timestamps and enforces a maximum rate.\n */\nclass CommandRateLimiter {\n private commandTimestamps: number[] = [];\n private readonly maxCommandsPerWindow: number;\n private readonly windowMs: number;\n\n constructor(maxCommandsPerWindow = 100, windowMs = 10000) {\n this.maxCommandsPerWindow = maxCommandsPerWindow;\n this.windowMs = windowMs;\n }\n\n /**\n * Checks if a command is allowed based on rate limits.\n * Returns true if allowed, false if rate limit exceeded.\n */\n isAllowed(): boolean {\n const now = Date.now();\n const windowStart = now - this.windowMs;\n\n // Remove old timestamps outside the window\n this.commandTimestamps = this.commandTimestamps.filter((ts) => ts > windowStart);\n\n if (this.commandTimestamps.length >= this.maxCommandsPerWindow) {\n return false;\n }\n\n this.commandTimestamps.push(now);\n return true;\n }\n\n reset(): void {\n this.commandTimestamps = [];\n }\n}\n\nconst cloneForTransport = (value: unknown): unknown => {\n if (typeof structuredClone === \"function\") {\n try {\n return structuredClone(value);\n } catch {\n // Fall through to the JSON serializer below.\n }\n }\n\n const seen = new WeakSet<object>();\n\n try {\n const serialized = JSON.stringify(value, (_key, currentValue) => {\n if (typeof currentValue === \"bigint\") {\n return currentValue.toString();\n }\n if (typeof currentValue === \"function\") {\n return `[Function ${currentValue.name || \"anonymous\"}]`;\n }\n if (typeof currentValue === \"symbol\") {\n return currentValue.toString();\n }\n if (typeof currentValue === \"object\" && currentValue !== null) {\n if (seen.has(currentValue)) {\n return \"[Circular]\";\n }\n seen.add(currentValue);\n }\n return currentValue;\n });\n\n if (serialized === undefined) {\n return undefined;\n }\n\n return JSON.parse(serialized) as unknown;\n } catch {\n return String(value);\n }\n};\n\nconst serializeError = (error: unknown): JourneyDevtoolsSerializedError => {\n if (error instanceof Error) {\n const cause =\n \"cause\" in error && (error as { cause?: unknown }).cause !== undefined\n ? (error as { cause?: unknown }).cause\n : null;\n return {\n name: error.name,\n message: error.message,\n stack: typeof error.stack === \"string\" ? error.stack : null,\n cause: cloneForTransport(cause)\n };\n }\n\n return {\n name: null,\n message: typeof error === \"string\" ? error : \"Unknown error\",\n stack: null,\n cause: cloneForTransport(error)\n };\n};\n\nconst serializeSnapshot = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>\n): JourneyDevtoolsSerializableSnapshot => {\n const byStep: Record<string, JourneyDevtoolsSerializableSnapshot[\"async\"][\"byStep\"][string]> = {};\n\n for (const [stepId, stepState] of Object.entries(\n snapshot.async.byStep as Record<string, unknown>\n )) {\n if (!isRecord(stepState)) {\n continue;\n }\n\n byStep[stepId] = {\n phase: isJourneyAsyncPhase(stepState.phase) ? stepState.phase : \"idle\",\n eventType: typeof stepState.eventType === \"string\" ? stepState.eventType : null,\n transitionId: typeof stepState.transitionId === \"string\" ? stepState.transitionId : null,\n error: stepState.error === null ? null : cloneForTransport(stepState.error)\n };\n }\n\n return {\n currentStepId: String(snapshot.currentStepId),\n context: cloneForTransport(snapshot.context),\n history: {\n timeline: snapshot.history.timeline.map((stepId) => String(stepId)),\n index: snapshot.history.index\n },\n visited: Object.fromEntries(\n Object.entries(snapshot.visited as Record<string, boolean>).map(([stepId, isVisited]) => [\n String(stepId),\n isVisited === true\n ])\n ),\n stepMeta: cloneForTransport(snapshot.stepMeta) as Record<string, unknown>,\n status: snapshot.status,\n async: {\n isLoading: snapshot.async.isLoading,\n byStep\n }\n };\n};\n\nconst isKnownStepId = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n stepId: string\n): stepId is TStepId => stepId in snapshot.stepMeta;\n\nconst assertKnownStepId = <TContext, TStepId extends string, TStepMeta>(\n machine: JourneyMachine<TContext, TStepId, string, Record<never, never>, TStepMeta>,\n stepId: string,\n commandType: JourneyDevtoolsCommand[\"type\"]\n): TStepId => {\n if (!isKnownStepId(machine.getSnapshot(), stepId)) {\n throw new Error(`Unknown stepId \"${stepId}\" for \"${commandType}\" command.`);\n }\n return stepId;\n};\n\nconst runCommand = async <TContext, TStepId extends string, TStepMeta>(\n machine: JourneyMachine<TContext, TStepId, string, Record<never, never>, TStepMeta>,\n command: JourneyDevtoolsCommand\n): Promise<SendOutcome<TContext, TStepId, TStepMeta>> => {\n switch (command.type) {\n case \"goToNextStep\":\n case \"completeJourney\": {\n const result = await machine.send({ type: command.type });\n return {\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {})\n };\n }\n case \"terminateMachine\": {\n const result = await machine.send({ type: \"terminateJourney\" });\n return {\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {})\n };\n }\n case \"goToStepById\": {\n const stepId = assertKnownStepId(machine, command.stepId, command.type);\n const result = await machine.send({\n type: \"goToStepById\",\n stepId\n });\n return {\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {})\n };\n }\n case \"goToPreviousStep\": {\n const result = await machine.goToPreviousStep(command.steps);\n return {\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {})\n };\n }\n case \"goToLastVisitedStep\": {\n const result = await machine.goToLastVisitedStep();\n return {\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {})\n };\n }\n case \"send\": {\n const sendEvent =\n command.event.payload === undefined\n ? { type: command.event.type }\n : { type: command.event.type, payload: command.event.payload };\n const result: JourneySendResult<TContext, TStepId, TStepMeta> = await machine.send(sendEvent);\n return {\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {})\n };\n }\n case \"updateStepMetadata\": {\n const stepId = assertKnownStepId(machine, command.stepId, command.type);\n return {\n snapshot: machine.updateStepMetadata(stepId, () => command.metadata as TStepMeta)\n };\n }\n case \"resetMachine\":\n return {\n snapshot: machine.resetMachine()\n };\n case \"clearStepError\": {\n const stepId =\n command.stepId === undefined\n ? undefined\n : assertKnownStepId(machine, command.stepId, command.type);\n return {\n snapshot: machine.clearStepError(stepId)\n };\n }\n }\n};\n\n/**\n * Attaches a journey machine to the browser devtools transport and returns\n * a detach function that unsubscribes listeners and unregisters the machine.\n */\nexport const attachJourneyDevtools = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TStepMeta\n>(\n machine: JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>,\n options: JourneyDevtoolsBridgeOptions = {}\n): (() => void) => {\n const enabled = options.enabled ?? resolveDefaultEnabled();\n if (!enabled || typeof window === \"undefined\") {\n return () => {};\n }\n const commandsEnabled = options.commandsEnabled ?? resolveDefaultCommandsEnabled();\n\n const machineId = options.machineId?.trim() || createMachineId();\n const meta: JourneyDevtoolsMachineMeta = {\n machineId,\n label: options.label?.trim() || DEFAULT_MACHINE_LABEL,\n appName:\n options.appName?.trim() || (typeof document !== \"undefined\" ? document.title : \"\") || null,\n commandsEnabled\n };\n const targetOrigin = resolveWindowTargetOrigin();\n\n const createBaseEnvelope = <TKind extends JourneyDevtoolsBridgeEnvelope[\"kind\"]>(\n kind: TKind\n ) => ({\n channel: JOURNEY_DEVTOOLS_CHANNEL,\n version: JOURNEY_DEVTOOLS_PROTOCOL_VERSION,\n source: JOURNEY_DEVTOOLS_BRIDGE_SOURCE,\n kind,\n machineId,\n timestamp: Date.now()\n });\n\n const post = (envelope: JourneyDevtoolsBridgeEnvelope) => {\n window.postMessage(envelope, targetOrigin);\n };\n\n const postSnapshot = (snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>) => {\n const envelope: JourneyDevtoolsBridgeSnapshotEnvelope = {\n ...createBaseEnvelope(\"snapshot\"),\n snapshot: serializeSnapshot(snapshot)\n };\n post(envelope);\n };\n\n let isDetached = false;\n const rateLimiter = new CommandRateLimiter();\n\n const onMessage = (event: MessageEvent<unknown>) => {\n if (\n event.source !== window ||\n !isExpectedWindowOrigin(event.origin) ||\n isDetached ||\n !isJourneyDevtoolsEnvelope(event.data)\n ) {\n return;\n }\n\n if (event.data.source !== JOURNEY_DEVTOOLS_EXTENSION_SOURCE || event.data.kind !== \"command\") {\n return;\n }\n\n const commandEnvelope: JourneyDevtoolsExtensionCommandEnvelope = event.data;\n if (commandEnvelope.machineId !== machineId) {\n return;\n }\n\n // Rate limiting to prevent command abuse\n if (!rateLimiter.isAllowed()) {\n const errorEnvelope: JourneyDevtoolsBridgeCommandErrorEnvelope = {\n ...createBaseEnvelope(\"commandError\"),\n requestId: commandEnvelope.requestId,\n error: serializeError(\n \"Command rate limit exceeded. Too many commands in a short time window.\"\n )\n };\n post(errorEnvelope);\n return;\n }\n\n if (!commandsEnabled) {\n const errorEnvelope: JourneyDevtoolsBridgeCommandErrorEnvelope = {\n ...createBaseEnvelope(\"commandError\"),\n requestId: commandEnvelope.requestId,\n error: serializeError(\"Bridge commands are disabled by configuration.\")\n };\n post(errorEnvelope);\n return;\n }\n\n const run = async () => {\n try {\n const outcome = await runCommand(\n machine as JourneyMachine<TContext, TStepId, string, Record<never, never>, TStepMeta>,\n commandEnvelope.command\n );\n if (isDetached) {\n return;\n }\n\n const resultEnvelope: JourneyDevtoolsBridgeCommandResultEnvelope = {\n ...createBaseEnvelope(\"commandResult\"),\n requestId: commandEnvelope.requestId,\n snapshot: serializeSnapshot(outcome.snapshot),\n ...(outcome.transitioned !== undefined ? { transitioned: outcome.transitioned } : {}),\n ...(outcome.transitionId ? { transitionId: outcome.transitionId } : {})\n };\n post(resultEnvelope);\n } catch (error) {\n if (isDetached) {\n return;\n }\n\n const errorEnvelope: JourneyDevtoolsBridgeCommandErrorEnvelope = {\n ...createBaseEnvelope(\"commandError\"),\n requestId: commandEnvelope.requestId,\n error: serializeError(error)\n };\n post(errorEnvelope);\n }\n };\n\n void run();\n };\n\n window.addEventListener(\"message\", onMessage);\n\n const unsubscribe = machine.subscribe(() => {\n if (isDetached) {\n return;\n }\n postSnapshot(machine.getSnapshot());\n });\n\n const registerEnvelope: JourneyDevtoolsBridgeRegisterEnvelope = {\n ...createBaseEnvelope(\"register\"),\n meta,\n snapshot: serializeSnapshot(machine.getSnapshot())\n };\n post(registerEnvelope);\n\n return () => {\n if (isDetached) {\n return;\n }\n\n isDetached = true;\n rateLimiter.reset();\n unsubscribe();\n window.removeEventListener(\"message\", onMessage);\n\n const unregisterEnvelope: JourneyDevtoolsBridgeUnregisterEnvelope = {\n ...createBaseEnvelope(\"unregister\")\n };\n post(unregisterEnvelope);\n };\n};\n"],
5
- "mappings": "AAEO,IAAMA,EAAoC,EACpCC,EAA2B,6BAE3BC,EAAiC,uBACjCC,EAAoC,0BAmG3CC,EAAYC,GAChB,OAAOA,GAAU,UAAYA,IAAU,KAEnCC,EAAiBD,GACrBA,IAAUH,GAAkCG,IAAUF,EAkBxD,IAAMI,EAAgB,CAACC,EAAgBC,EAAQ,IAAe,CAC5D,GAAIA,EAAQ,GACV,MAAO,GAQT,GALID,G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,EAAQ,YAAY,CAAC,CACpC,CAAC,EAEK8B,EAA0D,CAC9D,GAAGlB,EAAmB,UAAU,EAChC,KAAAF,EACA,SAAUlB,EAAkBQ,EAAQ,YAAY,CAAC,CACnD,EACA,OAAAgB,EAAKc,CAAgB,EAEd,IAAM,CACX,GAAIX,EACF,OAGFA,EAAa,GACbC,EAAY,MAAM,EAClBS,EAAY,EACZ,OAAO,oBAAoB,UAAWR,CAAS,EAE/C,IAAMU,EAA8D,CAClE,GAAGnB,EAAmB,YAAY,CACpC,EACAI,EAAKe,CAAkB,CACzB,CACF",
6
- "names": ["JOURNEY_DEVTOOLS_PROTOCOL_VERSION", "JOURNEY_DEVTOOLS_CHANNEL", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "isRecord", "value", "isKnownSource", "isSafePayload", "value", "depth", "item", "prop", "hasBaseEnvelopeShape", "isRecord", "JOURNEY_DEVTOOLS_CHANNEL", "isKnownSource", "isSendEvent", "isJourneyDevtoolsCommand", "isJourneyDevtoolsBridgeEnvelope", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "envelope", "isJourneyDevtoolsExtensionEnvelope", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "isJourneyDevtoolsEnvelope", "DEFAULT_MACHINE_LABEL", "isRecord", "value", "isJourneyAsyncPhase", "resolveDefaultEnabled", "nodeEnv", "resolveDefaultCommandsEnabled", "resolveWindowTargetOrigin", "isExpectedWindowOrigin", "origin", "expected", "createMachineId", "CommandRateLimiter", "maxCommandsPerWindow", "windowMs", "now", "windowStart", "ts", "cloneForTransport", "seen", "serialized", "_key", "currentValue", "serializeError", "error", "cause", "serializeSnapshot", "snapshot", "byStep", "stepId", "stepState", "isVisited", "isKnownStepId", "assertKnownStepId", "machine", "commandType", "runCommand", "command", "result", "sendEvent", "attachJourneyDevtools", "options", "commandsEnabled", "machineId", "meta", "targetOrigin", "createBaseEnvelope", "kind", "JOURNEY_DEVTOOLS_CHANNEL", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "post", "envelope", "postSnapshot", "isDetached", "rateLimiter", "onMessage", "event", "isJourneyDevtoolsEnvelope", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "commandEnvelope", "errorEnvelope", "outcome", "resultEnvelope", "unsubscribe", "registerEnvelope", "unregisterEnvelope"]
4
+ "sourcesContent": ["import type { JourneySnapshot, JourneyStepAsyncState } from \"@rxova/journey-core\";\n\nexport const JOURNEY_DEVTOOLS_PROTOCOL_VERSION = 3 as const;\nexport const JOURNEY_DEVTOOLS_CHANNEL = \"__RXOVA_JOURNEY_DEVTOOLS__\" as const;\n\nexport const JOURNEY_DEVTOOLS_BRIDGE_SOURCE = \"rxova-journey-bridge\" as const;\nexport const JOURNEY_DEVTOOLS_EXTENSION_SOURCE = \"rxova-journey-extension\" as const;\n\nexport type JourneyDevtoolsSource =\n | typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE\n | typeof JOURNEY_DEVTOOLS_EXTENSION_SOURCE;\n\nexport type JourneyDevtoolsStepAsyncState = JourneyStepAsyncState;\n\nexport type JourneyDevtoolsSerializableSnapshot = JourneySnapshot<unknown, string>;\n\nexport type JourneyDevtoolsMachineMeta = {\n machineId: string;\n label: string;\n appName: string | null;\n commandsEnabled?: boolean;\n};\n\nexport type JourneyDevtoolsSerializedError = {\n name: string | null;\n message: string;\n stack: string | null;\n cause: unknown;\n};\n\nexport type JourneyDevtoolsCommand =\n | { type: \"goToNextStep\" }\n | { type: \"terminateMachine\" }\n | { type: \"completeJourney\" }\n | { type: \"goToStepById\"; stepId: string }\n | { type: \"goToPreviousStep\"; steps?: number }\n | { type: \"goToLastVisitedStep\" }\n | { type: \"send\"; event: { type: string; payload?: unknown } }\n | { type: \"updateStepMetadata\"; stepId: string; metadata: unknown }\n | { type: \"resetMachine\" }\n | { type: \"clearStepError\"; stepId?: string };\n\nexport type JourneyDevtoolsEnvelopeBase = {\n channel: typeof JOURNEY_DEVTOOLS_CHANNEL;\n version: typeof JOURNEY_DEVTOOLS_PROTOCOL_VERSION;\n source: JourneyDevtoolsSource;\n kind: string;\n machineId: string;\n timestamp: number;\n};\n\nexport type JourneyDevtoolsBridgeRegisterEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"register\";\n meta: JourneyDevtoolsMachineMeta;\n snapshot: JourneyDevtoolsSerializableSnapshot;\n};\n\nexport type JourneyDevtoolsBridgeUnregisterEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"unregister\";\n};\n\nexport type JourneyDevtoolsBridgeSnapshotEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"snapshot\";\n snapshot: JourneyDevtoolsSerializableSnapshot;\n};\n\nexport type JourneyDevtoolsBridgeCommandResultEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"commandResult\";\n requestId: string;\n snapshot: JourneyDevtoolsSerializableSnapshot;\n transitioned?: boolean;\n transitionId?: string;\n error?: JourneyDevtoolsSerializedError;\n};\n\nexport type JourneyDevtoolsBridgeCommandErrorEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;\n kind: \"commandError\";\n requestId: string;\n error: JourneyDevtoolsSerializedError;\n};\n\nexport type JourneyDevtoolsExtensionCommandEnvelope = JourneyDevtoolsEnvelopeBase & {\n source: typeof JOURNEY_DEVTOOLS_EXTENSION_SOURCE;\n kind: \"command\";\n requestId: string;\n command: JourneyDevtoolsCommand;\n};\n\nexport type JourneyDevtoolsBridgeEnvelope =\n | JourneyDevtoolsBridgeRegisterEnvelope\n | JourneyDevtoolsBridgeUnregisterEnvelope\n | JourneyDevtoolsBridgeSnapshotEnvelope\n | JourneyDevtoolsBridgeCommandResultEnvelope\n | JourneyDevtoolsBridgeCommandErrorEnvelope;\n\nexport type JourneyDevtoolsExtensionEnvelope = JourneyDevtoolsExtensionCommandEnvelope;\n\nexport type JourneyDevtoolsEnvelope =\n | JourneyDevtoolsBridgeEnvelope\n | JourneyDevtoolsExtensionEnvelope;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isKnownSource = (value: unknown): value is JourneyDevtoolsSource =>\n value === JOURNEY_DEVTOOLS_BRIDGE_SOURCE || value === JOURNEY_DEVTOOLS_EXTENSION_SOURCE;\n\n/**\n * Maximum depth for nested object validation.\n * Prevents stack overflow and excessive processing from deeply nested malicious payloads.\n */\nconst MAX_PAYLOAD_DEPTH = 10;\n\n/**\n * Maximum size (in JSON string length) for serialized payloads.\n * Prevents memory exhaustion from extremely large payloads.\n */\nconst MAX_PAYLOAD_SIZE = 500_000; // 500KB\n\n/**\n * Validates that a value is safe for transport.\n * Checks size via a single serialization pass, then validates\n * depth, types, and prototype safety via a structure walk.\n */\nconst isSafePayload = (value: unknown): boolean => {\n try {\n const serialized = JSON.stringify(value);\n if (serialized !== undefined && serialized.length > MAX_PAYLOAD_SIZE) {\n return false;\n }\n } catch {\n return false;\n }\n\n return isStructureSafe(value, 0);\n};\n\nconst isStructureSafe = (value: unknown, depth: number): boolean => {\n if (depth > MAX_PAYLOAD_DEPTH) {\n return false;\n }\n\n if (value === null || value === undefined) {\n return true;\n }\n\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return true;\n }\n\n if (typeof value !== \"object\") {\n return false;\n }\n\n if (Array.isArray(value)) {\n return value.every((item) => isStructureSafe(item, depth + 1));\n }\n\n if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {\n return false;\n }\n\n return Object.values(value).every((prop) => isStructureSafe(prop, depth + 1));\n};\n\nconst hasBaseEnvelopeShape = (value: unknown): value is JourneyDevtoolsEnvelopeBase => {\n if (!isRecord(value)) {\n return false;\n }\n\n return (\n value.channel === JOURNEY_DEVTOOLS_CHANNEL &&\n value.version === JOURNEY_DEVTOOLS_PROTOCOL_VERSION &&\n isKnownSource(value.source) &&\n typeof value.kind === \"string\" &&\n typeof value.machineId === \"string\" &&\n typeof value.timestamp === \"number\"\n );\n};\n\nconst isSendEvent = (value: unknown): value is { type: string; payload?: unknown } => {\n if (!isRecord(value)) {\n return false;\n }\n\n if (typeof value.type !== \"string\" || value.type.length === 0 || value.type.length > 100) {\n return false;\n }\n\n // Validate payload if present\n if (\"payload\" in value && value.payload !== undefined) {\n return isSafePayload(value.payload);\n }\n\n return true;\n};\n\n/**\n * Validates whether an unknown value is a supported devtools command payload.\n */\nexport const isJourneyDevtoolsCommand = (value: unknown): value is JourneyDevtoolsCommand => {\n if (!isRecord(value) || typeof value.type !== \"string\") {\n return false;\n }\n\n // Validate command type is within reasonable length\n if (value.type.length === 0 || value.type.length > 50) {\n return false;\n }\n\n switch (value.type) {\n case \"goToNextStep\":\n case \"terminateMachine\":\n case \"completeJourney\":\n case \"resetMachine\":\n case \"goToLastVisitedStep\":\n // These commands should have no extra properties beyond type\n return Object.keys(value).length === 1;\n case \"goToStepById\":\n return (\n typeof value.stepId === \"string\" &&\n value.stepId.length > 0 &&\n value.stepId.length <= 100 &&\n Object.keys(value).length === 2\n );\n case \"goToPreviousStep\":\n return (\n (value.steps === undefined ||\n (typeof value.steps === \"number\" &&\n Number.isInteger(value.steps) &&\n value.steps >= 1 &&\n value.steps <= 10000)) &&\n Object.keys(value).length <= 2\n );\n case \"send\":\n return isSendEvent(value.event) && Object.keys(value).length === 2;\n case \"updateStepMetadata\":\n return (\n typeof value.stepId === \"string\" &&\n value.stepId.length > 0 &&\n value.stepId.length <= 100 &&\n isSafePayload(value.metadata) &&\n Object.keys(value).length === 3\n );\n case \"clearStepError\":\n return (\n (value.stepId === undefined ||\n (typeof value.stepId === \"string\" && value.stepId.length <= 100)) &&\n Object.keys(value).length <= 2\n );\n default:\n return false;\n }\n};\n\n/**\n * Validates whether an unknown value is a bridge-origin envelope.\n */\nexport const isJourneyDevtoolsBridgeEnvelope = (\n value: unknown\n): value is JourneyDevtoolsBridgeEnvelope => {\n if (!hasBaseEnvelopeShape(value) || value.source !== JOURNEY_DEVTOOLS_BRIDGE_SOURCE) {\n return false;\n }\n\n const envelope = value as Record<string, unknown>;\n\n switch (value.kind) {\n case \"register\":\n return (\n isRecord(envelope.meta) &&\n isRecord(envelope.snapshot) &&\n isSafePayload(envelope.meta) &&\n isSafePayload(envelope.snapshot)\n );\n case \"unregister\":\n return true;\n case \"snapshot\":\n return isRecord(envelope.snapshot) && isSafePayload(envelope.snapshot);\n case \"commandResult\":\n return (\n typeof envelope.requestId === \"string\" &&\n envelope.requestId.length > 0 &&\n envelope.requestId.length <= 100 &&\n isRecord(envelope.snapshot) &&\n isSafePayload(envelope.snapshot) &&\n (!(\"error\" in envelope) || isRecord(envelope.error))\n );\n case \"commandError\":\n return (\n typeof envelope.requestId === \"string\" &&\n envelope.requestId.length > 0 &&\n envelope.requestId.length <= 100 &&\n isRecord(envelope.error)\n );\n default:\n return false;\n }\n};\n\n/**\n * Validates whether an unknown value is an extension-origin command envelope.\n */\nexport const isJourneyDevtoolsExtensionEnvelope = (\n value: unknown\n): value is JourneyDevtoolsExtensionEnvelope => {\n if (!hasBaseEnvelopeShape(value) || value.source !== JOURNEY_DEVTOOLS_EXTENSION_SOURCE) {\n return false;\n }\n\n if (value.kind !== \"command\") {\n return false;\n }\n\n const envelope = value as Record<string, unknown>;\n return (\n typeof envelope.requestId === \"string\" &&\n envelope.requestId.length > 0 &&\n envelope.requestId.length <= 100 &&\n isJourneyDevtoolsCommand(envelope.command)\n );\n};\n\n/**\n * Validates whether an unknown value matches either supported devtools envelope shape.\n */\nexport const isJourneyDevtoolsEnvelope = (value: unknown): value is JourneyDevtoolsEnvelope =>\n isJourneyDevtoolsBridgeEnvelope(value) || isJourneyDevtoolsExtensionEnvelope(value);\n", "import type {\n JourneyEventPayloadMap,\n JourneyMachine,\n JourneySendResult,\n JourneySnapshot\n} from \"@rxova/journey-core\";\nimport {\n JOURNEY_DEVTOOLS_BRIDGE_SOURCE,\n JOURNEY_DEVTOOLS_CHANNEL,\n JOURNEY_DEVTOOLS_EXTENSION_SOURCE,\n JOURNEY_DEVTOOLS_PROTOCOL_VERSION,\n isJourneyDevtoolsEnvelope,\n type JourneyDevtoolsBridgeCommandErrorEnvelope,\n type JourneyDevtoolsBridgeCommandResultEnvelope,\n type JourneyDevtoolsBridgeEnvelope,\n type JourneyDevtoolsBridgeRegisterEnvelope,\n type JourneyDevtoolsBridgeSnapshotEnvelope,\n type JourneyDevtoolsBridgeUnregisterEnvelope,\n type JourneyDevtoolsCommand,\n type JourneyDevtoolsExtensionCommandEnvelope,\n type JourneyDevtoolsMachineMeta,\n type JourneyDevtoolsSerializableSnapshot,\n type JourneyDevtoolsSerializedError\n} from \"./protocol\";\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nexport type JourneyDevtoolsBridgeOptions = {\n machineId?: string;\n label?: string;\n enabled?: boolean;\n appName?: string;\n commandsEnabled?: boolean;\n};\n\ntype SendOutcome<TContext, TStepId extends string, TStepMeta> = {\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>;\n transitioned?: boolean;\n transitionId?: string;\n error?: JourneyDevtoolsSerializedError;\n};\n\ntype SnapshotScheduleKind = \"raf\" | \"timeout\";\n\nconst DEFAULT_MACHINE_LABEL = \"Journey Machine\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isJourneyAsyncPhase = (\n value: unknown\n): value is JourneyDevtoolsSerializableSnapshot[\"async\"][\"byStep\"][string][\"phase\"] =>\n value === \"idle\" ||\n value === \"evaluating-when\" ||\n value === \"running-effect\" ||\n value === \"error\";\n\ntype JourneyImportMetaEnv = {\n DEV?: unknown;\n PROD?: unknown;\n};\n\nconst resolveImportMetaEnvironment = (\n bundlerEnv: JourneyImportMetaEnv | null | undefined\n): boolean | null => {\n if (!isRecord(bundlerEnv)) {\n return null;\n }\n\n if (bundlerEnv.PROD === true) {\n return false;\n }\n\n if (bundlerEnv.DEV === true) {\n return true;\n }\n\n return null;\n};\n\nconst resolveNodeEnvironment = (nodeEnv: string | undefined): boolean | null => {\n if (typeof nodeEnv !== \"string\") {\n return null;\n }\n\n return nodeEnv !== \"production\";\n};\n\nexport const resolveNonProductionEnvironment = (\n options: {\n bundlerEnv?: JourneyImportMetaEnv | null | undefined;\n nodeEnv?: string | undefined;\n } = {}\n): boolean => {\n const resolvedBundlerEnv =\n \"bundlerEnv\" in options\n ? options.bundlerEnv\n : (import.meta as ImportMeta & { env?: JourneyImportMetaEnv }).env;\n const resolvedNodeEnv =\n \"nodeEnv\" in options\n ? options.nodeEnv\n : typeof process !== \"undefined\"\n ? process.env?.NODE_ENV\n : undefined;\n\n return (\n resolveImportMetaEnvironment(resolvedBundlerEnv) ??\n resolveNodeEnvironment(resolvedNodeEnv) ??\n false\n );\n};\n\nconst resolveWindowTargetOrigin = (): string => {\n if (typeof window === \"undefined\") {\n return \"*\";\n }\n\n return window.location.origin === \"null\" ? \"*\" : window.location.origin;\n};\n\n// No session token infrastructure needed\n\n/**\n * Validates that the message origin matches the current window origin.\n * This prevents messages from other origins from being processed.\n *\n * Note: This is part of defense-in-depth but not a hard security boundary.\n * Code running in the same origin can still send messages.\n */\nconst isExpectedWindowOrigin = (origin: string): boolean => {\n if (origin.length === 0) {\n return false;\n }\n\n if (typeof window === \"undefined\") {\n return false;\n }\n\n const expected = window.location.origin;\n if (expected === \"null\") {\n // For file:// or sandboxed contexts where origin is \"null\"\n return origin === \"null\";\n }\n\n // Strict equality check - no wildcard matching\n return origin === expected;\n};\n\nconst createMachineId = (): string =>\n `journey-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n\n/**\n * Simple rate limiter to prevent command abuse.\n * Tracks command timestamps and enforces a maximum rate.\n */\nclass CommandRateLimiter {\n private commandTimestamps: number[] = [];\n private readonly maxCommandsPerWindow: number;\n private readonly windowMs: number;\n\n constructor(maxCommandsPerWindow = 100, windowMs = 10000) {\n this.maxCommandsPerWindow = maxCommandsPerWindow;\n this.windowMs = windowMs;\n }\n\n /**\n * Checks if a command is allowed based on rate limits.\n * Returns true if allowed, false if rate limit exceeded.\n */\n isAllowed(): boolean {\n const now = Date.now();\n const windowStart = now - this.windowMs;\n\n // Remove old timestamps outside the window\n this.commandTimestamps = this.commandTimestamps.filter((ts) => ts > windowStart);\n\n if (this.commandTimestamps.length >= this.maxCommandsPerWindow) {\n return false;\n }\n\n this.commandTimestamps.push(now);\n return true;\n }\n\n reset(): void {\n this.commandTimestamps = [];\n }\n}\n\nconst cloneForTransport = (value: unknown): unknown => {\n const transportValue =\n typeof structuredClone === \"function\"\n ? (() => {\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n })()\n : value;\n const seen = new WeakSet<object>();\n\n try {\n const serialized = JSON.stringify(transportValue, (_key, currentValue) => {\n if (typeof currentValue === \"bigint\") {\n return currentValue.toString();\n }\n if (typeof currentValue === \"function\") {\n return `[Function ${currentValue.name || \"anonymous\"}]`;\n }\n if (typeof currentValue === \"symbol\") {\n return currentValue.toString();\n }\n if (typeof currentValue === \"object\" && currentValue !== null) {\n if (seen.has(currentValue)) {\n return \"[Circular]\";\n }\n seen.add(currentValue);\n }\n return currentValue;\n });\n\n if (serialized === undefined) {\n return undefined;\n }\n\n return JSON.parse(serialized) as unknown;\n } catch {\n return String(value);\n }\n};\n\nconst serializeError = (error: unknown): JourneyDevtoolsSerializedError => {\n if (error instanceof Error) {\n const cause =\n \"cause\" in error && (error as { cause?: unknown }).cause !== undefined\n ? (error as { cause?: unknown }).cause\n : null;\n return {\n name: error.name,\n message: error.message,\n stack: typeof error.stack === \"string\" ? error.stack : null,\n cause: cloneForTransport(cause)\n };\n }\n\n return {\n name: null,\n message: typeof error === \"string\" ? error : \"Unknown error\",\n stack: null,\n cause: cloneForTransport(error)\n };\n};\n\nconst serializeSnapshot = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>\n): JourneyDevtoolsSerializableSnapshot => {\n const byStep: Record<string, JourneyDevtoolsSerializableSnapshot[\"async\"][\"byStep\"][string]> = {};\n\n for (const [stepId, stepState] of Object.entries(\n snapshot.async.byStep as Record<string, unknown>\n )) {\n if (!isRecord(stepState)) {\n continue;\n }\n\n byStep[stepId] = {\n phase: isJourneyAsyncPhase(stepState.phase) ? stepState.phase : \"idle\",\n eventType: typeof stepState.eventType === \"string\" ? stepState.eventType : null,\n transitionId: typeof stepState.transitionId === \"string\" ? stepState.transitionId : null,\n error: stepState.error === null ? null : cloneForTransport(stepState.error)\n };\n }\n\n return {\n currentStepId: String(snapshot.currentStepId),\n context: cloneForTransport(snapshot.context),\n history: {\n timeline: snapshot.history.timeline.map((stepId) => String(stepId)),\n index: snapshot.history.index\n },\n visited: Object.fromEntries(\n Object.entries(snapshot.visited as Record<string, boolean>).map(([stepId, isVisited]) => [\n String(stepId),\n isVisited === true\n ])\n ),\n stepMeta: cloneForTransport(snapshot.stepMeta) as Record<string, unknown>,\n status: snapshot.status,\n async: {\n isLoading: snapshot.async.isLoading,\n byStep\n }\n };\n};\n\nconst isKnownStepId = <TContext, TStepId extends string, TStepMeta>(\n snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>,\n stepId: string\n): stepId is TStepId => stepId in snapshot.stepMeta;\n\nconst assertKnownStepId = <TContext, TStepId extends string, TStepMeta>(\n machine: JourneyMachine<TContext, TStepId, string, Record<never, never>, TStepMeta>,\n stepId: string,\n commandType: JourneyDevtoolsCommand[\"type\"]\n): TStepId => {\n if (!isKnownStepId(machine.getSnapshot(), stepId)) {\n throw new Error(`Unknown stepId \"${stepId}\" for \"${commandType}\" command.`);\n }\n return stepId;\n};\n\nconst toSendOutcome = <TContext, TStepId extends string, TStepMeta>(\n result: JourneySendResult<TContext, TStepId, TStepMeta>\n): SendOutcome<TContext, TStepId, TStepMeta> => ({\n snapshot: result.snapshot,\n transitioned: result.transitioned,\n ...(result.transitionId ? { transitionId: result.transitionId } : {}),\n ...(\"error\" in result ? { error: serializeError(result.error) } : {})\n});\n\nconst runCommand = async <TContext, TStepId extends string, TStepMeta>(\n machine: JourneyMachine<TContext, TStepId, string, Record<never, never>, TStepMeta>,\n command: JourneyDevtoolsCommand\n): Promise<SendOutcome<TContext, TStepId, TStepMeta>> => {\n switch (command.type) {\n case \"goToNextStep\":\n case \"completeJourney\": {\n const result = await machine.send({ type: command.type });\n return toSendOutcome(result);\n }\n case \"terminateMachine\": {\n const result = await machine.send({ type: \"terminateJourney\" });\n return toSendOutcome(result);\n }\n case \"goToStepById\": {\n const stepId = assertKnownStepId(machine, command.stepId, command.type);\n const result = await machine.send({\n type: \"goToStepById\",\n stepId\n });\n return toSendOutcome(result);\n }\n case \"goToPreviousStep\": {\n const result = await machine.goToPreviousStep(command.steps);\n return toSendOutcome(result);\n }\n case \"goToLastVisitedStep\": {\n const result = await machine.goToLastVisitedStep();\n return toSendOutcome(result);\n }\n case \"send\": {\n const sendEvent =\n command.event.payload === undefined\n ? { type: command.event.type }\n : { type: command.event.type, payload: command.event.payload };\n const result: JourneySendResult<TContext, TStepId, TStepMeta> = await machine.send(sendEvent);\n return toSendOutcome(result);\n }\n case \"updateStepMetadata\": {\n const stepId = assertKnownStepId(machine, command.stepId, command.type);\n return {\n snapshot: machine.updateStepMetadata(stepId, () => command.metadata as TStepMeta)\n };\n }\n case \"resetMachine\":\n return {\n snapshot: machine.resetMachine()\n };\n case \"clearStepError\": {\n const stepId =\n command.stepId === undefined\n ? undefined\n : assertKnownStepId(machine, command.stepId, command.type);\n return {\n snapshot: machine.clearStepError(stepId)\n };\n }\n }\n};\n\n/**\n * Attaches a journey machine to the browser devtools transport and returns\n * a detach function that unsubscribes listeners and unregisters the machine.\n */\nexport const attachJourneyDevtools = <\n TContext,\n TStepId extends string,\n TEventType extends string,\n TPayloadMap extends JourneyEventPayloadMap<TEventType>,\n TStepMeta\n>(\n machine: JourneyMachine<TContext, TStepId, TEventType, TPayloadMap, TStepMeta>,\n options: JourneyDevtoolsBridgeOptions = {}\n): (() => void) => {\n const enabled = options.enabled ?? resolveNonProductionEnvironment();\n if (!enabled || typeof window === \"undefined\") {\n return () => {};\n }\n const commandsEnabled = options.commandsEnabled ?? resolveNonProductionEnvironment();\n\n const machineId = options.machineId?.trim() || createMachineId();\n const meta: JourneyDevtoolsMachineMeta = {\n machineId,\n label: options.label?.trim() || DEFAULT_MACHINE_LABEL,\n appName:\n options.appName?.trim() || (typeof document !== \"undefined\" ? document.title : \"\") || null,\n commandsEnabled\n };\n const targetOrigin = resolveWindowTargetOrigin();\n\n const createBaseEnvelope = <TKind extends JourneyDevtoolsBridgeEnvelope[\"kind\"]>(\n kind: TKind\n ) => ({\n channel: JOURNEY_DEVTOOLS_CHANNEL,\n version: JOURNEY_DEVTOOLS_PROTOCOL_VERSION,\n source: JOURNEY_DEVTOOLS_BRIDGE_SOURCE,\n kind,\n machineId,\n timestamp: Date.now()\n });\n\n const post = (envelope: JourneyDevtoolsBridgeEnvelope) => {\n try {\n window.postMessage(envelope, targetOrigin);\n } catch {\n // Swallow transport failures so bridge lifecycle and commands remain non-throwing.\n }\n };\n\n const postSnapshot = (snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>) => {\n const envelope: JourneyDevtoolsBridgeSnapshotEnvelope = {\n ...createBaseEnvelope(\"snapshot\"),\n snapshot: serializeSnapshot(snapshot)\n };\n post(envelope);\n };\n\n let isDetached = false;\n const rateLimiter = new CommandRateLimiter();\n let pendingSnapshot: JourneySnapshot<TContext, TStepId, TStepMeta> | null = null;\n let scheduledSnapshotHandle: number | ReturnType<typeof globalThis.setTimeout> | null = null;\n let scheduledSnapshotKind: SnapshotScheduleKind | null = null;\n\n const clearScheduledSnapshotState = () => {\n pendingSnapshot = null;\n scheduledSnapshotHandle = null;\n scheduledSnapshotKind = null;\n };\n\n const flushScheduledSnapshot = () => {\n const snapshot = pendingSnapshot;\n clearScheduledSnapshotState();\n\n if (!snapshot || isDetached) {\n return;\n }\n\n postSnapshot(snapshot);\n };\n\n const scheduleSnapshotPost = (snapshot: JourneySnapshot<TContext, TStepId, TStepMeta>) => {\n pendingSnapshot = snapshot;\n if (scheduledSnapshotHandle !== null) {\n return;\n }\n\n if (typeof window.requestAnimationFrame === \"function\") {\n scheduledSnapshotKind = \"raf\";\n scheduledSnapshotHandle = window.requestAnimationFrame(() => {\n flushScheduledSnapshot();\n });\n return;\n }\n\n scheduledSnapshotKind = \"timeout\";\n scheduledSnapshotHandle = globalThis.setTimeout(() => {\n flushScheduledSnapshot();\n }, 0);\n };\n\n const cancelScheduledSnapshot = () => {\n if (scheduledSnapshotHandle === null) {\n clearScheduledSnapshotState();\n return;\n }\n\n if (scheduledSnapshotKind === \"raf\" && typeof window.cancelAnimationFrame === \"function\") {\n window.cancelAnimationFrame(scheduledSnapshotHandle as number);\n } else {\n globalThis.clearTimeout(scheduledSnapshotHandle);\n }\n\n clearScheduledSnapshotState();\n };\n\n const onMessage = (event: MessageEvent<unknown>) => {\n if (\n event.source !== window ||\n !isExpectedWindowOrigin(event.origin) ||\n isDetached ||\n !isJourneyDevtoolsEnvelope(event.data)\n ) {\n return;\n }\n\n if (event.data.source !== JOURNEY_DEVTOOLS_EXTENSION_SOURCE || event.data.kind !== \"command\") {\n return;\n }\n\n const commandEnvelope: JourneyDevtoolsExtensionCommandEnvelope = event.data;\n if (commandEnvelope.machineId !== machineId) {\n return;\n }\n\n // Rate limiting to prevent command abuse\n if (!rateLimiter.isAllowed()) {\n const errorEnvelope: JourneyDevtoolsBridgeCommandErrorEnvelope = {\n ...createBaseEnvelope(\"commandError\"),\n requestId: commandEnvelope.requestId,\n error: serializeError(\n \"Command rate limit exceeded. Too many commands in a short time window.\"\n )\n };\n post(errorEnvelope);\n return;\n }\n\n if (!commandsEnabled) {\n const errorEnvelope: JourneyDevtoolsBridgeCommandErrorEnvelope = {\n ...createBaseEnvelope(\"commandError\"),\n requestId: commandEnvelope.requestId,\n error: serializeError(\"Bridge commands are disabled by configuration.\")\n };\n post(errorEnvelope);\n return;\n }\n\n const run = async () => {\n try {\n const outcome = await runCommand(\n machine as JourneyMachine<TContext, TStepId, string, Record<never, never>, TStepMeta>,\n commandEnvelope.command\n );\n if (isDetached) {\n return;\n }\n\n const resultEnvelope: JourneyDevtoolsBridgeCommandResultEnvelope = {\n ...createBaseEnvelope(\"commandResult\"),\n requestId: commandEnvelope.requestId,\n snapshot: serializeSnapshot(outcome.snapshot),\n ...(outcome.transitioned !== undefined ? { transitioned: outcome.transitioned } : {}),\n ...(outcome.transitionId ? { transitionId: outcome.transitionId } : {}),\n ...(\"error\" in outcome ? { error: outcome.error } : {})\n };\n post(resultEnvelope);\n } catch (error) {\n if (isDetached) {\n return;\n }\n\n const errorEnvelope: JourneyDevtoolsBridgeCommandErrorEnvelope = {\n ...createBaseEnvelope(\"commandError\"),\n requestId: commandEnvelope.requestId,\n error: serializeError(error)\n };\n post(errorEnvelope);\n }\n };\n\n void run();\n };\n\n window.addEventListener(\"message\", onMessage);\n\n const unsubscribe = machine.subscribe(() => {\n if (isDetached) {\n return;\n }\n scheduleSnapshotPost(machine.getSnapshot());\n });\n\n const registerEnvelope: JourneyDevtoolsBridgeRegisterEnvelope = {\n ...createBaseEnvelope(\"register\"),\n meta,\n snapshot: serializeSnapshot(machine.getSnapshot())\n };\n post(registerEnvelope);\n\n return () => {\n if (isDetached) {\n return;\n }\n\n isDetached = true;\n rateLimiter.reset();\n unsubscribe();\n window.removeEventListener(\"message\", onMessage);\n cancelScheduledSnapshot();\n\n const unregisterEnvelope: JourneyDevtoolsBridgeUnregisterEnvelope = {\n ...createBaseEnvelope(\"unregister\")\n };\n post(unregisterEnvelope);\n };\n};\n"],
5
+ "mappings": "AAEO,IAAMA,EAAoC,EACpCC,EAA2B,6BAE3BC,EAAiC,uBACjCC,EAAoC,0BAoG3CC,E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EAAKsB,CAAkB,CACzB,CACF",
6
+ "names": ["JOURNEY_DEVTOOLS_PROTOCOL_VERSION", "JOURNEY_DEVTOOLS_CHANNEL", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "isRecord", "value", "isKnownSource", "isSafePayload", "value", "serialized", "isStructureSafe", "depth", "item", "prop", "hasBaseEnvelopeShape", "isRecord", "JOURNEY_DEVTOOLS_CHANNEL", "isKnownSource", "isSendEvent", "isJourneyDevtoolsCommand", "isJourneyDevtoolsBridgeEnvelope", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "envelope", "isJourneyDevtoolsExtensionEnvelope", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "isJourneyDevtoolsEnvelope", "DEFAULT_MACHINE_LABEL", "isRecord", "value", "isJourneyAsyncPhase", "resolveImportMetaEnvironment", "bundlerEnv", "resolveNodeEnvironment", "nodeEnv", "resolveNonProductionEnvironment", "options", "resolvedBundlerEnv", "resolvedNodeEnv", "resolveWindowTargetOrigin", "isExpectedWindowOrigin", "origin", "expected", "createMachineId", "CommandRateLimiter", "maxCommandsPerWindow", "windowMs", "now", "windowStart", "ts", "cloneForTransport", "transportValue", "seen", "serialized", "_key", "currentValue", "serializeError", "error", "cause", "serializeSnapshot", "snapshot", "byStep", "stepId", "stepState", "isVisited", "isKnownStepId", "assertKnownStepId", "machine", "commandType", "toSendOutcome", "result", "runCommand", "command", "sendEvent", "attachJourneyDevtools", "commandsEnabled", "machineId", "meta", "targetOrigin", "createBaseEnvelope", "kind", "JOURNEY_DEVTOOLS_CHANNEL", "JOURNEY_DEVTOOLS_BRIDGE_SOURCE", "post", "envelope", "postSnapshot", "isDetached", "rateLimiter", "pendingSnapshot", "scheduledSnapshotHandle", "scheduledSnapshotKind", "clearScheduledSnapshotState", "flushScheduledSnapshot", "scheduleSnapshotPost", "cancelScheduledSnapshot", "onMessage", "event", "isJourneyDevtoolsEnvelope", "JOURNEY_DEVTOOLS_EXTENSION_SOURCE", "commandEnvelope", "errorEnvelope", "outcome", "resultEnvelope", "unsubscribe", "registerEnvelope", "unregisterEnvelope"]
7
7
  }
@@ -78,6 +78,7 @@ export type JourneyDevtoolsBridgeCommandResultEnvelope = JourneyDevtoolsEnvelope
78
78
  snapshot: JourneyDevtoolsSerializableSnapshot;
79
79
  transitioned?: boolean;
80
80
  transitionId?: string;
81
+ error?: JourneyDevtoolsSerializedError;
81
82
  };
82
83
  export type JourneyDevtoolsBridgeCommandErrorEnvelope = JourneyDevtoolsEnvelopeBase & {
83
84
  source: typeof JOURNEY_DEVTOOLS_BRIDGE_SOURCE;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rxova/journey-devtools-bridge",
3
- "version": "0.6.3",
3
+ "version": "0.7.0",
4
4
  "description": "Bridge API to connect Journey machines to browser devtools.",
5
5
  "keywords": [
6
6
  "journey",
@@ -45,7 +45,7 @@
45
45
  ],
46
46
  "sideEffects": false,
47
47
  "dependencies": {
48
- "@rxova/journey-core": "^0.6.3"
48
+ "@rxova/journey-core": "^0.7.0"
49
49
  },
50
50
  "size-limit": [
51
51
  {
@@ -56,8 +56,8 @@
56
56
  }
57
57
  ],
58
58
  "scripts": {
59
- "build": "pnpm run clean && node ./scripts/build.mjs && tsc -p tsconfig.build.json && node ../../scripts/copy-types.mjs dist",
60
- "clean": "node ../../scripts/clean-paths.mjs dist tsconfig.build.tsbuildinfo",
59
+ "build": "pnpm run clean && node --import tsx ./scripts/build.ts && tsc -p tsconfig.build.json && node --import tsx ../../scripts/copy-types.ts dist",
60
+ "clean": "node --import tsx ../../scripts/clean-paths.ts dist tsconfig.build.tsbuildinfo",
61
61
  "coverage": "pnpm --workspace-root vitest run --coverage --coverage.include=packages/devtools-bridge/src/** --coverage.reporter=text-summary",
62
62
  "typecheck": "tsc --noEmit -p tsconfig.json",
63
63
  "publint": "publint",