diff --git a/.husky/.gitignore b/.husky/.gitignore new file mode 100644 index 0000000..31354ec --- /dev/null +++ b/.husky/.gitignore @@ -0,0 +1 @@ +_ diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 0000000..36af219 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,4 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + +npx lint-staged diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..8771bfc --- /dev/null +++ b/.prettierrc @@ -0,0 +1,9 @@ +{ + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "semi": true, + "singleQuote": true, + "trailingComma": "none", + "bracketSpacing": true +} diff --git a/babel.config.js b/babel.config.js index eb8f900..f13032a 100644 --- a/babel.config.js +++ b/babel.config.js @@ -1,7 +1,7 @@ module.exports = { presets: [ - ["@babel/preset-env", { targets: { node: "12" } }], - "@babel/preset-typescript", - "@babel/preset-react", - ], + ['@babel/preset-env', { targets: { node: '12' } }], + '@babel/preset-typescript', + '@babel/preset-react' + ] }; diff --git a/example-site/next.config.js b/example-site/next.config.js index bbb1729..113c45d 100644 --- a/example-site/next.config.js +++ b/example-site/next.config.js @@ -1,5 +1,5 @@ module.exports = { typescript: { - ignoreBuildErrors: true, - }, + ignoreBuildErrors: true + } }; diff --git a/example-site/postcss.config.js b/example-site/postcss.config.js index 4a15258..5789178 100644 --- a/example-site/postcss.config.js +++ b/example-site/postcss.config.js @@ -2,6 +2,6 @@ module.exports = { plugins: { tailwindcss: {}, - autoprefixer: {}, - }, + autoprefixer: {} + } }; diff --git a/example-site/src/pages/_app.tsx b/example-site/src/pages/_app.tsx index cfd0295..0a4203e 100644 --- a/example-site/src/pages/_app.tsx +++ b/example-site/src/pages/_app.tsx @@ -1,6 +1,6 @@ -import type { AppProps } from "next/app"; -import "../index.css"; -import Head from "next/head"; +import type { AppProps } from 'next/app'; +import '../index.css'; +import Head from 'next/head'; function MyApp({ Component, pageProps }: AppProps) { return ( diff --git a/example-site/src/pages/index.tsx b/example-site/src/pages/index.tsx index a7aa225..bb5d47c 100644 --- a/example-site/src/pages/index.tsx +++ b/example-site/src/pages/index.tsx @@ -1,15 +1,15 @@ -import React, { useMemo, useState } from "react"; -import { parseMachinesFromFile } from "xstate-parser-demo"; +import React, { useMemo, useState } from 'react'; +import { parseMachinesFromFile } from 'xstate-parser-demo'; function App() { const [text, setText] = useState(`createMachine({ initial: 'wow' })`); const result = useMemo(() => { try { return parseMachinesFromFile(text).machines.map((machine) => { - return machine.toConfig() || "could not compile"; + return machine.toConfig() || 'could not compile'; }); } catch (e) { - return "Could not parse"; + return 'Could not parse'; } }, [text]); diff --git a/example-site/tailwind.config.js b/example-site/tailwind.config.js index 6b71cd3..17c6450 100644 --- a/example-site/tailwind.config.js +++ b/example-site/tailwind.config.js @@ -1,12 +1,12 @@ // tailwind.config.js module.exports = { - purge: ["./index.html", "./src/**/*.{vue,js,ts,jsx,tsx}"], + purge: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'], darkMode: false, // or 'media' or 'class' theme: { - extend: {}, + extend: {} }, variants: { - extend: {}, + extend: {} }, - plugins: [], + plugins: [] }; diff --git a/example-site/tsconfig.json b/example-site/tsconfig.json index 69a5b1c..15a4006 100644 --- a/example-site/tsconfig.json +++ b/example-site/tsconfig.json @@ -2,11 +2,7 @@ "compilerOptions": { "target": "ESNext", "useDefineForClassFields": true, - "lib": [ - "DOM", - "DOM.Iterable", - "ESNext" - ], + "lib": ["DOM", "DOM.Iterable", "ESNext"], "allowJs": false, "skipLibCheck": true, "esModuleInterop": true, @@ -20,10 +16,6 @@ "noEmit": true, "jsx": "preserve" }, - "include": [ - "./src" - ], - "exclude": [ - "node_modules" - ] -} \ No newline at end of file + "include": ["./src"], + "exclude": ["node_modules"] +} diff --git a/examples/actions.ts b/examples/actions.ts index 8bb1e4b..2e29dc0 100644 --- a/examples/actions.ts +++ b/examples/actions.ts @@ -1,4 +1,4 @@ -import { createMachine, actions } from "xstate"; +import { createMachine, actions } from 'xstate'; const { after, @@ -16,27 +16,27 @@ const { sendParent, sendUpdate, start, - stop, + stop } = actions; export const machine = createMachine({ entry: [ after(400), assign({}), - cancel(""), - done(""), - escalate(""), - forwardTo(""), + cancel(''), + done(''), + escalate(''), + forwardTo(''), log(), pure(() => { return []; }), - raise(""), - respond(""), - send(""), - sendParent(""), + raise(''), + respond(''), + send(''), + sendParent(''), sendUpdate(), - start(""), - stop(""), - ], + start(''), + stop('') + ] }); diff --git a/examples/always.ts b/examples/always.ts index 9311eaf..a017167 100644 --- a/examples/always.ts +++ b/examples/always.ts @@ -9,16 +9,16 @@ // - actions // - XState (all XState exports) -import { assign, Machine } from "xstate"; +import { assign, Machine } from 'xstate'; export const always = Machine({ - initial: "checking", + initial: 'checking', states: { checking: { always: { - target: "next", - }, + target: 'next' + } }, - next: {}, - }, + next: {} + } }); diff --git a/examples/arraysAsTargets.ts b/examples/arraysAsTargets.ts index 6090504..26c36fe 100644 --- a/examples/arraysAsTargets.ts +++ b/examples/arraysAsTargets.ts @@ -1,33 +1,33 @@ -import { createMachine } from "xstate"; +import { createMachine } from 'xstate'; export const arraysAsTargets = createMachine({ - type: "parallel", + type: 'parallel', on: { - "*": [ + '*': [ { - target: ["first.a", "second.b"], + target: ['first.a', 'second.b'] }, { - target: ["first.c", "second.a"], - }, - ], + target: ['first.c', 'second.a'] + } + ] }, states: { first: { - initial: "a", + initial: 'a', states: { a: {}, b: {}, - c: {}, - }, + c: {} + } }, second: { - initial: "a", + initial: 'a', states: { a: {}, b: {}, - c: {}, - }, - }, - }, + c: {} + } + } + } }); diff --git a/examples/audio-recorder.machine.ts b/examples/audio-recorder.machine.ts index d45bb9b..0539ec5 100644 --- a/examples/audio-recorder.machine.ts +++ b/examples/audio-recorder.machine.ts @@ -3,8 +3,8 @@ import { createMachine, DoneInvokeEvent, forwardTo, - Sender, -} from "xstate"; + Sender +} from 'xstate'; export interface AudioRecorderMachineContext { stream?: MediaStream; @@ -13,26 +13,26 @@ export interface AudioRecorderMachineContext { export type AudioRecorderMachineEvent = | { - type: "RETRY"; + type: 'RETRY'; } | { - type: "RECORD"; + type: 'RECORD'; } | { - type: "AUDIO_CHUNK_RECEIVED"; + type: 'AUDIO_CHUNK_RECEIVED'; blob: Blob; } | { - type: "PAUSE"; + type: 'PAUSE'; } | { - type: "RESUME"; + type: 'RESUME'; } | { - type: "STOP"; + type: 'STOP'; } | { - type: "DOWNLOAD"; + type: 'DOWNLOAD'; }; const audioRecorderMachine = createMachine< @@ -40,102 +40,102 @@ const audioRecorderMachine = createMachine< AudioRecorderMachineEvent >( { - id: "audioRecorder", - initial: "idle", + id: 'audioRecorder', + initial: 'idle', context: { - mediaChunks: [], + mediaChunks: [] }, - exit: "removeMediaStream", + exit: 'removeMediaStream', states: { idle: { on: { RECORD: { - target: "requestingAudioOptions", - }, - }, + target: 'requestingAudioOptions' + } + } }, requestingAudioOptions: { invoke: { - src: "requestAudioOptions", + src: 'requestAudioOptions', onError: { - target: "couldNotRetrieveAudioOptions", + target: 'couldNotRetrieveAudioOptions' }, onDone: { - target: "recording", - actions: "assignStreamToContext", - }, - }, + target: 'recording', + actions: 'assignStreamToContext' + } + } }, recordingFailed: { on: { - RETRY: { target: "recording" }, - }, + RETRY: { target: 'recording' } + } }, recording: { on: { AUDIO_CHUNK_RECEIVED: { - actions: "appendBlob", + actions: 'appendBlob' }, STOP: { - target: "complete", - }, + target: 'complete' + } }, invoke: { - id: "recording", - src: "recordFromStream", + id: 'recording', + src: 'recordFromStream', onError: { - target: "recordingFailed", + target: 'recordingFailed', actions: (context, event) => { console.error(event); - }, - }, + } + } }, - initial: "running", + initial: 'running', states: { running: { on: { PAUSE: { - target: "paused", - actions: forwardTo("recording"), - }, - }, + target: 'paused', + actions: forwardTo('recording') + } + } }, paused: { on: { RESUME: { - target: "running", - actions: forwardTo("recording"), - }, - }, - }, - }, + target: 'running', + actions: forwardTo('recording') + } + } + } + } }, complete: { on: { RETRY: { - target: "recording", - actions: "clearBlobData", + target: 'recording', + actions: 'clearBlobData' }, DOWNLOAD: { - actions: "downloadBlob", - }, - }, + actions: 'downloadBlob' + } + } }, couldNotRetrieveAudioOptions: { on: { - RETRY: { target: "requestingAudioOptions" }, - }, - }, - }, + RETRY: { target: 'requestingAudioOptions' } + } + } + } }, { actions: { downloadBlob: (context) => { const blob = new Blob(context.mediaChunks, { - type: "audio/ogg; codecs=opus", + type: 'audio/ogg; codecs=opus' }); const url = URL.createObjectURL(blob); - const downloadLink = document.createElement("a"); + const downloadLink = document.createElement('a'); downloadLink.href = url; downloadLink.download = `file.ogg`; @@ -152,20 +152,20 @@ const audioRecorderMachine = createMachine< assignStreamToContext: assign((context, event) => { return { stream: (event as DoneInvokeEvent).data - .stream, + .stream }; }), clearBlobData: assign((context) => { return { - mediaChunks: [], + mediaChunks: [] }; }), appendBlob: assign((context, event) => { - if (event.type !== "AUDIO_CHUNK_RECEIVED") return {}; + if (event.type !== 'AUDIO_CHUNK_RECEIVED') return {}; return { - mediaChunks: [...context.mediaChunks, event.blob], + mediaChunks: [...context.mediaChunks, event.blob] }; - }), + }) }, services: { recordFromStream: (context) => (send, onReceive) => { @@ -175,37 +175,37 @@ const audioRecorderMachine = createMachine< // @ts-ignore mediaRecorder.ondataavailable = (e) => { send({ - type: "AUDIO_CHUNK_RECEIVED", - blob: e.data, + type: 'AUDIO_CHUNK_RECEIVED', + blob: e.data }); }; mediaRecorder.start(200); onReceive((event) => { - if (event.type === "PAUSE") { + if (event.type === 'PAUSE') { mediaRecorder.pause(); - } else if (event.type === "RESUME") { + } else if (event.type === 'RESUME') { mediaRecorder.resume(); } }); return () => { - if (mediaRecorder.state !== "inactive") { + if (mediaRecorder.state !== 'inactive') { mediaRecorder.stop(); } }; }, requestAudioOptions: async () => { const stream = await navigator.mediaDevices.getUserMedia({ - audio: true, + audio: true }); return { - stream, + stream }; - }, - }, - }, + } + } + } ); export default audioRecorderMachine; diff --git a/examples/audio-video-device-selection.machine.ts b/examples/audio-video-device-selection.machine.ts index 50162f0..0481659 100644 --- a/examples/audio-video-device-selection.machine.ts +++ b/examples/audio-video-device-selection.machine.ts @@ -4,7 +4,7 @@ import { DoneInvokeEvent, EventObject, Sender, - StateNodeConfig, + StateNodeConfig } from 'xstate'; export interface AudioVideoDeviceSelectionMachineContext { @@ -48,24 +48,24 @@ const audioVideoDeviceSelectionMachine = createMachine< videoInputDevices: [], formValues: { username: '', - password: '', - }, + password: '' + } }, states: { requestingDevices: { invoke: { src: 'requestAudioOptions', onError: { - target: 'couldNotRetrieveDevices', + target: 'couldNotRetrieveDevices' }, onDone: { actions: [ 'assignDevicesToContext', - 'assignDefaultDevicesToContext', + 'assignDefaultDevicesToContext' ], - target: 'gotDevices', - }, - }, + target: 'gotDevices' + } + } }, couldNotRetrieveDevices: {}, gotDevices: { @@ -75,10 +75,9 @@ const audioVideoDeviceSelectionMachine = createMachine< Boolean(context.audioInputDevices[event.index]), actions: assign((context, event) => { return { - selectedAudioInputDevice: - context.audioInputDevices[event.index], + selectedAudioInputDevice: context.audioInputDevices[event.index] }; - }), + }) }, CHOOSE_AUDIO_OUTPUT_DEVICE: { cond: (context, event) => @@ -86,52 +85,51 @@ const audioVideoDeviceSelectionMachine = createMachine< actions: assign((context, event) => { return { selectedAudioOutputDevice: - context.audioOutputDevices[event.index], + context.audioOutputDevices[event.index] }; - }), + }) }, CHOOSE_VIDEO_DEVICE: { cond: (context, event) => Boolean(context.videoInputDevices[event.index]), actions: assign((context, event) => { return { - selectedVideoInputDevice: - context.videoInputDevices[event.index], + selectedVideoInputDevice: context.videoInputDevices[event.index] }; - }), - }, - }, - }, - }, + }) + } + } + } + } }, { actions: { assignDevicesToContext: assign((context, event: unknown) => { return { audioInputDevices: (event as DevicesDoneEvent).data.devices.filter( - (device) => device.deviceId && device.kind === 'audioinput', + (device) => device.deviceId && device.kind === 'audioinput' ), audioOutputDevices: (event as DevicesDoneEvent).data.devices.filter( - (device) => device.deviceId && device.kind === 'audiooutput', + (device) => device.deviceId && device.kind === 'audiooutput' ), videoInputDevices: (event as DevicesDoneEvent).data.devices.filter( - (device) => device.deviceId && device.kind === 'videoinput', - ), + (device) => device.deviceId && device.kind === 'videoinput' + ) }; }), assignDefaultDevicesToContext: assign((context) => { return { selectedAudioInputDevice: context.audioInputDevices[0], selectedAudioOutputDevice: context.audioOutputDevices[0], - selectedVideoInputDevice: context.videoInputDevices[0], + selectedVideoInputDevice: context.videoInputDevices[0] }; - }), + }) }, services: { requestAudioOptions: async () => { const stream = await navigator.mediaDevices.getUserMedia({ audio: true, - video: true, + video: true }); const devices = await navigator.mediaDevices.enumerateDevices(); @@ -140,11 +138,11 @@ const audioVideoDeviceSelectionMachine = createMachine< }); return { - devices, + devices }; - }, - }, - }, + } + } + } ); export default audioVideoDeviceSelectionMachine; diff --git a/examples/authentication.machine.ts b/examples/authentication.machine.ts index bd0b950..caff3d5 100644 --- a/examples/authentication.machine.ts +++ b/examples/authentication.machine.ts @@ -1,4 +1,4 @@ -import { assign, createMachine, Sender } from "xstate"; +import { assign, createMachine, Sender } from 'xstate'; export type AuthenticationMachineContext = { userDetails?: UserDetails; @@ -10,17 +10,17 @@ interface UserDetails { export type AuthenticationMachineEvent = | { - type: "REPORT_IS_LOGGED_IN"; + type: 'REPORT_IS_LOGGED_IN'; userDetails: UserDetails; } | { - type: "REPORT_IS_LOGGED_OUT"; + type: 'REPORT_IS_LOGGED_OUT'; } | { - type: "LOG_OUT"; + type: 'LOG_OUT'; } | { - type: "LOG_IN"; + type: 'LOG_IN'; userDetails: UserDetails; }; @@ -29,41 +29,41 @@ const authenticationMachine = createMachine< AuthenticationMachineEvent >( { - id: "authentication", - initial: "checkingIfLoggedIn", + id: 'authentication', + initial: 'checkingIfLoggedIn', states: { checkingIfLoggedIn: { invoke: { - src: "checkIfLoggedIn", + src: 'checkIfLoggedIn', onError: { - target: "loggedOut", - }, + target: 'loggedOut' + } }, on: { REPORT_IS_LOGGED_IN: { - target: "loggedIn", - actions: "assignUserDetailsToContext", + target: 'loggedIn', + actions: 'assignUserDetailsToContext' }, - REPORT_IS_LOGGED_OUT: { target: "loggedOut" }, - }, + REPORT_IS_LOGGED_OUT: { target: 'loggedOut' } + } }, loggedIn: { on: { LOG_OUT: { - target: "loggedOut", - }, - }, + target: 'loggedOut' + } + } }, loggedOut: { - entry: ["navigateToAuthPage", "clearUserDetailsFromContext"], + entry: ['navigateToAuthPage', 'clearUserDetailsFromContext'], on: { LOG_IN: { - target: "loggedIn", - actions: "assignUserDetailsToContext", - }, - }, - }, - }, + target: 'loggedIn', + actions: 'assignUserDetailsToContext' + } + } + } + } }, { services: { @@ -82,7 +82,7 @@ const authenticationMachine = createMachine< // type: "REPORT_IS_LOGGED_OUT", // }); // } - }, + } }, actions: { navigateToAuthPage: () => { @@ -90,18 +90,18 @@ const authenticationMachine = createMachine< // should take them to the /auth route }, assignUserDetailsToContext: assign((context, event) => { - if (event.type !== "REPORT_IS_LOGGED_IN") { + if (event.type !== 'REPORT_IS_LOGGED_IN') { return {}; } return { - userDetails: event.userDetails, + userDetails: event.userDetails }; }), clearUserDetailsFromContext: assign((context) => ({ - userDetails: undefined, - })), - }, - }, + userDetails: undefined + })) + } + } ); export default authenticationMachine; diff --git a/examples/cast.ts b/examples/cast.ts index b9d898b..3119bfb 100644 --- a/examples/cast.ts +++ b/examples/cast.ts @@ -1,3 +1,3 @@ -import { createMachine } from "xstate"; +import { createMachine } from 'xstate'; export const machine = createMachine({} as any); diff --git a/examples/confirmation-dialog.machine.ts b/examples/confirmation-dialog.machine.ts index 6039c56..d5ba998 100644 --- a/examples/confirmation-dialog.machine.ts +++ b/examples/confirmation-dialog.machine.ts @@ -1,4 +1,4 @@ -import { assign, createMachine } from "xstate"; +import { assign, createMachine } from 'xstate'; export interface ConfirmationDialogMachineContext { action?: () => Promise; @@ -7,14 +7,14 @@ export interface ConfirmationDialogMachineContext { type ConfirmationDialogMachineEvent = | { - type: "OPEN_DIALOG"; + type: 'OPEN_DIALOG'; action: () => Promise; } | { - type: "CONFIRM"; + type: 'CONFIRM'; } | { - type: "CANCEL"; + type: 'CANCEL'; }; const confirmationDialogMachine = createMachine< @@ -22,75 +22,75 @@ const confirmationDialogMachine = createMachine< ConfirmationDialogMachineEvent >( { - id: "confirmationDialog", - initial: "closed", + id: 'confirmationDialog', + initial: 'closed', states: { closed: { - id: "closed", + id: 'closed', on: { OPEN_DIALOG: { - target: "open", - actions: "assignActionToContext", - }, - }, + target: 'open', + actions: 'assignActionToContext' + } + } }, open: { - exit: "clearErrorMessage", - initial: "idle", + exit: 'clearErrorMessage', + initial: 'idle', states: { idle: { on: { - CANCEL: { target: "#closed" }, - CONFIRM: { target: "executingAction" }, - }, + CANCEL: { target: '#closed' }, + CONFIRM: { target: 'executingAction' } + } }, executingAction: { invoke: { - src: "executeAction", + src: 'executeAction', onError: { - target: "idle", - actions: "assignErrorMessageToContext", + target: 'idle', + actions: 'assignErrorMessageToContext' }, onDone: { - target: "#closed", - actions: ["clearActionFromContext", "onSuccess"], - }, - }, - }, - }, - }, - }, + target: '#closed', + actions: ['clearActionFromContext', 'onSuccess'] + } + } + } + } + } + } }, { services: { executeAction: (context) => () => { // For demonstration purposes, I've commented this out. // await context.action() - }, + } }, actions: { assignActionToContext: assign((context, event) => { - if (event.type !== "OPEN_DIALOG") return {}; + if (event.type !== 'OPEN_DIALOG') return {}; return { - action: event.action, + action: event.action }; }), assignErrorMessageToContext: assign((context, event: any) => { return { - errorMessage: event.data?.message || "An unknown error occurred", + errorMessage: event.data?.message || 'An unknown error occurred' }; }), clearErrorMessage: assign((context) => ({ - errorMessage: undefined, + errorMessage: undefined })), clearActionFromContext: assign((context) => ({ - action: undefined, + action: undefined })), onSuccess: () => { - alert("onSuccess fired!"); - }, - }, - }, + alert('onSuccess fired!'); + } + } + } ); export default confirmationDialogMachine; diff --git a/examples/create-or-update-form.machine.ts b/examples/create-or-update-form.machine.ts index 4e7eb35..bee6314 100644 --- a/examples/create-or-update-form.machine.ts +++ b/examples/create-or-update-form.machine.ts @@ -1,4 +1,4 @@ -import { assign, createMachine, Sender } from "xstate"; +import { assign, createMachine, Sender } from 'xstate'; export interface CreateOrUpdateFormMachineContext { isInEditMode: boolean; @@ -12,15 +12,15 @@ interface Item { export type CreateOrUpdateFormMachineEvent = | { - type: "SUBMIT"; + type: 'SUBMIT'; item: Item; } | { - type: "SUCCESSFULLY_FETCHED_ITEM"; + type: 'SUCCESSFULLY_FETCHED_ITEM'; item: Item; } | { - type: "RETRY"; + type: 'RETRY'; }; const createOrUpdateFormMachine = createMachine< @@ -28,102 +28,102 @@ const createOrUpdateFormMachine = createMachine< CreateOrUpdateFormMachineEvent >( { - id: "createOrUpdateForm", - initial: "checkingIfInEditMode", + id: 'createOrUpdateForm', + initial: 'checkingIfInEditMode', context: { // Randomly true or false - isInEditMode: Math.random() < 0.5, + isInEditMode: Math.random() < 0.5 }, states: { checkingIfInEditMode: { always: [ { - cond: "isInEditMode", - target: "fetchingItemToEdit", + cond: 'isInEditMode', + target: 'fetchingItemToEdit' }, { - target: "awaitingSubmit", - }, - ], + target: 'awaitingSubmit' + } + ] }, fetchingItemToEdit: { invoke: { - src: "fetchItem", + src: 'fetchItem', onError: { - target: "failedToFetch", - actions: "assignErrorMessageToContext", - }, + target: 'failedToFetch', + actions: 'assignErrorMessageToContext' + } }, on: { SUCCESSFULLY_FETCHED_ITEM: { - target: "awaitingSubmit", - actions: "assignItemToContext", - }, - }, + target: 'awaitingSubmit', + actions: 'assignItemToContext' + } + } }, failedToFetch: { - exit: "clearErrorMessage", + exit: 'clearErrorMessage', on: { - RETRY: { target: "fetchingItemToEdit" }, - }, + RETRY: { target: 'fetchingItemToEdit' } + } }, awaitingSubmit: { - id: "awaitingSubmit", - exit: "clearErrorMessage", + id: 'awaitingSubmit', + exit: 'clearErrorMessage', on: { SUBMIT: { - target: "submitting", - actions: "assignItemToContext", - }, - }, + target: 'submitting', + actions: 'assignItemToContext' + } + } }, submitting: { - initial: "checkingIfInEditMode", + initial: 'checkingIfInEditMode', states: { checkingIfInEditMode: { always: [ { - cond: "isInEditMode", - target: "editing", + cond: 'isInEditMode', + target: 'editing' }, { - target: "creating", - }, - ], + target: 'creating' + } + ] }, editing: { invoke: { - src: "editItem", - onDone: { target: "#complete", actions: "onEditSuccess" }, + src: 'editItem', + onDone: { target: '#complete', actions: 'onEditSuccess' }, onError: { - target: "#awaitingSubmit", - actions: "assignErrorMessageToContext", - }, - }, + target: '#awaitingSubmit', + actions: 'assignErrorMessageToContext' + } + } }, creating: { invoke: { - src: "createItem", - onDone: { target: "#complete", actions: "onCreateSuccess" }, + src: 'createItem', + onDone: { target: '#complete', actions: 'onCreateSuccess' }, onError: { - target: "#awaitingSubmit", - actions: "assignErrorMessageToContext", - }, - }, - }, - }, + target: '#awaitingSubmit', + actions: 'assignErrorMessageToContext' + } + } + } + } }, complete: { - id: "complete", - type: "final", - }, - }, + id: 'complete', + type: 'final' + } + } }, { guards: { isInEditMode: (context) => { return context.isInEditMode; - }, + } }, services: { fetchItem: () => async (send: Sender) => { @@ -135,35 +135,35 @@ const createOrUpdateFormMachine = createMachine< // }); }, editItem: () => () => {}, - createItem: () => () => {}, + createItem: () => () => {} }, actions: { onCreateSuccess: () => { - alert("onCreateSuccess"); + alert('onCreateSuccess'); }, onEditSuccess: () => { - alert("onEditSuccess"); + alert('onEditSuccess'); }, clearErrorMessage: assign((context) => ({ - errorMessage: undefined, + errorMessage: undefined })), assignErrorMessageToContext: assign((context, event: any) => { return { - errorMessage: event.data?.message || "An unknown error occurred", + errorMessage: event.data?.message || 'An unknown error occurred' }; }), assignItemToContext: assign((context, event) => { if ( - event.type !== "SUCCESSFULLY_FETCHED_ITEM" && - event.type !== "SUBMIT" + event.type !== 'SUCCESSFULLY_FETCHED_ITEM' && + event.type !== 'SUBMIT' ) return {}; return { - itemToProcess: event.item, + itemToProcess: event.item }; - }), - }, - }, + }) + } + } ); export default createOrUpdateFormMachine; diff --git a/examples/debounce.machine.ts b/examples/debounce.machine.ts index db44af2..8976744 100644 --- a/examples/debounce.machine.ts +++ b/examples/debounce.machine.ts @@ -1,11 +1,11 @@ -import { assign, createMachine } from "xstate"; +import { assign, createMachine } from 'xstate'; export interface DebounceMachineContext { action?: () => void; } export type DebounceMachineEvent = { - type: "GO"; + type: 'GO'; action: () => void; }; @@ -14,48 +14,48 @@ const debounceMachine = createMachine< DebounceMachineEvent >( { - id: "debounce", - initial: "idle", + id: 'debounce', + initial: 'idle', states: { idle: { on: { GO: { - actions: "assignActionToContext", - target: "debouncing", - }, - }, + actions: 'assignActionToContext', + target: 'debouncing' + } + } }, debouncing: { on: { GO: { - actions: "assignActionToContext", - target: "debouncing", - }, + actions: 'assignActionToContext', + target: 'debouncing' + } }, after: { 2000: { - target: "idle", - actions: "performAction", - }, - }, - }, - }, + target: 'idle', + actions: 'performAction' + } + } + } + } }, { actions: { clearAction: assign((context) => ({ - action: undefined, + action: undefined })), assignActionToContext: assign((context, event) => { return { - action: event.action, + action: event.action }; }), performAction: (context) => { return context.action?.(); - }, - }, - }, + } + } + } ); export default debounceMachine; diff --git a/examples/deduplication.machine.ts b/examples/deduplication.machine.ts index 3e0f62e..806c5b4 100644 --- a/examples/deduplication.machine.ts +++ b/examples/deduplication.machine.ts @@ -19,26 +19,26 @@ const deduplicationMachine = createMachine< on: { GO: { target: 'deduplicating', - actions: 'performAction', - }, - }, + actions: 'performAction' + } + } }, deduplicating: { after: { 2000: { - target: 'canPerformAction', - }, - }, - }, - }, + target: 'canPerformAction' + } + } + } + } }, { actions: { performAction: (context, event) => { return event.action(); - }, - }, - }, + } + } + } ); export default deduplicationMachine; diff --git a/examples/delays.machine.ts b/examples/delays.machine.ts index cfb5bb2..f2c835d 100644 --- a/examples/delays.machine.ts +++ b/examples/delays.machine.ts @@ -1,18 +1,18 @@ -import { createMachine } from "xstate"; +import { createMachine } from 'xstate'; export const machine = createMachine( { after: { DELAY_NAME: { actions: () => { - console.log("Yay"); - }, - }, - }, + console.log('Yay'); + } + } + } }, { delays: { - DELAY_NAME: 200, - }, - }, + DELAY_NAME: 200 + } + } ); diff --git a/examples/drag-and-drop.machine.ts b/examples/drag-and-drop.machine.ts index e888b0d..049bb23 100644 --- a/examples/drag-and-drop.machine.ts +++ b/examples/drag-and-drop.machine.ts @@ -1,4 +1,4 @@ -import { assign, createMachine } from "xstate"; +import { assign, createMachine } from 'xstate'; export interface DragAndDropMachineContext { dataList: Data[]; @@ -14,14 +14,14 @@ interface Data { export type DragAndDropMachineEvent = | { - type: "DROP"; + type: 'DROP'; } | { - type: "DRAG_REACHED_INTERSECTION"; + type: 'DRAG_REACHED_INTERSECTION'; index: number; } | { - type: "PICK_UP"; + type: 'PICK_UP'; index: number; }; // | { @@ -36,64 +36,64 @@ const dragAndDropMachine = createMachine< DragAndDropMachineEvent >( { - id: "dragAndDrop", - initial: "idle", + id: 'dragAndDrop', + initial: 'idle', context: { dataList: [ { - id: 0, + id: 0 }, { - id: 1, + id: 1 }, { - id: 2, - }, - ], + id: 2 + } + ] }, states: { idle: { on: { PICK_UP: { - target: "dragging", - actions: "assignPickedUpItemToContext", - }, - }, + target: 'dragging', + actions: 'assignPickedUpItemToContext' + } + } }, dragging: { on: { DROP: { - target: "idle", + target: 'idle', actions: [ - "rearrangeListBasedOnIndex", - "removeItemBeingHeldFromContext", - ], + 'rearrangeListBasedOnIndex', + 'removeItemBeingHeldFromContext' + ] }, DRAG_REACHED_INTERSECTION: { - actions: "assignCurrentPositionToContext", - }, - }, - }, - }, + actions: 'assignCurrentPositionToContext' + } + } + } + } }, { actions: { assignPickedUpItemToContext: assign((context, event) => { - if (event.type !== "PICK_UP") return {}; + if (event.type !== 'PICK_UP') return {}; return { itemBeingHeld: { currentIndex: event.index, - startIndex: event.index, - }, + startIndex: event.index + } }; }), removeItemBeingHeldFromContext: assign((context) => { return { - itemBeingHeld: undefined, + itemBeingHeld: undefined }; }), rearrangeListBasedOnIndex: assign((context, event) => { - if (event.type !== "DROP") return {}; + if (event.type !== 'DROP') return {}; const newDataList = [...context.dataList]; @@ -101,23 +101,23 @@ const dragAndDropMachine = createMachine< newDataList.splice( context.itemBeingHeld?.currentIndex!, 0, - context.dataList[context.itemBeingHeld?.startIndex!], + context.dataList[context.itemBeingHeld?.startIndex!] ); return { - dataList: newDataList, + dataList: newDataList }; }), assignCurrentPositionToContext: assign((context, event) => { - if (event.type !== "DRAG_REACHED_INTERSECTION") return {}; + if (event.type !== 'DRAG_REACHED_INTERSECTION') return {}; return { itemBeingHeld: { ...context.itemBeingHeld!, - currentIndex: event.index, - }, + currentIndex: event.index + } }; - }), - }, - }, + }) + } + } ); export default dragAndDropMachine; diff --git a/examples/dynamic.ts b/examples/dynamic.ts index 1b7bd9d..93a8474 100644 --- a/examples/dynamic.ts +++ b/examples/dynamic.ts @@ -1,24 +1,24 @@ -import { createMachine } from "xstate"; +import { createMachine } from 'xstate'; const states = { - first: "FIRST", - second: "SECOND", + first: 'FIRST', + second: 'SECOND', third: { - fourth: "FOURTH", + fourth: 'FOURTH', deep: { - wow: "wow", - }, - }, + wow: 'wow' + } + } }; export const dynamic = createMachine({ initial: states.first, states: { [states.first]: { - on: {}, + on: {} }, [states.third.deep.wow]: { - states: {}, - }, - }, + states: {} + } + } }); diff --git a/examples/dynamicEverything.ts b/examples/dynamicEverything.ts index 4a578d1..8ca7686 100644 --- a/examples/dynamicEverything.ts +++ b/examples/dynamicEverything.ts @@ -1,28 +1,28 @@ -import { createMachine } from "xstate"; +import { createMachine } from 'xstate'; -const START_STATE = "first"; -const OTHER_STATE = "second"; -const COOL = "cool"; +const START_STATE = 'first'; +const OTHER_STATE = 'second'; +const COOL = 'cool'; const otherStates = { [START_STATE]: {}, awesome: {}, - "nice stuff": {}, + 'nice stuff': {} }; const states = { ...otherStates, [START_STATE]: {}, - ["cool"]: {}, + ['cool']: {}, [OTHER_STATE]: { on: { [COOL]: { - target: START_STATE, - }, - }, - }, + target: START_STATE + } + } + } }; export const machine = createMachine({ - states, + states }); diff --git a/examples/dynamicStateNames.ts b/examples/dynamicStateNames.ts index 3def4a3..1ff6cd7 100644 --- a/examples/dynamicStateNames.ts +++ b/examples/dynamicStateNames.ts @@ -1,10 +1,10 @@ -import { createMachine } from "xstate"; +import { createMachine } from 'xstate'; -const START_STATE = "first"; +const START_STATE = 'first'; export const machine = createMachine({ initial: START_STATE, states: { - [START_STATE]: {}, - }, + [START_STATE]: {} + } }); diff --git a/examples/fetchMachine.ts b/examples/fetchMachine.ts index bd0b157..5bb26e5 100644 --- a/examples/fetchMachine.ts +++ b/examples/fetchMachine.ts @@ -9,37 +9,37 @@ // - actions // - XState (all XState exports) -import { assign, Machine } from "xstate"; +import { assign, Machine } from 'xstate'; export const fetchMachine = Machine({ - id: "fetch", - initial: "idle", + id: 'fetch', + initial: 'idle', context: { - retries: 0, + retries: 0 }, states: { idle: { on: { FETCH: { - target: "loading", - }, - }, + target: 'loading' + } + } }, loading: { on: { - RESOLVE: { target: "success" }, - REJECT: { target: "failure" }, - }, + RESOLVE: { target: 'success' }, + REJECT: { target: 'failure' } + } }, success: { - type: "final", + type: 'final' }, failure: { on: { RETRY: { - target: "loading", - }, - }, - }, - }, + target: 'loading' + } + } + } + } }); diff --git a/examples/fetchMachineInFunction.ts b/examples/fetchMachineInFunction.ts index fb8f2da..259a1ff 100644 --- a/examples/fetchMachineInFunction.ts +++ b/examples/fetchMachineInFunction.ts @@ -9,41 +9,41 @@ // - actions // - XState (all XState exports) -import { assign, Machine } from "xstate"; +import { assign, Machine } from 'xstate'; const makeFetchMachine = () => Machine({ - id: "fetch", - initial: "idle", + id: 'fetch', + initial: 'idle', context: { - retries: 0, + retries: 0 }, - type: "atomic", + type: 'atomic', states: { idle: { on: { FETCH: { - target: "loading", - }, - }, + target: 'loading' + } + } }, loading: { on: { - RESOLVE: { target: "success" }, - REJECT: { target: "failure" }, - }, + RESOLVE: { target: 'success' }, + REJECT: { target: 'failure' } + } }, success: { - type: "final", + type: 'final' }, failure: { on: { RETRY: { - target: "loading", - }, - }, - }, - }, + target: 'loading' + } + } + } + } }); export const fetchMachine = makeFetchMachine(); diff --git a/examples/form-input.machine.ts b/examples/form-input.machine.ts index 7c713fa..89bb5b5 100644 --- a/examples/form-input.machine.ts +++ b/examples/form-input.machine.ts @@ -1,4 +1,4 @@ -import { assign, createMachine, Sender } from "xstate"; +import { assign, createMachine, Sender } from 'xstate'; export interface FormInputMachineContext { value: Value; @@ -9,23 +9,23 @@ type Value = any; export type FormInputMachineEvent = | { - type: "CHANGE"; + type: 'CHANGE'; value: Value; } | { - type: "BLUR"; + type: 'BLUR'; } | { - type: "FOCUS"; + type: 'FOCUS'; } | { - type: "DISABLE"; + type: 'DISABLE'; } | { - type: "ENABLE"; + type: 'ENABLE'; } | { - type: "REPORT_INVALID"; + type: 'REPORT_INVALID'; reason: string; }; @@ -34,90 +34,90 @@ const formInputMachine = createMachine< FormInputMachineEvent >( { - id: "formInput", - initial: "active", + id: 'formInput', + initial: 'active', states: { active: { on: { - DISABLE: { target: "disabled" }, + DISABLE: { target: 'disabled' } }, - type: "parallel", + type: 'parallel', states: { focus: { - initial: "unfocused", + initial: 'unfocused', states: { focused: { on: { - BLUR: { target: "unfocused" }, - }, + BLUR: { target: 'unfocused' } + } }, unfocused: { on: { - FOCUS: { target: "focused" }, - }, - }, - }, + FOCUS: { target: 'focused' } + } + } + } }, validation: { - initial: "pending", + initial: 'pending', on: { CHANGE: { - target: ".pending", - actions: "assignValueToContext", - }, + target: '.pending', + actions: 'assignValueToContext' + } }, states: { pending: { on: { REPORT_INVALID: { - target: "invalid", - actions: "assignReasonToErrorMessage", - }, + target: 'invalid', + actions: 'assignReasonToErrorMessage' + } }, invoke: { - src: "validateField", - onDone: { target: "valid" }, - }, + src: 'validateField', + onDone: { target: 'valid' } + } }, valid: {}, - invalid: {}, - }, - }, - }, + invalid: {} + } + } + } }, disabled: { on: { - ENABLE: { target: "active" }, - }, - }, - }, + ENABLE: { target: 'active' } + } + } + } }, { actions: { assignReasonToErrorMessage: assign((context, event) => { - if (event.type !== "REPORT_INVALID") return {}; + if (event.type !== 'REPORT_INVALID') return {}; return { - errorMessage: event.reason, + errorMessage: event.reason }; }), assignValueToContext: assign((context, event) => { - if (event.type !== "CHANGE") return {}; + if (event.type !== 'CHANGE') return {}; return { - value: event.value, + value: event.value }; - }), + }) }, services: { validateField: (context) => (send: Sender) => { - if (context.value === "") { + if (context.value === '') { send({ - type: "REPORT_INVALID", - reason: "Value cannot be empty", + type: 'REPORT_INVALID', + reason: 'Value cannot be empty' }); } - }, - }, - }, + } + } + } ); export default formInputMachine; diff --git a/examples/fromIdentifier.ts b/examples/fromIdentifier.ts index 67ab94b..195fe49 100644 --- a/examples/fromIdentifier.ts +++ b/examples/fromIdentifier.ts @@ -1,15 +1,15 @@ -import { createMachine, MachineConfig } from "xstate"; +import { createMachine, MachineConfig } from 'xstate'; const config: MachineConfig = { on: { NEXT: { - target: ".next", - }, + target: '.next' + } }, states: { idle: {}, - next: {}, - }, + next: {} + } }; export const machine = createMachine(config); diff --git a/examples/infinite-scroll.machine.ts b/examples/infinite-scroll.machine.ts index 45fd605..f494c48 100644 --- a/examples/infinite-scroll.machine.ts +++ b/examples/infinite-scroll.machine.ts @@ -1,4 +1,4 @@ -import { assign, createMachine, Sender } from "xstate"; +import { assign, createMachine, Sender } from 'xstate'; export interface InfiniteScrollMachineContext { data: Data[]; @@ -12,10 +12,10 @@ interface Data { export type InfiniteScrollMachineEvent = | { - type: "SCROLL_TO_BOTTOM"; + type: 'SCROLL_TO_BOTTOM'; } | { - type: "RECEIVED_DATA"; + type: 'RECEIVED_DATA'; data: Data[]; totalEntries: number; }; @@ -25,77 +25,77 @@ const infiniteScrollMachine = createMachine< InfiniteScrollMachineEvent >( { - id: "infiniteScroll", - initial: "fetchingRowOfData", + id: 'infiniteScroll', + initial: 'fetchingRowOfData', context: { totalEntries: Infinity, - data: [], + data: [] }, states: { fetchingRowOfData: { on: { RECEIVED_DATA: { - target: "checkingIfThereIsMoreData", - actions: "assignDataToContext", - }, + target: 'checkingIfThereIsMoreData', + actions: 'assignDataToContext' + } }, invoke: { - src: "fetchRowOfData", + src: 'fetchRowOfData', onError: { - target: "idle", - actions: "assignErrorMessageToContext", - }, - }, + target: 'idle', + actions: 'assignErrorMessageToContext' + } + } }, idle: { - exit: "clearErrorMessage", + exit: 'clearErrorMessage', on: { - SCROLL_TO_BOTTOM: { target: "fetchingRowOfData" }, - }, + SCROLL_TO_BOTTOM: { target: 'fetchingRowOfData' } + } }, checkingIfThereIsMoreData: { always: [ { - cond: "thereIsMoreData", - target: "idle", + cond: 'thereIsMoreData', + target: 'idle' }, { - target: "noMoreDataToFetch", - }, - ], + target: 'noMoreDataToFetch' + } + ] }, noMoreDataToFetch: { - type: "final", - }, - }, + type: 'final' + } + } }, { guards: { thereIsMoreData: (context) => { return context.totalEntries > context.data.length; - }, + } }, services: { - fetchRowOfData: () => (send: Sender) => {}, + fetchRowOfData: () => (send: Sender) => {} }, actions: { assignDataToContext: assign((context, event) => { - if (event.type !== "RECEIVED_DATA") return {}; + if (event.type !== 'RECEIVED_DATA') return {}; return { data: [...context.data, ...event.data], - totalEntries: event.totalEntries, + totalEntries: event.totalEntries }; }), clearErrorMessage: assign((context) => ({ - errorMessage: undefined, + errorMessage: undefined })), assignErrorMessageToContext: assign((context, event: any) => { return { - errorMessage: event.data?.message || "An unknown error occurred", + errorMessage: event.data?.message || 'An unknown error occurred' }; - }), - }, - }, + }) + } + } ); export default infiniteScrollMachine; diff --git a/examples/initial.ts b/examples/initial.ts index 29518e5..56fdf5f 100644 --- a/examples/initial.ts +++ b/examples/initial.ts @@ -1,8 +1,8 @@ -import { createMachine } from "xstate"; +import { createMachine } from 'xstate'; const machine = createMachine({ - initial: "idle", + initial: 'idle', states: { - idle: {}, - }, + idle: {} + } }); diff --git a/examples/jsx.tsx b/examples/jsx.tsx index 1ab938b..1908aaa 100644 --- a/examples/jsx.tsx +++ b/examples/jsx.tsx @@ -1,10 +1,10 @@ -import { createMachine } from "xstate"; +import { createMachine } from 'xstate'; export const machine = createMachine({ - initial: "wow", + initial: 'wow', states: { - wow: {}, - }, + wow: {} + } }); const Component = () => { diff --git a/examples/memberExpression.machine.ts b/examples/memberExpression.machine.ts index 6175d33..69628f4 100644 --- a/examples/memberExpression.machine.ts +++ b/examples/memberExpression.machine.ts @@ -1,12 +1,12 @@ -import * as XState from "xstate"; +import * as XState from 'xstate'; const deep = { - XState, + XState }; export const machine = deep.XState.createMachine({ - initial: "idle", + initial: 'idle', states: { - idle: {}, - }, + idle: {} + } }); diff --git a/examples/multi-step-form-with-validation.machine.ts b/examples/multi-step-form-with-validation.machine.ts index 1b9d882..8b16cd5 100644 --- a/examples/multi-step-form-with-validation.machine.ts +++ b/examples/multi-step-form-with-validation.machine.ts @@ -1,4 +1,4 @@ -import { assign, createMachine } from "xstate"; +import { assign, createMachine } from 'xstate'; export interface MultiStepFormMachineContext { beneficiaryInfo?: BeneficiaryInfo; @@ -18,18 +18,18 @@ interface DateInfo { export type MultiStepFormMachineEvent = | { - type: "BACK"; + type: 'BACK'; } | { - type: "CONFIRM_BENEFICIARY"; + type: 'CONFIRM_BENEFICIARY'; info: BeneficiaryInfo; } | { - type: "CONFIRM_DATE"; + type: 'CONFIRM_DATE'; info: DateInfo; } | { - type: "CONFIRM"; + type: 'CONFIRM'; }; const multiStepFormMachine = createMachine< @@ -37,133 +37,133 @@ const multiStepFormMachine = createMachine< MultiStepFormMachineEvent >( { - id: "multiStepForm", - initial: "enteringBeneficiary", + id: 'multiStepForm', + initial: 'enteringBeneficiary', states: { enteringBeneficiary: { - initial: "idle", - id: "enteringBeneficiary", + initial: 'idle', + id: 'enteringBeneficiary', onDone: { - target: "enteringDate", + target: 'enteringDate' }, states: { idle: { - exit: "clearErrorMessage", + exit: 'clearErrorMessage', on: { CONFIRM_BENEFICIARY: { - target: "submitting", - actions: "assignBeneficiaryInfoToContext", - }, - }, + target: 'submitting', + actions: 'assignBeneficiaryInfoToContext' + } + } }, submitting: { invoke: { - src: "validateBeneficiary", + src: 'validateBeneficiary', onDone: { - target: "complete", + target: 'complete' }, onError: { - target: "idle", - actions: "assignErrorMessageToContext", - }, - }, + target: 'idle', + actions: 'assignErrorMessageToContext' + } + } }, - complete: { type: "final" }, - }, + complete: { type: 'final' } + } }, enteringDate: { - id: "enteringDate", + id: 'enteringDate', onDone: { - target: "confirming", + target: 'confirming' }, - initial: "idle", + initial: 'idle', states: { idle: { - exit: "clearErrorMessage", + exit: 'clearErrorMessage', on: { CONFIRM_DATE: { - target: "submitting", - actions: "assignDateToContext", + target: 'submitting', + actions: 'assignDateToContext' }, BACK: { - target: "#enteringBeneficiary", - }, - }, + target: '#enteringBeneficiary' + } + } }, submitting: { invoke: { - src: "validateDate", + src: 'validateDate', onDone: { - target: "complete", + target: 'complete' }, onError: { - target: "idle", - actions: "assignErrorMessageToContext", - }, - }, + target: 'idle', + actions: 'assignErrorMessageToContext' + } + } }, - complete: { type: "final" }, - }, + complete: { type: 'final' } + } }, confirming: { onDone: { - target: "success", + target: 'success' }, - initial: "idle", + initial: 'idle', states: { idle: { - exit: "clearErrorMessage", + exit: 'clearErrorMessage', on: { - CONFIRM: { target: "submitting" }, + CONFIRM: { target: 'submitting' }, BACK: { - target: "#enteringDate", - }, - }, + target: '#enteringDate' + } + } }, submitting: { invoke: { - src: "submitPayment", + src: 'submitPayment', onDone: { - target: "complete", + target: 'complete' }, onError: { - target: "idle", - actions: "assignErrorMessageToContext", - }, - }, + target: 'idle', + actions: 'assignErrorMessageToContext' + } + } }, - complete: { type: "final" }, - }, + complete: { type: 'final' } + } }, success: { - type: "final", - }, - }, + type: 'final' + } + } }, { actions: { assignDateToContext: assign((context, event) => { - if (event.type !== "CONFIRM_DATE") return {}; + if (event.type !== 'CONFIRM_DATE') return {}; return { - dateInfo: event.info, + dateInfo: event.info }; }), clearErrorMessage: assign((context) => ({ - errorMessage: undefined, + errorMessage: undefined })), assignBeneficiaryInfoToContext: assign((context, event) => { - if (event.type !== "CONFIRM_BENEFICIARY") return {}; + if (event.type !== 'CONFIRM_BENEFICIARY') return {}; return { - beneficiaryInfo: event.info, + beneficiaryInfo: event.info }; }), assignErrorMessageToContext: assign((context, event: any) => { return { - errorMessage: event.data?.message || "An unknown error occurred", + errorMessage: event.data?.message || 'An unknown error occurred' }; - }), - }, - }, + }) + } + } ); export default multiStepFormMachine; diff --git a/examples/multi-step-form.machine.ts b/examples/multi-step-form.machine.ts index 77b6b47..45774ec 100644 --- a/examples/multi-step-form.machine.ts +++ b/examples/multi-step-form.machine.ts @@ -1,4 +1,4 @@ -import { assign, createMachine } from "xstate"; +import { assign, createMachine } from 'xstate'; export interface MultiStepFormMachineContext { beneficiaryInfo?: BeneficiaryInfo; @@ -18,18 +18,18 @@ interface DateInfo { export type MultiStepFormMachineEvent = | { - type: "BACK"; + type: 'BACK'; } | { - type: "CONFIRM_BENEFICIARY"; + type: 'CONFIRM_BENEFICIARY'; info: BeneficiaryInfo; } | { - type: "CONFIRM_DATE"; + type: 'CONFIRM_DATE'; info: DateInfo; } | { - type: "CONFIRM"; + type: 'CONFIRM'; }; const multiStepFormMachine = createMachine< @@ -37,89 +37,89 @@ const multiStepFormMachine = createMachine< MultiStepFormMachineEvent >( { - id: "multiStepFormWithValidation", - initial: "enteringBeneficiary", + id: 'multiStepFormWithValidation', + initial: 'enteringBeneficiary', states: { enteringBeneficiary: { on: { CONFIRM_BENEFICIARY: { - target: "enteringDate", - actions: "assignBeneficiaryInfoToContext", - }, - }, + target: 'enteringDate', + actions: 'assignBeneficiaryInfoToContext' + } + } }, enteringDate: { - id: "enteringDate", + id: 'enteringDate', on: { BACK: { - target: "enteringBeneficiary", + target: 'enteringBeneficiary' }, CONFIRM_DATE: { - target: "confirming", - actions: "assignDateToContext", - }, - }, + target: 'confirming', + actions: 'assignDateToContext' + } + } }, confirming: { onDone: { - target: "success", + target: 'success' }, - initial: "idle", + initial: 'idle', states: { idle: { - exit: "clearErrorMessage", + exit: 'clearErrorMessage', on: { - CONFIRM: { target: "submitting" }, + CONFIRM: { target: 'submitting' }, BACK: { - target: "#enteringDate", - }, - }, + target: '#enteringDate' + } + } }, submitting: { invoke: { - src: "submitPayment", + src: 'submitPayment', onDone: { - target: "complete", + target: 'complete' }, onError: { - target: "idle", - actions: "assignErrorMessageToContext", - }, - }, + target: 'idle', + actions: 'assignErrorMessageToContext' + } + } }, - complete: { type: "final" }, - }, + complete: { type: 'final' } + } }, success: { - type: "final", - }, - }, + type: 'final' + } + } }, { services: { submitPayment: () => () => {} }, actions: { assignDateToContext: assign((context, event) => { - if (event.type !== "CONFIRM_DATE") return {}; + if (event.type !== 'CONFIRM_DATE') return {}; return { - dateInfo: event.info, + dateInfo: event.info }; }), assignBeneficiaryInfoToContext: assign((context, event) => { - if (event.type !== "CONFIRM_BENEFICIARY") return {}; + if (event.type !== 'CONFIRM_BENEFICIARY') return {}; return { - beneficiaryInfo: event.info, + beneficiaryInfo: event.info }; }), assignErrorMessageToContext: assign((context, event: any) => { return { - errorMessage: event.data?.message || "An unknown error occurred", + errorMessage: event.data?.message || 'An unknown error occurred' }; }), clearErrorMessage: assign((context) => ({ - errorMessage: undefined, - })), - }, - }, + errorMessage: undefined + })) + } + } ); export default multiStepFormMachine; diff --git a/examples/multi-step-timer.machine.ts b/examples/multi-step-timer.machine.ts index 0aa8602..7f9b1e4 100644 --- a/examples/multi-step-timer.machine.ts +++ b/examples/multi-step-timer.machine.ts @@ -1,41 +1,41 @@ -import { createMachine } from "xstate"; +import { createMachine } from 'xstate'; export type MultiStepTimerMachineContext = {}; export type MultiStepTimerMachineEvent = { - type: "BEGIN"; + type: 'BEGIN'; }; const multiStepTimerMachine = createMachine< MultiStepTimerMachineContext, MultiStepTimerMachineEvent >({ - id: "multiStepTimer", - initial: "idle", + id: 'multiStepTimer', + initial: 'idle', states: { idle: { on: { BEGIN: { - target: "firstStep", - }, - }, + target: 'firstStep' + } + } }, firstStep: { after: { - 3000: { target: "secondStep" }, - }, + 3000: { target: 'secondStep' } + } }, secondStep: { after: { - 3000: { target: "thirdStep" }, - }, + 3000: { target: 'thirdStep' } + } }, thirdStep: { after: { - 3000: { target: "idle" }, - }, - }, - }, + 3000: { target: 'idle' } + } + } + } }); export default multiStepTimerMachine; diff --git a/examples/netflix-style-video-hover.machine.ts b/examples/netflix-style-video-hover.machine.ts index 3c1d213..3e4b3dc 100644 --- a/examples/netflix-style-video-hover.machine.ts +++ b/examples/netflix-style-video-hover.machine.ts @@ -1,4 +1,4 @@ -import { assign, createMachine } from "xstate"; +import { assign, createMachine } from 'xstate'; export interface NetflixStyleVideoHoverMachineContext { hasVideoLoaded: boolean; @@ -6,19 +6,19 @@ export interface NetflixStyleVideoHoverMachineContext { export type NetflixStyleVideoHoverMachineEvent = | { - type: "REPORT_IMAGE_LOADED"; + type: 'REPORT_IMAGE_LOADED'; } | { - type: "REPORT_IMAGE_FAILED_TO_LOAD"; + type: 'REPORT_IMAGE_FAILED_TO_LOAD'; } | { - type: "MOUSE_OVER"; + type: 'MOUSE_OVER'; } | { - type: "REPORT_VIDEO_LOADED"; + type: 'REPORT_VIDEO_LOADED'; } | { - type: "MOUSE_OUT"; + type: 'MOUSE_OUT'; }; const netflixStyleVideoHoverMachine = createMachine< @@ -26,108 +26,108 @@ const netflixStyleVideoHoverMachine = createMachine< NetflixStyleVideoHoverMachineEvent >( { - id: "netflixStyleVideoHover", - initial: "awaitingBackgroundImageLoad", + id: 'netflixStyleVideoHover', + initial: 'awaitingBackgroundImageLoad', context: { - hasVideoLoaded: false, + hasVideoLoaded: false }, states: { awaitingBackgroundImageLoad: { on: { REPORT_IMAGE_LOADED: { - target: "idle", + target: 'idle' }, REPORT_IMAGE_FAILED_TO_LOAD: { - target: "imageFailedToLoad", - }, - }, + target: 'imageFailedToLoad' + } + } }, imageFailedToLoad: {}, idle: { on: { MOUSE_OVER: { - target: "showingVideo", - }, - }, + target: 'showingVideo' + } + } }, showingVideo: { - initial: "checkingIfVideoHasLoaded", + initial: 'checkingIfVideoHasLoaded', on: { MOUSE_OUT: { - target: "idle", - }, + target: 'idle' + } }, states: { checkingIfVideoHasLoaded: { always: [ { - cond: "hasLoadedVideo", - target: "waitingBeforePlaying", + cond: 'hasLoadedVideo', + target: 'waitingBeforePlaying' }, { - target: "loadingVideoSrc", - }, - ], + target: 'loadingVideoSrc' + } + ] }, waitingBeforePlaying: { after: { 2000: { - target: "autoPlayingVideo", - }, - }, + target: 'autoPlayingVideo' + } + } }, loadingVideoSrc: { - initial: "cannotMoveOn", + initial: 'cannotMoveOn', onDone: { - target: "autoPlayingVideo", + target: 'autoPlayingVideo' }, states: { cannotMoveOn: { after: { 2000: { - target: "canMoveOn", - }, + target: 'canMoveOn' + } }, on: { REPORT_VIDEO_LOADED: { - actions: "reportVideoLoaded", - }, - }, + actions: 'reportVideoLoaded' + } + } }, canMoveOn: { always: { - cond: "hasLoadedVideo", - target: "loaded", + cond: 'hasLoadedVideo', + target: 'loaded' }, on: { REPORT_VIDEO_LOADED: { - actions: "reportVideoLoaded", - target: "loaded", - }, - }, + actions: 'reportVideoLoaded', + target: 'loaded' + } + } }, loaded: { - type: "final", - }, - }, + type: 'final' + } + } }, - autoPlayingVideo: {}, - }, - }, - }, + autoPlayingVideo: {} + } + } + } }, { guards: { hasLoadedVideo: (context) => { return context.hasVideoLoaded; - }, + } }, actions: { reportVideoLoaded: assign((context) => ({ - hasVideoLoaded: true, - })), - }, - }, + hasVideoLoaded: true + })) + } + } ); export default netflixStyleVideoHoverMachine; diff --git a/examples/pagination.machine.ts b/examples/pagination.machine.ts index 45c7425..f4030d5 100644 --- a/examples/pagination.machine.ts +++ b/examples/pagination.machine.ts @@ -1,5 +1,5 @@ -import { assign, createMachine } from "xstate"; -import { choose } from "xstate/lib/actions"; +import { assign, createMachine } from 'xstate'; +import { choose } from 'xstate/lib/actions'; export interface PaginationMachineContext { totalPages?: number; @@ -11,17 +11,17 @@ export interface PaginationMachineContext { export type PaginationMachineEvent = | { - type: "UPDATE_TOTAL_PAGES"; + type: 'UPDATE_TOTAL_PAGES'; totalPages: number; } | { - type: "NEXT_PAGE"; + type: 'NEXT_PAGE'; } | { - type: "PREV_PAGE"; + type: 'PREV_PAGE'; } | { - type: "GO_TO_TARGET_PAGE"; + type: 'GO_TO_TARGET_PAGE'; targetPage: number; }; @@ -30,55 +30,55 @@ const paginationMachine = createMachine< PaginationMachineEvent >( { - id: "pagination", - initial: "awaitingTotalPages", + id: 'pagination', + initial: 'awaitingTotalPages', context: { - currentPage: 1, + currentPage: 1 }, on: { UPDATE_TOTAL_PAGES: { - cond: "newTotalPagesIsValidValue", + cond: 'newTotalPagesIsValidValue', actions: choose([ { - actions: ["assignTotalPagesToContext", "goToFirstPage"], - cond: "currentPageIsAboveNewTotalPages", + actions: ['assignTotalPagesToContext', 'goToFirstPage'], + cond: 'currentPageIsAboveNewTotalPages' }, { - actions: "assignTotalPagesToContext", - }, + actions: 'assignTotalPagesToContext' + } ]), - target: "idle", - }, + target: 'idle' + } }, states: { awaitingTotalPages: {}, idle: { on: { NEXT_PAGE: { - cond: "canGoToNextPage", - actions: "goToNextPage", + cond: 'canGoToNextPage', + actions: 'goToNextPage' }, PREV_PAGE: { - cond: "canGoToPrevPage", - actions: "goToPrevPage", + cond: 'canGoToPrevPage', + actions: 'goToPrevPage' }, GO_TO_TARGET_PAGE: { - actions: "goToTargetPage", - cond: "targetPageIsWithinBounds", - }, - }, - }, - }, + actions: 'goToTargetPage', + cond: 'targetPageIsWithinBounds' + } + } + } + } }, { guards: { newTotalPagesIsValidValue: (context, event) => { - if (event.type !== "UPDATE_TOTAL_PAGES") return false; + if (event.type !== 'UPDATE_TOTAL_PAGES') return false; return event.totalPages > 0; }, currentPageIsAboveNewTotalPages: (context, event) => { - if (event.type !== "UPDATE_TOTAL_PAGES") return false; + if (event.type !== 'UPDATE_TOTAL_PAGES') return false; return context.currentPage > event.totalPages; }, @@ -89,37 +89,37 @@ const paginationMachine = createMachine< return context.currentPage > 1; }, targetPageIsWithinBounds: (context, event) => { - if (event.type !== "GO_TO_TARGET_PAGE") return false; + if (event.type !== 'GO_TO_TARGET_PAGE') return false; return ( event.targetPage >= 1 && event.targetPage <= (context.totalPages || 0) ); - }, + } }, actions: { goToFirstPage: assign({ - currentPage: 1, + currentPage: 1 }), goToPrevPage: assign({ - currentPage: (context) => context.currentPage - 1, + currentPage: (context) => context.currentPage - 1 }), goToNextPage: assign({ - currentPage: (context) => context.currentPage + 1, + currentPage: (context) => context.currentPage + 1 }), goToTargetPage: assign((context, event) => { - if (event.type !== "GO_TO_TARGET_PAGE") return {}; + if (event.type !== 'GO_TO_TARGET_PAGE') return {}; return { - currentPage: event.targetPage, + currentPage: event.targetPage }; }), assignTotalPagesToContext: assign((context, event) => { - if (event.type !== "UPDATE_TOTAL_PAGES") return {}; + if (event.type !== 'UPDATE_TOTAL_PAGES') return {}; return { - totalPages: event.totalPages, + totalPages: event.totalPages }; - }), - }, - }, + }) + } + } ); export default paginationMachine; diff --git a/examples/queue.machine.ts b/examples/queue.machine.ts index 549325a..b683083 100644 --- a/examples/queue.machine.ts +++ b/examples/queue.machine.ts @@ -1,11 +1,11 @@ -import { assign, createMachine } from "xstate"; +import { assign, createMachine } from 'xstate'; export interface QueueMachineContext { queue: QueueItemWithTime[]; } interface QueueItem { - action: "ALERT_BROWSER_AFTER_PAUSE" | "FAIL_AFTER_PAUSE"; + action: 'ALERT_BROWSER_AFTER_PAUSE' | 'FAIL_AFTER_PAUSE'; } interface QueueItemWithTime extends QueueItem { @@ -14,90 +14,90 @@ interface QueueItemWithTime extends QueueItem { export type QueueMachineEvent = | { - type: "ADD_TO_QUEUE"; + type: 'ADD_TO_QUEUE'; items: QueueItem[]; } | { - type: "RETRY"; + type: 'RETRY'; } | { - type: "CLEAR_QUEUE"; + type: 'CLEAR_QUEUE'; }; const queueMachine = createMachine( { - id: "queue", + id: 'queue', /** * Check initially if we should execute items in the queue */ - initial: "checkingIfThereAreMoreItems", + initial: 'checkingIfThereAreMoreItems', context: { - queue: [], + queue: [] }, on: { CLEAR_QUEUE: { - target: "idle", - actions: "clearQueue", - }, + target: 'idle', + actions: 'clearQueue' + } }, states: { idle: { on: { ADD_TO_QUEUE: { - actions: "addItemToQueue", - target: "executingItem", - }, - }, + actions: 'addItemToQueue', + target: 'executingItem' + } + } }, executingItem: { on: { ADD_TO_QUEUE: { - actions: "addItemToQueue", - }, + actions: 'addItemToQueue' + } }, invoke: { - src: "executeOldestItemInQueue", + src: 'executeOldestItemInQueue', onDone: { - target: "checkingIfThereAreMoreItems", - actions: "removeOldestItemFromQueue", + target: 'checkingIfThereAreMoreItems', + actions: 'removeOldestItemFromQueue' }, onError: { - target: "awaitingRetry", - }, - }, + target: 'awaitingRetry' + } + } }, awaitingRetry: { on: { ADD_TO_QUEUE: { - actions: "addItemToQueue", - target: "executingItem", + actions: 'addItemToQueue', + target: 'executingItem' }, - RETRY: { target: "executingItem" }, - }, + RETRY: { target: 'executingItem' } + } }, checkingIfThereAreMoreItems: { on: { ADD_TO_QUEUE: { - actions: "addItemToQueue", - }, + actions: 'addItemToQueue' + } }, always: [ { - cond: "thereAreMoreItemsInTheQueue", - target: "executingItem", + cond: 'thereAreMoreItemsInTheQueue', + target: 'executingItem' }, { - target: "idle", - }, - ], - }, - }, + target: 'idle' + } + ] + } + } }, { guards: { thereAreMoreItemsInTheQueue: (context) => { return context.queue.length > 0; - }, + } }, services: { executeOldestItemInQueue: async (context) => { @@ -106,42 +106,42 @@ const queueMachine = createMachine( if (!oldestItem) return; switch (oldestItem.action) { - case "ALERT_BROWSER_AFTER_PAUSE": { + case 'ALERT_BROWSER_AFTER_PAUSE': { await wait(2000); - alert("Alert from ALERT_BROWSER_AFTER_PAUSE"); + alert('Alert from ALERT_BROWSER_AFTER_PAUSE'); break; } - case "FAIL_AFTER_PAUSE": { + case 'FAIL_AFTER_PAUSE': { await wait(2000); - throw new Error("Something went wrong!"); + throw new Error('Something went wrong!'); } } - }, + } }, actions: { clearQueue: assign((context) => ({ - queue: [], + queue: [] })), addItemToQueue: assign((context, event) => { - if (event.type !== "ADD_TO_QUEUE") return {}; + if (event.type !== 'ADD_TO_QUEUE') return {}; return { queue: [ ...context.queue, ...(event.items?.map((item) => ({ ...item, - timeAdded: new Date().toISOString(), - })) || []), - ], + timeAdded: new Date().toISOString() + })) || []) + ] }; }), removeOldestItemFromQueue: assign((context) => { const [, ...newQueue] = context.queue; return { - queue: newQueue, + queue: newQueue }; - }), - }, - }, + }) + } + } ); export default queueMachine; diff --git a/examples/simple-data-fetch.machine.ts b/examples/simple-data-fetch.machine.ts index f341e62..9bb4eaa 100644 --- a/examples/simple-data-fetch.machine.ts +++ b/examples/simple-data-fetch.machine.ts @@ -1,4 +1,4 @@ -import { assign, createMachine } from "xstate"; +import { assign, createMachine } from 'xstate'; export interface SimpleDataFetchMachineContext { data?: Data; @@ -15,15 +15,15 @@ interface Data { export type SimpleDataFetchMachineEvent = | { - type: "FETCH"; + type: 'FETCH'; variables: Variables; } | { - type: "RECEIVE_DATA"; + type: 'RECEIVE_DATA'; data: Data; } | { - type: "CANCEL"; + type: 'CANCEL'; }; const simpleDataFetchMachine = createMachine< @@ -31,67 +31,67 @@ const simpleDataFetchMachine = createMachine< SimpleDataFetchMachineEvent >( { - id: "simpleDataFetch", - initial: "idle", + id: 'simpleDataFetch', + initial: 'idle', states: { idle: { on: { FETCH: { - target: "fetching", - }, + target: 'fetching' + } }, - initial: "noError", + initial: 'noError', states: { noError: { - entry: "clearErrorMessage", + entry: 'clearErrorMessage' }, - errored: {}, - }, + errored: {} + } }, fetching: { on: { FETCH: { - target: "fetching", + target: 'fetching' }, CANCEL: { - target: "idle", + target: 'idle' }, RECEIVE_DATA: { - target: "idle", - actions: "assignDataToContext", - }, + target: 'idle', + actions: 'assignDataToContext' + } }, invoke: { - src: "fetchData", + src: 'fetchData', onError: { - target: "idle.errored", - actions: "assignErrorToContext", - }, - }, - }, - }, + target: 'idle.errored', + actions: 'assignErrorToContext' + } + } + } + } }, { services: { - fetchData: () => () => {}, + fetchData: () => () => {} }, actions: { assignDataToContext: assign((context, event) => { - if (event.type !== "RECEIVE_DATA") return {}; + if (event.type !== 'RECEIVE_DATA') return {}; return { - data: event.data, + data: event.data }; }), clearErrorMessage: assign((context) => ({ - errorMessage: undefined, + errorMessage: undefined })), assignErrorToContext: assign((context, event: any) => { return { - errorMessage: event.data?.message || "An unknown error occurred", + errorMessage: event.data?.message || 'An unknown error occurred' }; - }), - }, - }, + }) + } + } ); export default simpleDataFetchMachine; diff --git a/examples/stateStrings.ts b/examples/stateStrings.ts index 710addf..816bf99 100644 --- a/examples/stateStrings.ts +++ b/examples/stateStrings.ts @@ -1,8 +1,8 @@ -import { createMachine } from "xstate"; +import { createMachine } from 'xstate'; export const machine = createMachine({ - initial: "wow awesome", + initial: 'wow awesome', states: { - "wow awesome": {}, - }, + 'wow awesome': {} + } }); diff --git a/examples/tab-focus.machine.ts b/examples/tab-focus.machine.ts index 3301054..c60c281 100644 --- a/examples/tab-focus.machine.ts +++ b/examples/tab-focus.machine.ts @@ -1,13 +1,13 @@ -import { assign, createMachine, Sender } from "xstate"; +import { assign, createMachine, Sender } from 'xstate'; export interface TabFocusMachineContext {} export type TabFocusMachineEvent = | { - type: "REPORT_TAB_BLUR"; + type: 'REPORT_TAB_BLUR'; } | { - type: "REPORT_TAB_FOCUS"; + type: 'REPORT_TAB_FOCUS'; }; const tabFocusMachine = createMachine< @@ -15,53 +15,53 @@ const tabFocusMachine = createMachine< TabFocusMachineEvent >( { - id: "tabFocus", - initial: "userIsOnTab", + id: 'tabFocus', + initial: 'userIsOnTab', states: { userIsOnTab: { invoke: { - src: "checkForDocumentBlur", + src: 'checkForDocumentBlur' }, on: { - REPORT_TAB_BLUR: { target: "userIsNotOnTab" }, - }, + REPORT_TAB_BLUR: { target: 'userIsNotOnTab' } + } }, userIsNotOnTab: { invoke: { - src: "checkForDocumentFocus", + src: 'checkForDocumentFocus' }, on: { - REPORT_TAB_FOCUS: { target: "userIsOnTab" }, - }, - }, - }, + REPORT_TAB_FOCUS: { target: 'userIsOnTab' } + } + } + } }, { services: { checkForDocumentBlur: () => (send: Sender) => { const listener = () => { - send("REPORT_TAB_BLUR"); + send('REPORT_TAB_BLUR'); }; - window.addEventListener("blur", listener); + window.addEventListener('blur', listener); return () => { - window.removeEventListener("blur", listener); + window.removeEventListener('blur', listener); }; }, checkForDocumentFocus: () => (send: Sender) => { const listener = () => { - send("REPORT_TAB_FOCUS"); + send('REPORT_TAB_FOCUS'); }; - window.addEventListener("focus", listener); + window.addEventListener('focus', listener); return () => { - window.removeEventListener("focus", listener); + window.removeEventListener('focus', listener); }; - }, - }, - }, + } + } + } ); export default tabFocusMachine; diff --git a/examples/with-local-cache.machine.ts b/examples/with-local-cache.machine.ts index 959c57a..1670005 100644 --- a/examples/with-local-cache.machine.ts +++ b/examples/with-local-cache.machine.ts @@ -1,4 +1,4 @@ -import { assign, createMachine } from "xstate"; +import { assign, createMachine } from 'xstate'; export interface WithLocalCacheMachineContext { cache: Cache; @@ -18,15 +18,15 @@ interface Data { export type WithLocalCacheMachineEvent = | { - type: "FETCH"; + type: 'FETCH'; variables: Variables; } | { - type: "RECEIVE_DATA"; + type: 'RECEIVE_DATA'; data: Data; } | { - type: "CANCEL"; + type: 'CANCEL'; }; const withLocalCacheMachine = createMachine< @@ -34,101 +34,100 @@ const withLocalCacheMachine = createMachine< WithLocalCacheMachineEvent >( { - id: "simpleDataFetch", - initial: "idle", + id: 'simpleDataFetch', + initial: 'idle', context: { - cache: {}, + cache: {} }, states: { idle: { on: { FETCH: [ { - cond: "itemIsAlreadyInCache", - target: "idle", + cond: 'itemIsAlreadyInCache', + target: 'idle' }, { - target: "fetching", - actions: "assignVariablesToContext", - }, - ], + target: 'fetching', + actions: 'assignVariablesToContext' + } + ] }, - initial: "noError", + initial: 'noError', states: { noError: { - entry: "clearErrorMessage", + entry: 'clearErrorMessage' }, - errored: {}, - }, + errored: {} + } }, fetching: { on: { FETCH: [ { - cond: "itemIsAlreadyInCache", - target: "idle", + cond: 'itemIsAlreadyInCache', + target: 'idle' }, { - target: "fetching", - actions: "assignVariablesToContext", - }, + target: 'fetching', + actions: 'assignVariablesToContext' + } ], CANCEL: { - target: "idle", + target: 'idle' }, RECEIVE_DATA: { - target: "idle", - actions: "assignDataToContext", - }, + target: 'idle', + actions: 'assignDataToContext' + } }, invoke: { - src: "fetchData", + src: 'fetchData', onError: { - target: "idle.errored", - actions: "assignErrorToContext", - }, - }, - }, - }, + target: 'idle.errored', + actions: 'assignErrorToContext' + } + } + } + } }, { guards: { itemIsAlreadyInCache: (context, event) => { - if (event.type !== "FETCH") return false; + if (event.type !== 'FETCH') return false; return Boolean(context.cache[JSON.stringify(event.variables)]); - }, + } }, services: { - fetchData: () => () => {}, + fetchData: () => () => {} }, actions: { assignVariablesToContext: assign((context, event) => { - if (event.type !== "FETCH") return {}; + if (event.type !== 'FETCH') return {}; return { - currentVariablesBeingProcessed: event.variables, + currentVariablesBeingProcessed: event.variables }; }), assignDataToContext: assign((context, event) => { - if (event.type !== "RECEIVE_DATA") return {}; + if (event.type !== 'RECEIVE_DATA') return {}; return { cache: { ...context.cache, - [JSON.stringify(context.currentVariablesBeingProcessed)]: - event.data, - }, + [JSON.stringify(context.currentVariablesBeingProcessed)]: event.data + } }; }), clearErrorMessage: assign((context) => ({ - errorMessage: undefined, + errorMessage: undefined })), assignErrorToContext: assign((context, event: any) => { return { - errorMessage: event.data?.message || "An unknown error occurred", + errorMessage: event.data?.message || 'An unknown error occurred' }; - }), - }, - }, + }) + } + } ); export default withLocalCacheMachine; diff --git a/package.json b/package.json index 4e2ff62..c82a1d7 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "scripts": { "test": "jest src", "build": "tsc", - "prepare": "patch-package && yarn build" + "prepare": "patch-package && yarn build && husky install" }, "dependencies": {}, "peerDependencies": { @@ -29,9 +29,17 @@ "@types/babel__traverse": "^7.14.1", "@types/jest": "^26.0.24", "@types/node": "^16.0.1", + "husky": ">=6", "jest": "^27.0.6", + "lint-staged": ">=10", "patch-package": "^6.4.7", + "prettier": "^2.5.1", "typescript": "^4.3.5", "xstate": "^4.27.0" + }, + "lint-staged": { + "*.{ts,tsx,js,jsx,json,md,mdx}": [ + "prettier --write" + ] } } diff --git a/src/MachineParseResult.ts b/src/MachineParseResult.ts index 5d02632..ed2cbcb 100644 --- a/src/MachineParseResult.ts +++ b/src/MachineParseResult.ts @@ -1,14 +1,14 @@ -import { Action, Condition } from "xstate"; -import * as t from "@babel/types"; -import { TMachineCallExpression } from "./machineCallExpression"; -import { StateNodeReturn } from "./stateNode"; -import { toMachineConfig } from "./toMachineConfig"; -import { StringLiteralNode, Comment } from "./types"; -import { TransitionConfigNode } from "./transitions"; -import { ActionNode, ParsedChooseCondition } from "./actions"; -import type { Scope } from "@babel/traverse"; -import { DeclarationType, INLINE_IMPLEMENTATION_TYPE } from "."; -import { RecordOfArrays } from "./RecordOfArrays"; +import { Action, Condition } from 'xstate'; +import * as t from '@babel/types'; +import { TMachineCallExpression } from './machineCallExpression'; +import { StateNodeReturn } from './stateNode'; +import { toMachineConfig } from './toMachineConfig'; +import { StringLiteralNode, Comment } from './types'; +import { TransitionConfigNode } from './transitions'; +import { ActionNode, ParsedChooseCondition } from './actions'; +import type { Scope } from '@babel/traverse'; +import { DeclarationType, INLINE_IMPLEMENTATION_TYPE } from '.'; +import { RecordOfArrays } from './RecordOfArrays'; export interface MachineParseResultStateNode { path: string[]; @@ -53,12 +53,12 @@ export class MachineParseResult { const getSubNodes = ( definition: StateNodeReturn | undefined, - path: string[], + path: string[] ) => { if (definition) { nodes.push({ ast: definition, - path, + path }); } @@ -75,7 +75,7 @@ export class MachineParseResult { getIsIgnored = () => { if (!this.ast?.callee?.loc) return false; const isIgnored = this.fileComments.some((comment) => { - if (comment.type !== "xstate-ignore-next-line") return false; + if (comment.type !== 'xstate-ignore-next-line') return false; return comment.node.loc.end.line === this.ast!.callee.loc!.start.line - 1; }); @@ -91,14 +91,14 @@ export class MachineParseResult { getLayoutComment = (): { value: string; comment: Comment } | undefined => { if (!this.ast?.callee?.loc) return undefined; const layoutComment = this.fileComments.find((comment) => { - if (comment.type !== "xstate-layout") return false; + if (comment.type !== 'xstate-layout') return false; return comment.node.loc.end.line === this.ast!.callee.loc!.start.line - 1; }); if (!layoutComment) return undefined; - const comment = layoutComment?.node.value || ""; + const comment = layoutComment?.node.value || ''; const value = getLayoutString(comment); @@ -115,7 +115,7 @@ export class MachineParseResult { on.result.forEach((transition) => { targets.push({ config: transition, - fromPath: stateNode.path, + fromPath: stateNode.path }); }); }); @@ -123,34 +123,34 @@ export class MachineParseResult { after.result.forEach((transition) => { targets.push({ config: transition, - fromPath: stateNode.path, + fromPath: stateNode.path }); }); }); stateNode.ast.onDone?.forEach((transition) => { targets.push({ config: transition, - fromPath: stateNode.path, + fromPath: stateNode.path }); }); stateNode.ast.invoke?.forEach((invoke) => { invoke.onDone?.forEach((transition) => { targets.push({ config: transition, - fromPath: stateNode.path, + fromPath: stateNode.path }); }); invoke.onError?.forEach((transition) => { targets.push({ config: transition, - fromPath: stateNode.path, + fromPath: stateNode.path }); }); }); stateNode.ast.always?.forEach((transition) => { targets.push({ config: transition, - fromPath: stateNode.path, + fromPath: stateNode.path }); }); }); @@ -162,7 +162,7 @@ export class MachineParseResult { return this.getTransitions() .map((transition) => ({ target: transition.config?.target, - fromPath: transition.fromPath, + fromPath: transition.fromPath })) .filter((transition) => Boolean(transition.target)) as { fromPath: string[]; @@ -172,7 +172,7 @@ export class MachineParseResult { getStateNodeByPath = (path: string[]) => { return this.stateNodes.find((node) => { - return node.path.join("") === path.join(""); + return node.path.join('') === path.join(''); }); }; @@ -184,11 +184,11 @@ export class MachineParseResult { getAllConds = ( declarationTypes: DeclarationType[] = [ - "identifier", - "inline", - "unknown", - "named", - ], + 'identifier', + 'inline', + 'unknown', + 'named' + ] ) => { const conds: { node: t.Node; @@ -206,7 +206,7 @@ export class MachineParseResult { name: transition.config.cond.name, node: transition.config.cond.node, cond: transition.config.cond.cond, - statePath: transition.fromPath, + statePath: transition.fromPath }); } }); @@ -216,14 +216,14 @@ export class MachineParseResult { if ( chooseCondition.conditionNode?.declarationType && declarationTypes.includes( - chooseCondition.conditionNode?.declarationType, + chooseCondition.conditionNode?.declarationType ) ) { conds.push({ name: chooseCondition.conditionNode.name, node: chooseCondition.conditionNode.node, cond: chooseCondition.conditionNode.cond, - statePath: action.statePath, + statePath: action.statePath }); } }); @@ -241,7 +241,7 @@ export class MachineParseResult { const addAction = (action: ActionNode, statePath: string[]) => { actions.push({ node: action, - statePath, + statePath }); action.chooseConditions?.forEach((chooseCondition) => { @@ -253,7 +253,7 @@ export class MachineParseResult { this.getTransitions().forEach((transition) => { transition.config?.actions?.forEach((action) => - addAction(action, transition.fromPath), + addAction(action, transition.fromPath) ); }); @@ -277,11 +277,11 @@ export class MachineParseResult { getAllActions = ( declarationTypes: DeclarationType[] = [ - "identifier", - "inline", - "unknown", - "named", - ], + 'identifier', + 'inline', + 'unknown', + 'named' + ] ) => { const actions: { node: t.Node; @@ -298,7 +298,7 @@ export class MachineParseResult { node: action.node, action: action.action, statePath, - chooseConditions: action.chooseConditions, + chooseConditions: action.chooseConditions }); } }; @@ -312,11 +312,11 @@ export class MachineParseResult { getAllServices = ( declarationTypes: DeclarationType[] = [ - "identifier", - "inline", - "unknown", - "named", - ], + 'identifier', + 'inline', + 'unknown', + 'named' + ] ) => { const services: { node: t.Node; @@ -329,7 +329,7 @@ export class MachineParseResult { this.stateNodes.map((stateNode) => { stateNode.ast.invoke?.forEach((invoke) => { const invokeSrc = - typeof invoke.src?.value === "string" ? invoke.src.value : undefined; + typeof invoke.src?.value === 'string' ? invoke.src.value : undefined; if ( invoke.src?.declarationType && declarationTypes.includes(invoke.src?.declarationType) @@ -339,7 +339,7 @@ export class MachineParseResult { id: invoke.id?.value, node: invoke.node, statePath: stateNode.path, - srcNode: invoke.src?.node, + srcNode: invoke.src?.node }); } }); @@ -363,7 +363,7 @@ export class MachineParseResult { delays.add(key, { node: property.keyNode, name: key, - statePath: stateNode.path, + statePath: stateNode.path }); } }); diff --git a/src/__tests__/after.test.ts b/src/__tests__/after.test.ts index 6de6139..6a5fd3d 100644 --- a/src/__tests__/after.test.ts +++ b/src/__tests__/after.test.ts @@ -1,7 +1,7 @@ -import { parseMachinesFromFile } from ".."; +import { parseMachinesFromFile } from '..'; -describe("After parsing", () => { - it("Should be able to grab actions and guards declared inside a delay", () => { +describe('After parsing', () => { + it('Should be able to grab actions and guards declared inside a delay', () => { const result = parseMachinesFromFile(` createMachine({ after: { @@ -13,7 +13,7 @@ describe("After parsing", () => { `); expect( - Object.keys(result.machines[0].getAllActions(["named"])), + Object.keys(result.machines[0].getAllActions(['named'])) ).toHaveLength(2); }); }); diff --git a/src/__tests__/choose.test.ts b/src/__tests__/choose.test.ts index d4dc2b2..1550e72 100644 --- a/src/__tests__/choose.test.ts +++ b/src/__tests__/choose.test.ts @@ -1,7 +1,7 @@ -import { groupByUniqueName, parseMachinesFromFile } from ".."; +import { groupByUniqueName, parseMachinesFromFile } from '..'; -describe("Choose parsing", () => { - it("Should be able to grab actions and guardsdeclared inside a choose action", () => { +describe('Choose parsing', () => { + it('Should be able to grab actions and guardsdeclared inside a choose action', () => { const result = parseMachinesFromFile(` createMachine({ entry: [ @@ -20,13 +20,13 @@ describe("Choose parsing", () => { `); expect( - Object.keys(groupByUniqueName(result.machines[0].getAllConds(["named"]))), + Object.keys(groupByUniqueName(result.machines[0].getAllConds(['named']))) ).toHaveLength(2); expect( Object.keys( - groupByUniqueName(result.machines[0].getAllActions(["named"])), - ), + groupByUniqueName(result.machines[0].getAllActions(['named'])) + ) ).toHaveLength(4); }); }); diff --git a/src/__tests__/delays.test.ts b/src/__tests__/delays.test.ts index 8bc2207..b2e7e81 100644 --- a/src/__tests__/delays.test.ts +++ b/src/__tests__/delays.test.ts @@ -1,7 +1,7 @@ -import { parseMachinesFromFile } from "../parseMachinesFromFile"; +import { parseMachinesFromFile } from '../parseMachinesFromFile'; -describe("Delays", () => { - it("Should pick up delays in options", () => { +describe('Delays', () => { + it('Should pick up delays in options', () => { const machines = parseMachinesFromFile(` createMachine({}, { delays: { @@ -15,12 +15,12 @@ describe("Delays", () => { const result = machines.machines[0]; const propertyKeys = result.ast?.options?.delays?.properties.map( - (val) => val.key, + (val) => val.key ); - expect(propertyKeys).toEqual(["SOME_NAME", "SOMETHING_ELSE", "WOW"]); + expect(propertyKeys).toEqual(['SOME_NAME', 'SOMETHING_ELSE', 'WOW']); }); - it("Should be able to grab all named delays", () => { + it('Should be able to grab all named delays', () => { const machines = parseMachinesFromFile(` createMachine({ after: { @@ -34,9 +34,9 @@ describe("Delays", () => { const result = machines.machines[0]; expect(Object.keys(result.getAllNamedDelays())).toEqual([ - "SOME_NAME", - "SOMETHING_ELSE", - "WOW", + 'SOME_NAME', + 'SOMETHING_ELSE', + 'WOW' ]); }); }); diff --git a/src/__tests__/enums.test.ts b/src/__tests__/enums.test.ts index de4800b..6c153f0 100644 --- a/src/__tests__/enums.test.ts +++ b/src/__tests__/enums.test.ts @@ -1,7 +1,7 @@ -import { parseMachinesFromFile } from ".."; +import { parseMachinesFromFile } from '..'; -describe("Enums", () => { - it("Should pick up state keys declared as enums and initials", () => { +describe('Enums', () => { + it('Should pick up state keys declared as enums and initials', () => { const result = parseMachinesFromFile(` enum MyEnum { First @@ -16,16 +16,16 @@ describe("Enums", () => { `); expect(result.machines[0].toConfig()).toEqual({ - initial: "0", + initial: '0', states: { - 0: {}, - }, + 0: {} + } }); }); }); -describe("Member expressions", () => { - it("Should pick up state keys declared as member expressions", () => { +describe('Member expressions', () => { + it('Should pick up state keys declared as member expressions', () => { const result = parseMachinesFromFile(` const states = { FIRST: 'first' @@ -40,10 +40,10 @@ describe("Member expressions", () => { `); expect(result.machines[0].toConfig()).toEqual({ - initial: "first", + initial: 'first', states: { - first: {}, - }, + first: {} + } }); }); }); diff --git a/src/__tests__/examples.test.ts b/src/__tests__/examples.test.ts index 4f537c1..cb3fb99 100644 --- a/src/__tests__/examples.test.ts +++ b/src/__tests__/examples.test.ts @@ -1,22 +1,22 @@ -import fs from "fs"; -import path from "path"; -import { StateMachine } from "xstate"; -import { parseMachinesFromFile } from "../parseMachinesFromFile"; -import { testUtils } from "../testUtils"; +import fs from 'fs'; +import path from 'path'; +import { StateMachine } from 'xstate'; +import { parseMachinesFromFile } from '../parseMachinesFromFile'; +import { testUtils } from '../testUtils'; -const examples = fs.readdirSync(path.resolve(__dirname, "../../examples")); +const examples = fs.readdirSync(path.resolve(__dirname, '../../examples')); -describe("Examples", () => { +describe('Examples', () => { examples.forEach((example) => { test(example, async () => { const exampleMachineImports = require(`../../examples/${example}`); const exampleMachines: StateMachine[] = Object.values( - exampleMachineImports, + exampleMachineImports ); const fileAsString = fs - .readFileSync(path.resolve(__dirname, "../../examples", example)) + .readFileSync(path.resolve(__dirname, '../../examples', example)) .toString(); const { machines } = parseMachinesFromFile(fileAsString); @@ -24,14 +24,14 @@ describe("Examples", () => { exampleMachines.forEach((machine, index) => { try { const sourceMachineConfig = testUtils.withoutContext( - machine.config as any, + machine.config as any ); const machineConfigUnderTest = machines[index].toConfig(); expect(machineConfigUnderTest).toEqual(sourceMachineConfig); } catch (e: any) { - if (!e.message.includes("Received: serializes to the same string")) { + if (!e.message.includes('Received: serializes to the same string')) { throw e; } } diff --git a/src/__tests__/ignore.test.ts b/src/__tests__/ignore.test.ts index 1a77769..caf22df 100644 --- a/src/__tests__/ignore.test.ts +++ b/src/__tests__/ignore.test.ts @@ -1,7 +1,7 @@ -import { parseMachinesFromFile } from ".."; +import { parseMachinesFromFile } from '..'; -describe("xstate-ignore blocks", () => { - it("Should pick up the comment blocks with ignore in them", () => { +describe('xstate-ignore blocks', () => { + it('Should pick up the comment blocks with ignore in them', () => { const result = parseMachinesFromFile(` // xstate-ignore-next-line createMachine({}) @@ -11,7 +11,7 @@ describe("xstate-ignore blocks", () => { expect(result.machines[0].getIsIgnored()).toEqual(true); }); - it("Should pick up multi-line comment blocks with ignore in them", () => { + it('Should pick up multi-line comment blocks with ignore in them', () => { const result = parseMachinesFromFile(` /** xstate-ignore-next-line */ createMachine({}) @@ -21,7 +21,7 @@ describe("xstate-ignore blocks", () => { expect(result.machines[0].getIsIgnored()).toEqual(true); }); - it("Should ignore misspelled comments", () => { + it('Should ignore misspelled comments', () => { const result = parseMachinesFromFile(` /** xstate-ignore-next-sline */ createMachine({}) @@ -31,7 +31,7 @@ describe("xstate-ignore blocks", () => { expect(result.machines[0].getIsIgnored()).toEqual(false); }); - it("Should ignore comments that are above the line", () => { + it('Should ignore comments that are above the line', () => { const result = parseMachinesFromFile(` /** xstate-ignore-next-line */ @@ -40,7 +40,7 @@ describe("xstate-ignore blocks", () => { expect(result.machines[0].getIsIgnored()).toEqual(false); }); - it("Should ignore comments that are inside the definition", () => { + it('Should ignore comments that are inside the definition', () => { const result = parseMachinesFromFile(` createMachine( diff --git a/src/__tests__/invoke.test.ts b/src/__tests__/invoke.test.ts index 730999d..2ec5d23 100644 --- a/src/__tests__/invoke.test.ts +++ b/src/__tests__/invoke.test.ts @@ -1,8 +1,8 @@ -import { INLINE_IMPLEMENTATION_TYPE } from "../constants"; -import { parseMachinesFromFile } from "../parseMachinesFromFile"; +import { INLINE_IMPLEMENTATION_TYPE } from '../constants'; +import { parseMachinesFromFile } from '../parseMachinesFromFile'; -describe("Invoke", () => { - it("Should allow for JSON stringifying anonymous invocations", () => { +describe('Invoke', () => { + it('Should allow for JSON stringifying anonymous invocations', () => { const result = parseMachinesFromFile(` createMachine({ invoke: { @@ -20,7 +20,7 @@ describe("Invoke", () => { expect(config).toContain(INLINE_IMPLEMENTATION_TYPE); }); - it("Should detect inline implementations correctly", () => { + it('Should detect inline implementations correctly', () => { const result = parseMachinesFromFile(` createMachine({ invoke: { @@ -31,9 +31,9 @@ describe("Invoke", () => { const invoke = result.machines[0].ast.definition?.invoke?.[0]; - expect(invoke?.src?.declarationType).toEqual("inline"); + expect(invoke?.src?.declarationType).toEqual('inline'); - const invokes = result.machines[0].getAllServices(["inline"]); + const invokes = result.machines[0].getAllServices(['inline']); expect(invokes).toHaveLength(1); }); diff --git a/src/__tests__/layout-comment.test.ts b/src/__tests__/layout-comment.test.ts index 2416c33..80718c8 100644 --- a/src/__tests__/layout-comment.test.ts +++ b/src/__tests__/layout-comment.test.ts @@ -1,14 +1,14 @@ -import { parseMachinesFromFile } from ".."; +import { parseMachinesFromFile } from '..'; -describe("Layout comments", () => { - it("Should ensure that layout comments are parsed", () => { +describe('Layout comments', () => { + it('Should ensure that layout comments are parsed', () => { const result = parseMachinesFromFile(` /** @xstate-layout layout-string */ const machine = createMachine({}); `); expect(result.machines[0].getLayoutComment()?.value).toEqual( - `layout-string`, + `layout-string` ); }); }); diff --git a/src/__tests__/options.test.ts b/src/__tests__/options.test.ts index 4b8366b..14493a9 100644 --- a/src/__tests__/options.test.ts +++ b/src/__tests__/options.test.ts @@ -1,8 +1,8 @@ -import { parseMachinesFromFile } from ".."; -import * as t from "@babel/types"; +import { parseMachinesFromFile } from '..'; +import * as t from '@babel/types'; -describe("Options", () => { - it("Should handle functions declared as ObjectMethod", () => { +describe('Options', () => { + it('Should handle functions declared as ObjectMethod', () => { const result = parseMachinesFromFile(` const machine = createMachine({}, { services: { @@ -12,7 +12,7 @@ describe("Options", () => { `); expect(result.machines[0].ast.options?.services?.properties).toHaveLength( - 1, + 1 ); const node = diff --git a/src/__tests__/parseResult.test.ts b/src/__tests__/parseResult.test.ts index 5f6dac0..0636e81 100644 --- a/src/__tests__/parseResult.test.ts +++ b/src/__tests__/parseResult.test.ts @@ -1,8 +1,8 @@ -import { groupByUniqueName } from ".."; -import { parseMachinesFromFile } from "../parseMachinesFromFile"; +import { groupByUniqueName } from '..'; +import { parseMachinesFromFile } from '../parseMachinesFromFile'; -describe("MachineParseResult", () => { - it("Should let you get a state node by path", () => { +describe('MachineParseResult', () => { + it('Should let you get a state node by path', () => { const result = parseMachinesFromFile(` createMachine({ states: { @@ -20,16 +20,16 @@ describe("MachineParseResult", () => { expect(machine.getAllStateNodes()).toHaveLength(4); - const aNode = machine.getStateNodeByPath(["a"]); + const aNode = machine.getStateNodeByPath(['a']); - expect(aNode?.path).toEqual(["a"]); + expect(aNode?.path).toEqual(['a']); - const b1Node = machine.getStateNodeByPath(["b", "b1"]); + const b1Node = machine.getStateNodeByPath(['b', 'b1']); - expect(b1Node?.path).toEqual(["b", "b1"]); + expect(b1Node?.path).toEqual(['b', 'b1']); }); - it("Should let you list all of the transition target nodes", () => { + it('Should let you list all of the transition target nodes', () => { const result = parseMachinesFromFile(` createMachine({ onDone: ['state.onDone'], @@ -54,11 +54,11 @@ describe("MachineParseResult", () => { // Doing a map here to improve the error messaging expect( - targets.map((target) => target.target.map((target) => target.value)), + targets.map((target) => target.target.map((target) => target.value)) ).toHaveLength(6); }); - it("Should let you list all of the named guards", () => { + it('Should let you list all of the named guards', () => { const result = parseMachinesFromFile(` createMachine({ onDone: [{cond: 'state.onDone'}], @@ -81,14 +81,14 @@ describe("MachineParseResult", () => { }) `); - const conds = groupByUniqueName(result.machines[0].getAllConds(["named"])); + const conds = groupByUniqueName(result.machines[0].getAllConds(['named'])); expect(Object.keys(conds)).toHaveLength(5); - expect(conds["WOW.object"]).toHaveLength(2); + expect(conds['WOW.object']).toHaveLength(2); }); - it("Should grab all invoke names", () => { + it('Should grab all invoke names', () => { const result = parseMachinesFromFile(` createMachine({ invoke: { @@ -97,7 +97,7 @@ describe("MachineParseResult", () => { }) `); - const services = result.machines[0].getAllServices(["named"]); + const services = result.machines[0].getAllServices(['named']); expect(Object.keys(services)).toHaveLength(1); }); diff --git a/src/__tests__/typeParameters.test.ts b/src/__tests__/typeParameters.test.ts index 0093434..ec28171 100644 --- a/src/__tests__/typeParameters.test.ts +++ b/src/__tests__/typeParameters.test.ts @@ -1,7 +1,7 @@ -import { parseMachinesFromFile } from ".."; +import { parseMachinesFromFile } from '..'; -describe("Type parameter parsing", () => { - it("Should parse the correct params", () => { +describe('Type parameter parsing', () => { + it('Should parse the correct params', () => { const fileText = ` createMachine({}); `; @@ -11,9 +11,9 @@ describe("Type parameter parsing", () => { const sliceOfResult = fileText.slice( result.machines[0].ast?.typeArguments?.node.start!, - result.machines[0].ast?.typeArguments?.node.end!, + result.machines[0].ast?.typeArguments?.node.end! ); - expect(sliceOfResult).toEqual(""); + expect(sliceOfResult).toEqual(''); }); }); diff --git a/src/__tests__/validation.test.ts b/src/__tests__/validation.test.ts index c7a55c4..0961547 100644 --- a/src/__tests__/validation.test.ts +++ b/src/__tests__/validation.test.ts @@ -1,16 +1,16 @@ -import { parseMachinesFromFile } from "../parseMachinesFromFile"; +import { parseMachinesFromFile } from '../parseMachinesFromFile'; -describe("Validation and failsafes", () => { - describe("When the code does not contain createMachine or Machine", () => { - it("Should return an empty object", () => { +describe('Validation and failsafes', () => { + describe('When the code does not contain createMachine or Machine', () => { + it('Should return an empty object', () => { expect( parseMachinesFromFile(` const hello = 2; - `), + `) ).toEqual( expect.objectContaining({ - machines: [], - }), + machines: [] + }) ); }); }); diff --git a/src/actions.ts b/src/actions.ts index a02f0c8..80e3c75 100644 --- a/src/actions.ts +++ b/src/actions.ts @@ -1,16 +1,16 @@ -import * as t from "@babel/types"; -import { Action, ChooseCondition } from "xstate"; -import { assign, choose, forwardTo, send } from "xstate/lib/actions"; +import * as t from '@babel/types'; +import { Action, ChooseCondition } from 'xstate'; +import { assign, choose, forwardTo, send } from 'xstate/lib/actions'; -import { Cond, CondNode } from "./conds"; -import { AnyNode, NumericLiteral, StringLiteral } from "./scalars"; +import { Cond, CondNode } from './conds'; +import { AnyNode, NumericLiteral, StringLiteral } from './scalars'; import { arrayOf, isFunctionOrArrowFunctionExpression, maybeArrayOf, namedFunctionCall, - objectTypeWithKnownKeys, -} from "./utils"; + objectTypeWithKnownKeys +} from './utils'; import { AfterAction, CancelAction, @@ -23,15 +23,15 @@ import { SendParentAction, SendUpdateAction, StartAction, - StopAction, -} from "./namedActions"; -import { createParser } from "./createParser"; -import { unionType } from "./unionType"; -import { maybeIdentifierTo } from "./identifiers"; -import { maybeTsAsExpression } from "./tsAsExpression"; -import { wrapParserResult } from "./wrapParserResult"; -import { DeclarationType } from "./types"; -import { INLINE_IMPLEMENTATION_TYPE } from "./constants"; + StopAction +} from './namedActions'; +import { createParser } from './createParser'; +import { unionType } from './unionType'; +import { maybeIdentifierTo } from './identifiers'; +import { maybeTsAsExpression } from './tsAsExpression'; +import { wrapParserResult } from './wrapParserResult'; +import { DeclarationType } from './types'; +import { INLINE_IMPLEMENTATION_TYPE } from './constants'; export interface ActionNode { node: t.Node; @@ -54,9 +54,9 @@ export const ActionAsIdentifier = createParser({ action: node.name, node, name: node.name, - declarationType: "identifier", + declarationType: 'identifier' }; - }, + } }); export const ActionAsFunctionExpression = maybeTsAsExpression( @@ -70,12 +70,12 @@ export const ActionAsFunctionExpression = maybeTsAsExpression( return { node, action, - name: "", - declarationType: "inline", + name: '', + declarationType: 'inline' }; - }, - }), - ), + } + }) + ) ); export const ActionAsString = maybeTsAsExpression( @@ -87,11 +87,11 @@ export const ActionAsString = maybeTsAsExpression( action: node.value, node, name: node.value, - declarationType: "named", + declarationType: 'named' }; - }, - }), - ), + } + }) + ) ); export const ActionAsNode = createParser({ @@ -100,10 +100,10 @@ export const ActionAsNode = createParser({ return { action: INLINE_IMPLEMENTATION_TYPE, node, - name: "", - declarationType: "unknown", + name: '', + declarationType: 'unknown' }; - }, + } }); const ChooseFirstArg = arrayOf( @@ -112,21 +112,21 @@ const ChooseFirstArg = arrayOf( // Don't allow choose inside of choose for now, // too recursive // TODO - fix - actions: maybeArrayOf(ActionAsString), - }), + actions: maybeArrayOf(ActionAsString) + }) ); export const ChooseAction = wrapParserResult( - namedFunctionCall("choose", ChooseFirstArg), + namedFunctionCall('choose', ChooseFirstArg), (result, node): ActionNode => { const conditions: ParsedChooseCondition[] = []; result.argument1Result?.forEach((arg1Result) => { const toPush: typeof conditions[number] = { condition: { - actions: [], + actions: [] }, - actionNodes: [], + actionNodes: [] }; if (arg1Result.actions) { const actionResult = arg1Result.actions.map((action) => action.action); @@ -149,10 +149,10 @@ export const ChooseAction = wrapParserResult( node: node, action: choose(conditions.map((condition) => condition.condition)), chooseConditions: conditions, - name: "", - declarationType: "inline", + name: '', + declarationType: 'inline' }; - }, + } ); interface AssignFirstArg { @@ -165,9 +165,9 @@ const AssignFirstArgObject = createParser({ parseNode: (node) => { return { node, - value: {}, + value: {} }; - }, + } }); const AssignFirstArgFunction = createParser({ @@ -182,18 +182,18 @@ const AssignFirstArgFunction = createParser({ return { node, - value, + value }; - }, + } }); const AssignFirstArg = unionType([ AssignFirstArgObject, - AssignFirstArgFunction, + AssignFirstArgFunction ]); export const AssignAction = wrapParserResult( - namedFunctionCall("assign", AssignFirstArg), + namedFunctionCall('assign', AssignFirstArg), (result): ActionNode => { const defaultAction = function anonymous() { return {}; @@ -205,65 +205,65 @@ export const AssignAction = wrapParserResult( return { node: result.node, action: assign(result.argument1Result?.value || defaultAction), - name: "", - declarationType: "inline", + name: '', + declarationType: 'inline' }; - }, + } ); export const SendActionSecondArg = objectTypeWithKnownKeys({ to: StringLiteral, delay: unionType<{ node: t.Node; value: string | number }>([ NumericLiteral, - StringLiteral, + StringLiteral ]), - id: StringLiteral, + id: StringLiteral }); export const SendAction = wrapParserResult( namedFunctionCall( - "send", + 'send', unionType<{ node: t.Node; value?: string }>([StringLiteral, AnyNode]), - SendActionSecondArg, + SendActionSecondArg ), (result): ActionNode => { return { node: result.node, - name: "", + name: '', action: send( result.argument1Result?.value ?? (() => { return { - type: "UNDEFINED", + type: 'UNDEFINED' }; }), { id: result.argument2Result?.id?.value, to: result.argument2Result?.to?.value, - delay: result.argument2Result?.delay?.value, - }, + delay: result.argument2Result?.delay?.value + } ), - declarationType: "inline", + declarationType: 'inline' }; - }, + } ); export const ForwardToActionSecondArg = objectTypeWithKnownKeys({ - to: StringLiteral, + to: StringLiteral }); export const ForwardToAction = wrapParserResult( - namedFunctionCall("forwardTo", StringLiteral, ForwardToActionSecondArg), + namedFunctionCall('forwardTo', StringLiteral, ForwardToActionSecondArg), (result): ActionNode => { return { node: result.node, - action: forwardTo(result.argument1Result?.value || "", { - to: result.argument2Result?.to?.value, + action: forwardTo(result.argument1Result?.value || '', { + to: result.argument2Result?.to?.value }), - name: "", - declarationType: "inline", + name: '', + declarationType: 'inline' }; - }, + } ); const NamedAction = unionType([ @@ -282,18 +282,18 @@ const NamedAction = unionType([ SendUpdateAction, StartAction, StopAction, - SendParentAction, + SendParentAction ]); const BasicAction = unionType([ ActionAsFunctionExpression, ActionAsString, ActionAsIdentifier, - ActionAsNode, + ActionAsNode ]); export const ArrayOfBasicActions = maybeArrayOf(BasicAction); export const MaybeArrayOfActions = maybeArrayOf( - unionType([NamedAction, BasicAction]), + unionType([NamedAction, BasicAction]) ); diff --git a/src/conds.ts b/src/conds.ts index 696ca4a..a5c5cda 100644 --- a/src/conds.ts +++ b/src/conds.ts @@ -1,10 +1,10 @@ -import * as t from "@babel/types"; -import { Condition } from "xstate"; -import { DeclarationType } from "."; -import { INLINE_IMPLEMENTATION_TYPE } from "./constants"; -import { createParser } from "./createParser"; -import { unionType } from "./unionType"; -import { isFunctionOrArrowFunctionExpression } from "./utils"; +import * as t from '@babel/types'; +import { Condition } from 'xstate'; +import { DeclarationType } from '.'; +import { INLINE_IMPLEMENTATION_TYPE } from './constants'; +import { createParser } from './createParser'; +import { unionType } from './unionType'; +import { isFunctionOrArrowFunctionExpression } from './utils'; export interface CondNode { node: t.Node; @@ -18,13 +18,13 @@ const CondAsFunctionExpression = createParser({ parseNode: (node): CondNode => { return { node, - name: "", + name: '', cond: () => { return false; }, - declarationType: "inline", + declarationType: 'inline' }; - }, + } }); const CondAsStringLiteral = createParser({ @@ -34,9 +34,9 @@ const CondAsStringLiteral = createParser({ node, name: node.value, cond: node.value, - declarationType: "named", + declarationType: 'named' }; - }, + } }); const CondAsNode = createParser({ @@ -44,11 +44,11 @@ const CondAsNode = createParser({ parseNode: (node): CondNode => { return { node, - name: "", + name: '', cond: INLINE_IMPLEMENTATION_TYPE, - declarationType: "unknown", + declarationType: 'unknown' }; - }, + } }); const CondAsIdentifier = createParser({ @@ -56,16 +56,16 @@ const CondAsIdentifier = createParser({ parseNode: (node): CondNode => { return { node, - name: "", + name: '', cond: INLINE_IMPLEMENTATION_TYPE, - declarationType: "identifier", + declarationType: 'identifier' }; - }, + } }); export const Cond = unionType([ CondAsFunctionExpression, CondAsStringLiteral, CondAsIdentifier, - CondAsNode, + CondAsNode ]); diff --git a/src/constants.ts b/src/constants.ts index b6ed34f..2fab0e7 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -1 +1 @@ -export const INLINE_IMPLEMENTATION_TYPE = "_inline"; +export const INLINE_IMPLEMENTATION_TYPE = '_inline'; diff --git a/src/context.ts b/src/context.ts index 3acc1f4..57532b2 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,4 +1,4 @@ -import { createParser } from "./createParser"; -import { AnyNode } from "./scalars"; +import { createParser } from './createParser'; +import { AnyNode } from './scalars'; export const Context = AnyNode; diff --git a/src/createParser.ts b/src/createParser.ts index 6609056..f5ac8ac 100644 --- a/src/createParser.ts +++ b/src/createParser.ts @@ -1,5 +1,5 @@ -import * as t from "@babel/types"; -import { Parser, ParserContext } from "./types"; +import * as t from '@babel/types'; +import { Parser, ParserContext } from './types'; /** * Creates a parser, which can be run later on AST nodes @@ -18,6 +18,6 @@ export const createParser = (params: { }; return { parse, - matches, + matches }; }; diff --git a/src/enums.ts b/src/enums.ts index df2ad3a..2d62893 100644 --- a/src/enums.ts +++ b/src/enums.ts @@ -1,5 +1,5 @@ -import traverse from "@babel/traverse"; -import * as t from "@babel/types"; -import { createParser } from "./createParser"; -import { AnyParser } from "./types"; -import { unionType } from "./unionType"; +import traverse from '@babel/traverse'; +import * as t from '@babel/types'; +import { createParser } from './createParser'; +import { AnyParser } from './types'; +import { unionType } from './unionType'; diff --git a/src/groupByUniqueName.ts b/src/groupByUniqueName.ts index 8c376fe..4bf8b8b 100644 --- a/src/groupByUniqueName.ts +++ b/src/groupByUniqueName.ts @@ -1,7 +1,7 @@ -import { RecordOfArrays } from "./RecordOfArrays"; +import { RecordOfArrays } from './RecordOfArrays'; export const groupByUniqueName = ( - arr: T[], + arr: T[] ): Record => { const record = new RecordOfArrays(); diff --git a/src/history.ts b/src/history.ts index 7dfc3be..3438ce2 100644 --- a/src/history.ts +++ b/src/history.ts @@ -1,10 +1,10 @@ -import * as t from "@babel/types"; -import { createParser } from "./createParser"; -import { unionType } from "./unionType"; +import * as t from '@babel/types'; +import { createParser } from './createParser'; +import { unionType } from './unionType'; interface HistoryNode { node: t.Node; - value: "shallow" | "deep" | boolean; + value: 'shallow' | 'deep' | boolean; } const HistoryAsString = createParser({ @@ -12,9 +12,9 @@ const HistoryAsString = createParser({ parseNode: (node): HistoryNode => { return { node, - value: node.value as HistoryNode["value"], + value: node.value as HistoryNode['value'] }; - }, + } }); const HistoryAsBoolean = createParser({ @@ -22,9 +22,9 @@ const HistoryAsBoolean = createParser({ parseNode: (node): HistoryNode => { return { node, - value: node.value, + value: node.value }; - }, + } }); export const History = unionType([HistoryAsString, HistoryAsBoolean]); diff --git a/src/identifiers.ts b/src/identifiers.ts index a3e7af0..11ed455 100644 --- a/src/identifiers.ts +++ b/src/identifiers.ts @@ -1,13 +1,13 @@ -import traverse from "@babel/traverse"; -import * as t from "@babel/types"; -import { createParser } from "./createParser"; -import { AnyParser } from "./types"; -import { unionType } from "./unionType"; +import traverse from '@babel/traverse'; +import * as t from '@babel/types'; +import { createParser } from './createParser'; +import { AnyParser } from './types'; +import { unionType } from './unionType'; import { getPropertiesOfObjectExpression, - parserFromBabelMatcher, -} from "./utils"; -import { wrapParserResult } from "./wrapParserResult"; + parserFromBabelMatcher +} from './utils'; +import { wrapParserResult } from './wrapParserResult'; /** * Finds a declarator in the same file which corresponds @@ -15,7 +15,7 @@ import { wrapParserResult } from "./wrapParserResult"; */ export const findVariableDeclaratorWithName = ( file: any, - name: string, + name: string ): t.VariableDeclarator | null | undefined => { let declarator: t.VariableDeclarator | null | undefined = null; @@ -24,7 +24,7 @@ export const findVariableDeclaratorWithName = ( if (t.isIdentifier(path.node.id) && path.node.id.name === name) { declarator = path.node as any; } - }, + } }); return declarator; @@ -35,18 +35,18 @@ export const findVariableDeclaratorWithName = ( * which references a variable declaration of a certain type */ export const identifierReferencingVariableDeclaration = ( - parser: AnyParser, + parser: AnyParser ) => { return createParser({ babelMatcher: t.isIdentifier, parseNode: (node, context) => { const variableDeclarator = findVariableDeclaratorWithName( context.file, - node.name, + node.name ); return parser.parse(variableDeclarator?.init, context); - }, + } }); }; @@ -56,7 +56,7 @@ export const identifierReferencingVariableDeclaration = ( */ export const findTSEnumDeclarationWithName = ( file: any, - name: string, + name: string ): t.TSEnumDeclaration | null | undefined => { let declarator: t.TSEnumDeclaration | null | undefined = null; @@ -65,7 +65,7 @@ export const findTSEnumDeclarationWithName = ( if (t.isIdentifier(path.node.id) && path.node.id.name === name) { declarator = path.node as any; } - }, + } }); return declarator; @@ -77,7 +77,7 @@ interface DeepMemberExpression { } const deepMemberExpressionToPath = ( - memberExpression: DeepMemberExpression, + memberExpression: DeepMemberExpression ): string[] => { let currentLevel: DeepMemberExpression | undefined = memberExpression; const path: string[] = []; @@ -103,21 +103,21 @@ const deepMemberExpression = createParser({ }, parseNode: ( node: t.MemberExpression | t.Identifier, - context, + context ): DeepMemberExpression => { return { node, child: - "object" in node + 'object' in node ? deepMemberExpression.parse(node.object, context) - : undefined, + : undefined }; - }, + } }); export const objectExpressionWithDeepPath = ( path: string[], - parser: AnyParser, + parser: AnyParser ) => createParser({ babelMatcher: t.isObjectExpression, @@ -130,13 +130,13 @@ export const objectExpressionWithDeepPath = ( const objectProperties = getPropertiesOfObjectExpression( currentNode as any, - context, + context ); currentNode = ( objectProperties.find( (property) => - property.key === pathSection && t.isObjectProperty(property.node), + property.key === pathSection && t.isObjectProperty(property.node) )?.node as t.ObjectProperty )?.value; @@ -144,11 +144,11 @@ export const objectExpressionWithDeepPath = ( } return parser.parse(currentNode, context); - }, + } }); const getRootIdentifierOfDeepMemberExpression = ( - deepMemberExpression: DeepMemberExpression | undefined, + deepMemberExpression: DeepMemberExpression | undefined ): t.Identifier | undefined => { if (!deepMemberExpressionToPath) return undefined; if (t.isIdentifier(deepMemberExpression?.node)) { @@ -158,7 +158,7 @@ const getRootIdentifierOfDeepMemberExpression = ( }; export const memberExpressionReferencingObjectExpression = ( - parser: AnyParser, + parser: AnyParser ) => createParser({ babelMatcher: t.isMemberExpression, @@ -172,9 +172,9 @@ export const memberExpressionReferencingObjectExpression = ( const path = deepMemberExpressionToPath(result); return identifierReferencingVariableDeclaration( - objectExpressionWithDeepPath(path.slice(1), parser), + objectExpressionWithDeepPath(path.slice(1), parser) ).parse(rootIdentifier, context); - }, + } }); export const memberExpressionReferencingEnumMember = createParser({ @@ -190,7 +190,7 @@ export const memberExpressionReferencingEnumMember = createParser({ const foundEnum = findTSEnumDeclarationWithName( context.file, - rootIdentifier?.name!, + rootIdentifier?.name! ); if (!foundEnum) return undefined; @@ -200,12 +200,12 @@ export const memberExpressionReferencingEnumMember = createParser({ const valueParser = unionType([ wrapParserResult( parserFromBabelMatcher(t.isStringLiteral), - (node) => node.value, + (node) => node.value ), wrapParserResult( parserFromBabelMatcher(t.isIdentifier), - (node) => node.name, - ), + (node) => node.name + ) ]); const memberIndex = foundEnum.members.findIndex((member) => { @@ -226,26 +226,26 @@ export const memberExpressionReferencingEnumMember = createParser({ value: unionType([ wrapParserResult( parserFromBabelMatcher(t.isStringLiteral), - (node) => node.value, + (node) => node.value ), wrapParserResult(parserFromBabelMatcher(t.isNumericLiteral), (node) => - String(node.value), - ), - ]).parse(member.initializer, context) as string, + String(node.value) + ) + ]).parse(member.initializer, context) as string }; } else { return { node: member, - value: String(memberIndex), + value: String(memberIndex) }; } - }, + } }); export const maybeIdentifierTo = (parser: AnyParser) => { return unionType([ parser, identifierReferencingVariableDeclaration(parser), - memberExpressionReferencingObjectExpression(parser), + memberExpressionReferencingObjectExpression(parser) ]); }; diff --git a/src/index.ts b/src/index.ts index 030d6a2..9f046ba 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ -export * from "./types"; -export * from "./constants"; -export * from "./stateNode"; -export * from "xstate/lib/types"; -export * from "./parseMachinesFromFile"; -export * from "./groupByUniqueName"; +export * from './types'; +export * from './constants'; +export * from './stateNode'; +export * from 'xstate/lib/types'; +export * from './parseMachinesFromFile'; +export * from './groupByUniqueName'; diff --git a/src/invoke.ts b/src/invoke.ts index 0e45a95..c7356c8 100644 --- a/src/invoke.ts +++ b/src/invoke.ts @@ -1,17 +1,17 @@ -import * as t from "@babel/types"; -import { DeclarationType } from "."; -import { INLINE_IMPLEMENTATION_TYPE } from "./constants"; -import { createParser } from "./createParser"; -import { maybeIdentifierTo } from "./identifiers"; -import { BooleanLiteral, StringLiteral } from "./scalars"; -import { MaybeTransitionArray } from "./transitions"; -import { maybeTsAsExpression } from "./tsAsExpression"; -import { unionType } from "./unionType"; +import * as t from '@babel/types'; +import { DeclarationType } from '.'; +import { INLINE_IMPLEMENTATION_TYPE } from './constants'; +import { createParser } from './createParser'; +import { maybeIdentifierTo } from './identifiers'; +import { BooleanLiteral, StringLiteral } from './scalars'; +import { MaybeTransitionArray } from './transitions'; +import { maybeTsAsExpression } from './tsAsExpression'; +import { unionType } from './unionType'; import { isFunctionOrArrowFunctionExpression, maybeArrayOf, - objectTypeWithKnownKeys, -} from "./utils"; + objectTypeWithKnownKeys +} from './utils'; interface InvokeNode { node: t.Node; @@ -30,11 +30,11 @@ const InvokeSrcFunctionExpression = maybeTsAsExpression( return { value, node, - declarationType: "inline", + declarationType: 'inline' }; - }, - }), - ), + } + }) + ) ); const InvokeSrcNode = createParser({ @@ -42,8 +42,8 @@ const InvokeSrcNode = createParser({ parseNode: (node): InvokeNode => ({ value: INLINE_IMPLEMENTATION_TYPE, node, - declarationType: "unknown", - }), + declarationType: 'unknown' + }) }); const InvokeSrcStringLiteral = createParser({ @@ -51,8 +51,8 @@ const InvokeSrcStringLiteral = createParser({ parseNode: (node): InvokeNode => ({ value: node.value, node, - declarationType: "named", - }), + declarationType: 'named' + }) }); const InvokeSrcIdentifier = createParser({ @@ -60,15 +60,15 @@ const InvokeSrcIdentifier = createParser({ parseNode: (node): InvokeNode => ({ value: INLINE_IMPLEMENTATION_TYPE, node, - declarationType: "identifier", - }), + declarationType: 'identifier' + }) }); const InvokeSrc = unionType([ InvokeSrcStringLiteral, InvokeSrcFunctionExpression, InvokeSrcIdentifier, - InvokeSrcNode, + InvokeSrcNode ]); const InvokeConfigObject = objectTypeWithKnownKeys({ @@ -77,7 +77,7 @@ const InvokeConfigObject = objectTypeWithKnownKeys({ onDone: MaybeTransitionArray, onError: MaybeTransitionArray, autoForward: BooleanLiteral, - forward: BooleanLiteral, + forward: BooleanLiteral }); export const Invoke = maybeArrayOf(InvokeConfigObject); diff --git a/src/machineCallExpression.ts b/src/machineCallExpression.ts index 6cd64bf..ec74bb3 100644 --- a/src/machineCallExpression.ts +++ b/src/machineCallExpression.ts @@ -1,9 +1,9 @@ -import * as t from "@babel/types"; -import { StateNode } from "./stateNode"; -import { GetParserResult } from "./utils"; -import { MachineOptions } from "./options"; -import { createParser } from "./createParser"; -import { AnyTypeParameterList } from "./typeParameters"; +import * as t from '@babel/types'; +import { StateNode } from './stateNode'; +import { GetParserResult } from './utils'; +import { MachineOptions } from './options'; +import { createParser } from './createParser'; +import { AnyTypeParameterList } from './typeParameters'; export type TMachineCallExpression = GetParserResult< typeof MachineCallExpression @@ -15,7 +15,7 @@ export const MachineCallExpression = createParser({ if ( t.isMemberExpression(node.callee) && t.isIdentifier(node.callee.property) && - ["createMachine", "Machine"].includes(node.callee.property.name) + ['createMachine', 'Machine'].includes(node.callee.property.name) ) { return { callee: node.callee, @@ -24,13 +24,13 @@ export const MachineCallExpression = createParser({ options: MachineOptions.parse(node.arguments[1], context), isMemberExpression: true, typeArguments: AnyTypeParameterList.parse(node.typeParameters, context), - node, + node }; } if ( t.isIdentifier(node.callee) && - ["createMachine", "Machine"].includes(node.callee.name) + ['createMachine', 'Machine'].includes(node.callee.name) ) { return { callee: node.callee, @@ -39,8 +39,8 @@ export const MachineCallExpression = createParser({ options: MachineOptions.parse(node.arguments[1], context), isMemberExpression: false, typeArguments: AnyTypeParameterList.parse(node.typeParameters, context), - node, + node }; } - }, + } }); diff --git a/src/meta.ts b/src/meta.ts index 0818048..f05bd13 100644 --- a/src/meta.ts +++ b/src/meta.ts @@ -1,9 +1,9 @@ -import { StringLiteral, TemplateLiteral } from "./scalars"; -import { unionType } from "./unionType"; -import { objectTypeWithKnownKeys } from "./utils"; +import { StringLiteral, TemplateLiteral } from './scalars'; +import { unionType } from './unionType'; +import { objectTypeWithKnownKeys } from './utils'; export const MetaDescription = unionType([StringLiteral, TemplateLiteral]); export const StateMeta = objectTypeWithKnownKeys({ - description: MetaDescription, + description: MetaDescription }); diff --git a/src/namedActions.ts b/src/namedActions.ts index a3c4572..7539b40 100644 --- a/src/namedActions.ts +++ b/src/namedActions.ts @@ -10,161 +10,161 @@ import { sendParent, sendUpdate, start, - stop, -} from "xstate/lib/actions"; -import type { ActionNode } from "./actions"; -import { AnyNode, NumericLiteral, StringLiteral } from "./scalars"; -import { namedFunctionCall } from "./utils"; -import * as t from "@babel/types"; -import { unionType } from "./unionType"; -import { wrapParserResult } from "./wrapParserResult"; + stop +} from 'xstate/lib/actions'; +import type { ActionNode } from './actions'; +import { AnyNode, NumericLiteral, StringLiteral } from './scalars'; +import { namedFunctionCall } from './utils'; +import * as t from '@babel/types'; +import { unionType } from './unionType'; +import { wrapParserResult } from './wrapParserResult'; export const AfterAction = wrapParserResult( namedFunctionCall( - "after", + 'after', unionType<{ node: t.Node; value: number | string }>([ StringLiteral, - NumericLiteral, - ]), + NumericLiteral + ]) ), (result): ActionNode => { return { node: result.node, - action: after(result.argument1Result?.value || ""), - name: "", - declarationType: "inline", + action: after(result.argument1Result?.value || ''), + name: '', + declarationType: 'inline' }; - }, + } ); export const CancelAction = wrapParserResult( - namedFunctionCall("cancel", AnyNode), + namedFunctionCall('cancel', AnyNode), (result): ActionNode => { return { node: result.node, - action: cancel(""), - name: "", - declarationType: "inline", + action: cancel(''), + name: '', + declarationType: 'inline' }; - }, + } ); export const DoneAction = wrapParserResult( - namedFunctionCall("done", AnyNode), + namedFunctionCall('done', AnyNode), (result): ActionNode => { return { node: result.node, - action: done(""), - name: "", - declarationType: "inline", + action: done(''), + name: '', + declarationType: 'inline' }; - }, + } ); export const EscalateAction = wrapParserResult( - namedFunctionCall("escalate", AnyNode), + namedFunctionCall('escalate', AnyNode), (result): ActionNode => { return { node: result.node, - action: escalate(""), - name: "", - declarationType: "inline", + action: escalate(''), + name: '', + declarationType: 'inline' }; - }, + } ); export const LogAction = wrapParserResult( - namedFunctionCall("log", AnyNode), + namedFunctionCall('log', AnyNode), (result): ActionNode => { return { node: result.node, action: log(), - name: "", - declarationType: "inline", + name: '', + declarationType: 'inline' }; - }, + } ); export const PureAction = wrapParserResult( - namedFunctionCall("pure", AnyNode), + namedFunctionCall('pure', AnyNode), (result): ActionNode => { return { node: result.node, action: pure(() => []), - name: "", - declarationType: "inline", + name: '', + declarationType: 'inline' }; - }, + } ); export const RaiseAction = wrapParserResult( - namedFunctionCall("raise", AnyNode), + namedFunctionCall('raise', AnyNode), (result): ActionNode => { return { node: result.node, - action: raise(""), - name: "", - declarationType: "inline", + action: raise(''), + name: '', + declarationType: 'inline' }; - }, + } ); export const RespondAction = wrapParserResult( - namedFunctionCall("respond", AnyNode), + namedFunctionCall('respond', AnyNode), (result): ActionNode => { return { node: result.node, - action: respond(""), - name: "", - declarationType: "inline", + action: respond(''), + name: '', + declarationType: 'inline' }; - }, + } ); export const SendParentAction = wrapParserResult( - namedFunctionCall("sendParent", AnyNode), + namedFunctionCall('sendParent', AnyNode), (result): ActionNode => { return { node: result.node, - action: sendParent(""), - name: "", - declarationType: "inline", + action: sendParent(''), + name: '', + declarationType: 'inline' }; - }, + } ); export const SendUpdateAction = wrapParserResult( - namedFunctionCall("sendUpdate", AnyNode), + namedFunctionCall('sendUpdate', AnyNode), (result): ActionNode => { return { node: result.node, action: sendUpdate(), - name: "", - declarationType: "inline", + name: '', + declarationType: 'inline' }; - }, + } ); export const StartAction = wrapParserResult( - namedFunctionCall("start", AnyNode), + namedFunctionCall('start', AnyNode), (result): ActionNode => { return { node: result.node, - action: start(""), - name: "", - declarationType: "inline", + action: start(''), + name: '', + declarationType: 'inline' }; - }, + } ); export const StopAction = wrapParserResult( - namedFunctionCall("stop", AnyNode), + namedFunctionCall('stop', AnyNode), (result): ActionNode => { return { node: result.node, - action: stop(""), - name: "", - declarationType: "inline", + action: stop(''), + name: '', + declarationType: 'inline' }; - }, + } ); diff --git a/src/options.ts b/src/options.ts index eb72fcf..2c3ea0a 100644 --- a/src/options.ts +++ b/src/options.ts @@ -1,16 +1,16 @@ -import { maybeIdentifierTo } from "./identifiers"; -import { AnyNode, BooleanLiteral } from "./scalars"; -import { maybeTsAsExpression } from "./tsAsExpression"; -import { objectOf, objectTypeWithKnownKeys } from "./utils"; +import { maybeIdentifierTo } from './identifiers'; +import { AnyNode, BooleanLiteral } from './scalars'; +import { maybeTsAsExpression } from './tsAsExpression'; +import { objectOf, objectTypeWithKnownKeys } from './utils'; const MachineOptionsObject = objectTypeWithKnownKeys({ actions: objectOf(AnyNode), services: objectOf(AnyNode), guards: objectOf(AnyNode), delays: objectOf(AnyNode), - devTools: BooleanLiteral, + devTools: BooleanLiteral }); export const MachineOptions = maybeTsAsExpression( - maybeIdentifierTo(MachineOptionsObject), + maybeIdentifierTo(MachineOptionsObject) ); diff --git a/src/parseMachinesFromFile.ts b/src/parseMachinesFromFile.ts index 5f03e43..53092a5 100644 --- a/src/parseMachinesFromFile.ts +++ b/src/parseMachinesFromFile.ts @@ -1,48 +1,48 @@ -import * as parser from "@babel/parser"; -import traverse from "@babel/traverse"; -import { MachineConfig } from "xstate"; -import { MachineCallExpression } from "./machineCallExpression"; -import { MachineParseResult } from "./MachineParseResult"; -import { toMachineConfig } from "./toMachineConfig"; -import { ParseResult } from "./types"; +import * as parser from '@babel/parser'; +import traverse from '@babel/traverse'; +import { MachineConfig } from 'xstate'; +import { MachineCallExpression } from './machineCallExpression'; +import { MachineParseResult } from './MachineParseResult'; +import { toMachineConfig } from './toMachineConfig'; +import { ParseResult } from './types'; export const parseMachinesFromFile = (fileContents: string): ParseResult => { if ( - !fileContents.includes("createMachine") && - !fileContents.includes("Machine") + !fileContents.includes('createMachine') && + !fileContents.includes('Machine') ) { return { machines: [], comments: [], - file: undefined, + file: undefined }; } const parseResult = parser.parse(fileContents, { - sourceType: "module", + sourceType: 'module', plugins: [ - "typescript", - "jsx", - ["decorators", { decoratorsBeforeExport: false }], - ], + 'typescript', + 'jsx', + ['decorators', { decoratorsBeforeExport: false }] + ] }); let result: ParseResult = { machines: [], comments: [], - file: parseResult, + file: parseResult }; parseResult.comments?.forEach((comment) => { - if (comment.value.includes("xstate-ignore-next-line")) { + if (comment.value.includes('xstate-ignore-next-line')) { result.comments.push({ node: comment, - type: "xstate-ignore-next-line", + type: 'xstate-ignore-next-line' }); - } else if (comment.value.includes("@xstate-layout")) { + } else if (comment.value.includes('@xstate-layout')) { result.comments.push({ node: comment, - type: "xstate-layout", + type: 'xstate-layout' }); } }); @@ -50,18 +50,18 @@ export const parseMachinesFromFile = (fileContents: string): ParseResult => { traverse(parseResult as any, { CallExpression(path) { const ast = MachineCallExpression.parse(path.node as any, { - file: parseResult, + file: parseResult }); if (ast) { result.machines.push( new MachineParseResult({ ast, fileComments: result.comments, - scope: path.scope, - }), + scope: path.scope + }) ); } - }, + } }); return result; diff --git a/src/scalars.ts b/src/scalars.ts index d1abb38..9ec72c0 100644 --- a/src/scalars.ts +++ b/src/scalars.ts @@ -1,19 +1,19 @@ -import * as t from "@babel/types"; -import { createParser } from "./createParser"; +import * as t from '@babel/types'; +import { createParser } from './createParser'; import { maybeIdentifierTo, - memberExpressionReferencingEnumMember, -} from "./identifiers"; -import { StringLiteralNode } from "./types"; -import { maybeTsAsExpression } from "./tsAsExpression"; -import { unionType } from "./unionType"; -import { wrapParserResult } from "./wrapParserResult"; + memberExpressionReferencingEnumMember +} from './identifiers'; +import { StringLiteralNode } from './types'; +import { maybeTsAsExpression } from './tsAsExpression'; +import { unionType } from './unionType'; +import { wrapParserResult } from './wrapParserResult'; export const StringLiteral = unionType([ wrapParserResult(memberExpressionReferencingEnumMember, (node) => { return { node: node.node as t.Node, - value: node.value, + value: node.value }; }), maybeTsAsExpression( @@ -23,12 +23,12 @@ export const StringLiteral = unionType([ parseNode: (node): StringLiteralNode => { return { value: node.value, - node, + node }; - }, - }), - ), - ), + } + }) + ) + ) ]); export const NumericLiteral = maybeTsAsExpression( @@ -38,11 +38,11 @@ export const NumericLiteral = maybeTsAsExpression( parseNode: (node) => { return { value: node.value, - node, + node }; - }, - }), - ), + } + }) + ) ); export const BooleanLiteral = maybeTsAsExpression( @@ -52,21 +52,21 @@ export const BooleanLiteral = maybeTsAsExpression( parseNode: (node) => { return { value: node.value, - node, + node }; - }, - }), - ), + } + }) + ) ); export const AnyNode = createParser({ babelMatcher: t.isNode, - parseNode: (node) => ({ node }), + parseNode: (node) => ({ node }) }); export const Identifier = createParser({ babelMatcher: t.isIdentifier, - parseNode: (node) => ({ node }), + parseNode: (node) => ({ node }) }); export const TemplateLiteral = maybeTsAsExpression( @@ -74,16 +74,16 @@ export const TemplateLiteral = maybeTsAsExpression( createParser({ babelMatcher: t.isTemplateLiteral, parseNode: (node) => { - let value = ""; + let value = ''; node.quasis.forEach((quasi) => { value = `${value}${quasi.value.raw}`; }); return { node, - value, + value }; - }, - }), - ), + } + }) + ) ); diff --git a/src/schema.ts b/src/schema.ts index 9a03de8..4751ef1 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -1,9 +1,9 @@ -import { AnyNode } from "./scalars"; -import { unionType } from "./unionType"; -import { objectTypeWithKnownKeys } from "./utils"; +import { AnyNode } from './scalars'; +import { unionType } from './unionType'; +import { objectTypeWithKnownKeys } from './utils'; export const Schema = objectTypeWithKnownKeys({ context: AnyNode, events: AnyNode, - services: AnyNode, + services: AnyNode }); diff --git a/src/stateNode.ts b/src/stateNode.ts index bd09542..4305a59 100644 --- a/src/stateNode.ts +++ b/src/stateNode.ts @@ -1,21 +1,21 @@ -import * as t from "@babel/types"; -import { MaybeArrayOfActions } from "./actions"; -import { Context } from "./context"; -import { History } from "./history"; -import { Invoke } from "./invoke"; -import { StateMeta } from "./meta"; -import { AnyNode, BooleanLiteral, StringLiteral } from "./scalars"; -import { Schema } from "./schema"; -import { MaybeTransitionArray } from "./transitions"; -import { TsTypes } from "./tsTypes"; -import { AnyParser } from "./types"; +import * as t from '@babel/types'; +import { MaybeArrayOfActions } from './actions'; +import { Context } from './context'; +import { History } from './history'; +import { Invoke } from './invoke'; +import { StateMeta } from './meta'; +import { AnyNode, BooleanLiteral, StringLiteral } from './scalars'; +import { Schema } from './schema'; +import { MaybeTransitionArray } from './transitions'; +import { TsTypes } from './tsTypes'; +import { AnyParser } from './types'; import { GetParserResult, maybeArrayOf, objectOf, ObjectOfReturn, - objectTypeWithKnownKeys, -} from "./utils"; + objectTypeWithKnownKeys +} from './utils'; const On = objectOf(MaybeTransitionArray); @@ -80,8 +80,8 @@ const StateNodeObject: AnyParser = objectTypeWithKnownKeys( meta: StateMeta, context: Context, data: AnyNode, - preserveActionOrder: BooleanLiteral, - }), + preserveActionOrder: BooleanLiteral + }) ); export const StateNode = StateNodeObject; diff --git a/src/testUtils.ts b/src/testUtils.ts index 8acbf94..7cc4b34 100644 --- a/src/testUtils.ts +++ b/src/testUtils.ts @@ -1,10 +1,10 @@ -import fs from "fs"; -import path from "path"; -import * as XStateParser from "./index"; +import fs from 'fs'; +import path from 'path'; +import * as XStateParser from './index'; const parseFileFromExamplesDir = (filename: string) => { const asString = fs - .readFileSync(path.resolve(__dirname, "../examples", filename)) + .readFileSync(path.resolve(__dirname, '../examples', filename)) .toString(); const result = XStateParser.parseMachinesFromFile(asString); @@ -13,10 +13,10 @@ const parseFileFromExamplesDir = (filename: string) => { }; const withoutContext = ( - config: T, -): Omit => { + config: T +): Omit => { const newConfig = { - ...config, + ...config }; delete newConfig.context; @@ -31,5 +31,5 @@ const serialise = (machine: any) => { export const testUtils = { parseFileFromExamplesDir, withoutContext, - serialise, + serialise }; diff --git a/src/toMachineConfig.ts b/src/toMachineConfig.ts index 1b8d7e8..ac9f9d8 100644 --- a/src/toMachineConfig.ts +++ b/src/toMachineConfig.ts @@ -2,17 +2,17 @@ import { Actions, MachineConfig, StateNodeConfig, - TransitionConfigOrTarget, -} from "xstate"; -import { MaybeArrayOfActions } from "./actions"; -import { INLINE_IMPLEMENTATION_TYPE } from "./constants"; -import { TMachineCallExpression } from "./machineCallExpression"; -import { StateNodeReturn } from "./stateNode"; -import { MaybeTransitionArray } from "./transitions"; -import { GetParserResult } from "./utils"; + TransitionConfigOrTarget +} from 'xstate'; +import { MaybeArrayOfActions } from './actions'; +import { INLINE_IMPLEMENTATION_TYPE } from './constants'; +import { TMachineCallExpression } from './machineCallExpression'; +import { StateNodeReturn } from './stateNode'; +import { MaybeTransitionArray } from './transitions'; +import { GetParserResult } from './utils'; const parseStateNode = ( - astResult: StateNodeReturn, + astResult: StateNodeReturn ): StateNodeConfig => { const config: MachineConfig = {}; @@ -54,7 +54,7 @@ const parseStateNode = ( astResult.after.properties.forEach((afterProperty) => { (config.after as any)[afterProperty.key] = getTransitions( - afterProperty.result, + afterProperty.result ); }); } @@ -79,7 +79,7 @@ const parseStateNode = ( if (astResult.meta?.description) { config.meta = { - description: astResult.meta.description.value, + description: astResult.meta.description.value }; } @@ -93,7 +93,7 @@ const parseStateNode = ( astResult.invoke.forEach((invoke) => { const toPush: typeof invokes[number] = { - src: INLINE_IMPLEMENTATION_TYPE, + src: INLINE_IMPLEMENTATION_TYPE }; if (invoke.src) { toPush.src = invoke.src.value; @@ -135,14 +135,14 @@ const parseStateNode = ( }; export const toMachineConfig = ( - result: TMachineCallExpression, + result: TMachineCallExpression ): MachineConfig | undefined => { if (!result?.definition) return undefined; return parseStateNode(result?.definition); }; export const getActionConfig = ( - astActions: GetParserResult, + astActions: GetParserResult ): Actions => { const actions: Actions = []; @@ -158,7 +158,7 @@ export const getActionConfig = ( }; export const getTransitions = ( - astTransitions: GetParserResult, + astTransitions: GetParserResult ): TransitionConfigOrTarget => { const transitions: TransitionConfigOrTarget = []; diff --git a/src/transitions.ts b/src/transitions.ts index 8537ea4..6f86cf8 100644 --- a/src/transitions.ts +++ b/src/transitions.ts @@ -1,16 +1,16 @@ -import * as t from "@babel/types"; -import { MaybeArrayOfActions } from "./actions"; -import { Cond } from "./conds"; -import { createParser } from "./createParser"; -import { StringLiteral } from "./scalars"; -import { StringLiteralNode } from "./types"; -import { unionType } from "./unionType"; +import * as t from '@babel/types'; +import { MaybeArrayOfActions } from './actions'; +import { Cond } from './conds'; +import { createParser } from './createParser'; +import { StringLiteral } from './scalars'; +import { StringLiteralNode } from './types'; +import { unionType } from './unionType'; import { GetParserResult, maybeArrayOf, - objectTypeWithKnownKeys, -} from "./utils"; -import { wrapParserResult } from "./wrapParserResult"; + objectTypeWithKnownKeys +} from './utils'; +import { wrapParserResult } from './wrapParserResult'; export type TransitionConfigNode = GetParserResult; @@ -19,7 +19,7 @@ const TransitionTarget = maybeArrayOf(StringLiteral); const TransitionObject = objectTypeWithKnownKeys({ target: TransitionTarget, actions: MaybeArrayOfActions, - cond: Cond, + cond: Cond }); const TransitionConfigOrTargetLiteral = unionType([ @@ -27,11 +27,11 @@ const TransitionConfigOrTargetLiteral = unionType([ wrapParserResult(TransitionTarget, (targets): TransitionConfigNode => { return { target: targets, - node: targets[0].node, + node: targets[0].node }; - }), + }) ]); export const MaybeTransitionArray = maybeArrayOf( - TransitionConfigOrTargetLiteral, + TransitionConfigOrTargetLiteral ); diff --git a/src/tsAsExpression.ts b/src/tsAsExpression.ts index 0c807c7..df263a9 100644 --- a/src/tsAsExpression.ts +++ b/src/tsAsExpression.ts @@ -1,7 +1,7 @@ -import { AnyParser } from "."; -import * as t from "@babel/types"; -import { createParser } from "./createParser"; -import { unionType } from "./unionType"; +import { AnyParser } from '.'; +import * as t from '@babel/types'; +import { createParser } from './createParser'; +import { unionType } from './unionType'; export const tsAsExpression = (parser: AnyParser) => { return createParser({ @@ -10,7 +10,7 @@ export const tsAsExpression = (parser: AnyParser) => { if (parser.matches(node.expression)) { return parser.parse(node.expression, context); } - }, + } }); }; diff --git a/src/tsTypes.ts b/src/tsTypes.ts index ecd2b7c..1998831 100644 --- a/src/tsTypes.ts +++ b/src/tsTypes.ts @@ -1,9 +1,9 @@ -import { AnyNode, BooleanLiteral } from "./scalars"; -import { unionType } from "./unionType"; -import { wrapParserResult } from "./wrapParserResult"; -import * as t from "@babel/types"; +import { AnyNode, BooleanLiteral } from './scalars'; +import { unionType } from './unionType'; +import { wrapParserResult } from './wrapParserResult'; +import * as t from '@babel/types'; export const TsTypes = unionType<{ node: t.Node; value?: boolean }>([ BooleanLiteral, - AnyNode, + AnyNode ]); diff --git a/src/typeParameters.ts b/src/typeParameters.ts index c125581..176a0d8 100644 --- a/src/typeParameters.ts +++ b/src/typeParameters.ts @@ -1,28 +1,28 @@ -import { createParser } from "./createParser"; -import * as t from "@babel/types"; -import { AnyParser } from "."; -import { arrayOf } from "./utils"; +import { createParser } from './createParser'; +import * as t from '@babel/types'; +import { AnyParser } from '.'; +import { arrayOf } from './utils'; export const TSTypeParameterInstantiation = ( - parser: AnyParser, + parser: AnyParser ) => createParser({ babelMatcher: t.isTSTypeParameterInstantiation, parseNode: (node, context) => { return { node, - params: node.params.map((param) => parser.parse(param, context)), + params: node.params.map((param) => parser.parse(param, context)) }; - }, + } }); export const TSType = createParser({ babelMatcher: t.isTSType, parseNode: (node) => { return { - node, + node }; - }, + } }); export const AnyTypeParameterList = TSTypeParameterInstantiation(TSType); diff --git a/src/types.ts b/src/types.ts index b1d8b11..48e9920 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,6 +1,6 @@ -import * as t from "@babel/types"; -import { MachineConfig } from "xstate"; -import { MachineParseResult } from "./MachineParseResult"; +import * as t from '@babel/types'; +import { MachineConfig } from 'xstate'; +import { MachineParseResult } from './MachineParseResult'; export type Location = t.SourceLocation | null; @@ -16,7 +16,7 @@ export interface ParserContext { export interface Parser { parse: ( node: t.Node | undefined | null, - context: ParserContext, + context: ParserContext ) => Result | undefined; matches: (node: T) => boolean; } @@ -28,7 +28,7 @@ export interface AnyParser { export interface Comment { node: t.CommentLine | t.CommentBlock; - type: "xstate-ignore-next-line" | "xstate-layout"; + type: 'xstate-ignore-next-line' | 'xstate-layout'; } export interface ParseResult { @@ -37,4 +37,4 @@ export interface ParseResult { file: t.File | undefined; } -export type DeclarationType = "named" | "inline" | "identifier" | "unknown"; +export type DeclarationType = 'named' | 'inline' | 'identifier' | 'unknown'; diff --git a/src/unionType.ts b/src/unionType.ts index ebdb1cf..4306b0a 100644 --- a/src/unionType.ts +++ b/src/unionType.ts @@ -1,4 +1,4 @@ -import { AnyParser, ParserContext } from "."; +import { AnyParser, ParserContext } from '.'; /** * Used to declare when a type can be either one @@ -6,7 +6,7 @@ import { AnyParser, ParserContext } from "."; * return the same result */ export const unionType = ( - parsers: AnyParser[], + parsers: AnyParser[] ): AnyParser => { const matches = (node: any) => { return parsers.some((parser) => parser.matches(node)); @@ -21,6 +21,6 @@ export const unionType = ( return { matches, - parse, + parse }; }; diff --git a/src/utils.ts b/src/utils.ts index 8de9cfa..291693b 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,22 +1,22 @@ -import * as t from "@babel/types"; -import { createParser } from "./createParser"; +import * as t from '@babel/types'; +import { createParser } from './createParser'; import { identifierReferencingVariableDeclaration, - maybeIdentifierTo, -} from "./identifiers"; + maybeIdentifierTo +} from './identifiers'; import { Identifier, NumericLiteral, StringLiteral, - TemplateLiteral, -} from "./scalars"; -import { maybeTsAsExpression } from "./tsAsExpression"; -import { AnyParser, ParserContext } from "./types"; -import { unionType } from "./unionType"; -import { wrapParserResult } from "./wrapParserResult"; + TemplateLiteral +} from './scalars'; +import { maybeTsAsExpression } from './tsAsExpression'; +import { AnyParser, ParserContext } from './types'; +import { unionType } from './unionType'; +import { wrapParserResult } from './wrapParserResult'; export const parserFromBabelMatcher = ( - babelMatcher: (node: any) => node is T, + babelMatcher: (node: any) => node is T ) => createParser({ babelMatcher, parseNode: (node) => node }); /** @@ -24,7 +24,7 @@ export const parserFromBabelMatcher = ( * be declared as an array */ export const maybeArrayOf = ( - parser: AnyParser | AnyParser, + parser: AnyParser | AnyParser ): AnyParser => { const arrayParser = createParser({ babelMatcher: t.isArrayExpression, @@ -41,7 +41,7 @@ export const maybeArrayOf = ( }); return toReturn; - }, + } }); const otherParser = wrapParserResult( @@ -51,7 +51,7 @@ export const maybeArrayOf = ( return res; } return [res]; - }, + } ); return unionType([arrayParser, otherParser]); @@ -62,7 +62,7 @@ export const maybeArrayOf = ( * an array of something */ export const arrayOf = ( - parser: AnyParser, + parser: AnyParser ): AnyParser => { return createParser({ babelMatcher: t.isArrayExpression, @@ -77,7 +77,7 @@ export const arrayOf = ( }); return toReturn; - }, + } }); }; @@ -88,14 +88,14 @@ export const objectMethod = createParser({ node, key: wrapParserResult(Identifier, ({ node }) => ({ node: node, - value: node.name, - })).parse(node.key, context), + value: node.name + })).parse(node.key, context) }; - }, + } }); export const staticObjectProperty = ( - keyParser: AnyParser, + keyParser: AnyParser ) => createParser< t.ObjectProperty, @@ -110,9 +110,9 @@ export const staticObjectProperty = ( parseNode: (node, context) => { return { node, - key: keyParser.parse(node.key, context), + key: keyParser.parse(node.key, context) }; - }, + } }); export const spreadElement = (parser: AnyParser) => { @@ -121,22 +121,22 @@ export const spreadElement = (parser: AnyParser) => { parseNode: (node, context) => { const result = { node, - argumentResult: parser.parse(node.argument, context), + argumentResult: parser.parse(node.argument, context) }; return result; - }, + } }); }; export const spreadElementReferencingIdentifier = ( - parser: AnyParser, + parser: AnyParser ) => { return spreadElement(identifierReferencingVariableDeclaration(parser)); }; export const dynamicObjectProperty = ( - keyParser: AnyParser, + keyParser: AnyParser ) => createParser< t.ObjectProperty, @@ -151,9 +151,9 @@ export const dynamicObjectProperty = ( parseNode: (node, context) => { return { node, - key: keyParser.parse(node.key, context), + key: keyParser.parse(node.key, context) }; - }, + } }); const staticPropertyWithKey = staticObjectProperty( @@ -163,13 +163,13 @@ const staticPropertyWithKey = staticObjectProperty( parseNode: (node) => { return { node, - value: node.name, + value: node.name }; - }, + } }), StringLiteral, - NumericLiteral, - ]), + NumericLiteral + ]) ); const dynamicPropertyWithKey = dynamicObjectProperty( @@ -177,8 +177,8 @@ const dynamicPropertyWithKey = dynamicObjectProperty( unionType<{ node: t.Node; value: string | number | undefined; - }>([StringLiteral, NumericLiteral, TemplateLiteral]), - ), + }>([StringLiteral, NumericLiteral, TemplateLiteral]) + ) ); const propertyKey = unionType<{ @@ -195,7 +195,7 @@ const propertyKey = unionType<{ */ export const getPropertiesOfObjectExpression = ( node: t.ObjectExpression | undefined, - context: ParserContext, + context: ParserContext ) => { const propertiesToReturn: { node: t.ObjectProperty | t.ObjectMethod; @@ -214,12 +214,12 @@ export const getPropertiesOfObjectExpression = ( const spreadElementResult = spreadElementReferencingIdentifier( createParser({ babelMatcher: t.isObjectExpression, - parseNode: (node) => node, - }), + parseNode: (node) => node + }) ).parse(property, context); propertiesToParse.push( - ...(spreadElementResult?.argumentResult?.properties || []), + ...(spreadElementResult?.argumentResult?.properties || []) ); propertiesToParse.forEach((property) => { @@ -229,7 +229,7 @@ export const getPropertiesOfObjectExpression = ( key: `${result.key?.value}`, node: result.node, keyNode: result.key.node, - property, + property }); } }); @@ -239,15 +239,15 @@ export const getPropertiesOfObjectExpression = ( }; export type GetObjectKeysResult< - T extends { [index: string]: AnyParser }, + T extends { [index: string]: AnyParser } > = { - [K in keyof T]?: ReturnType; + [K in keyof T]?: ReturnType; } & { node: t.Node; }; export type GetParserResult> = NonNullable< - ReturnType + ReturnType >; /** @@ -255,9 +255,9 @@ export type GetParserResult> = NonNullable< * can be different things */ export const objectTypeWithKnownKeys = < - T extends { [index: string]: AnyParser }, + T extends { [index: string]: AnyParser } >( - parserObject: T | (() => T), + parserObject: T | (() => T) ) => maybeTsAsExpression( maybeIdentifierTo( @@ -266,10 +266,10 @@ export const objectTypeWithKnownKeys = < parseNode: (node, context) => { const properties = getPropertiesOfObjectExpression(node, context); const parseObject = - typeof parserObject === "function" ? parserObject() : parserObject; + typeof parserObject === 'function' ? parserObject() : parserObject; const toReturn = { - node, + node }; properties?.forEach((property) => { @@ -290,9 +290,9 @@ export const objectTypeWithKnownKeys = < }); return toReturn as GetObjectKeysResult; - }, - }), - ), + } + }) + ) ); export interface ObjectOfReturn { @@ -311,7 +311,7 @@ export interface ObjectOfReturn { * `on` */ export const objectOf = ( - parser: AnyParser, + parser: AnyParser ): AnyParser> => { return maybeIdentifierTo( createParser({ @@ -321,7 +321,7 @@ export const objectOf = ( const toReturn = { node, - properties: [], + properties: [] } as ObjectOfReturn; properties.forEach((property) => { @@ -338,14 +338,14 @@ export const objectOf = ( key: property.key, keyNode: property.keyNode, result, - property: property.property, + property: property.property }); } }); return toReturn; - }, - }), + } + }) ); }; @@ -356,7 +356,7 @@ export const objectOf = ( export const namedFunctionCall = ( name: string, argument1Parser: AnyParser, - argument2Parser?: AnyParser, + argument2Parser?: AnyParser ): AnyParser<{ node: t.CallExpression; argument1Result: Argument1Result | undefined; @@ -368,9 +368,9 @@ export const namedFunctionCall = ( babelMatcher: t.isCallExpression, parseNode: (node) => { return node; - }, - }), - ), + } + }) + ) ); return { @@ -389,14 +389,14 @@ export const namedFunctionCall = ( return { node, argument1Result: argument1Parser.parse(node.arguments[0], context), - argument2Result: argument2Parser?.parse(node.arguments[1], context), + argument2Result: argument2Parser?.parse(node.arguments[1], context) }; - }, + } }; }; export const isFunctionOrArrowFunctionExpression = ( - node: any, + node: any ): node is t.ArrowFunctionExpression | t.FunctionExpression => { return t.isArrowFunctionExpression(node) || t.isFunctionExpression(node); }; diff --git a/src/wrapParserResult.ts b/src/wrapParserResult.ts index ecc9ba3..74aafbf 100644 --- a/src/wrapParserResult.ts +++ b/src/wrapParserResult.ts @@ -1,5 +1,5 @@ -import * as t from "@babel/types"; -import { AnyParser } from "./types"; +import * as t from '@babel/types'; +import { AnyParser } from './types'; /** * Allows you to wrap a parser and reformulate @@ -7,7 +7,7 @@ import { AnyParser } from "./types"; */ export const wrapParserResult = ( parser: AnyParser, - changeResult: (result: Result, node: T) => NewResult | undefined, + changeResult: (result: Result, node: T) => NewResult | undefined ): AnyParser => { return { matches: parser.matches, @@ -15,6 +15,6 @@ export const wrapParserResult = ( const result = parser.parse(node, context); if (!result) return undefined; return changeResult(result, node); - }, + } }; }; diff --git a/tsconfig.json b/tsconfig.json index 3108163..947755d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,18 +14,11 @@ "experimentalDecorators": true, "skipLibCheck": true, "jsx": "react", - "lib": [ - "es6", - "dom" - ], + "lib": ["es6", "dom"], "strictPropertyInitialization": true, "outDir": "./lib", - "rootDir": "./src", + "rootDir": "./src" }, - "include": [ - "src", - ], - "exclude": [ - "node_modules" - ] -} \ No newline at end of file + "include": ["src"], + "exclude": ["node_modules"] +} diff --git a/yarn.lock b/yarn.lock index d7cae9b..8890cfa 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1494,7 +1494,15 @@ agent-base@6: dependencies: debug "4" -ansi-escapes@^4.2.1: +aggregate-error@^3.0.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/aggregate-error/-/aggregate-error-3.1.0.tgz#92670ff50f5359bdb7a3e0d40d0ec30c5737687a" + integrity sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA== + dependencies: + clean-stack "^2.0.0" + indent-string "^4.0.0" + +ansi-escapes@^4.2.1, ansi-escapes@^4.3.0: version "4.3.2" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.2.tgz#6b2291d1db7d98b6521d5f1efa42d0f3a9feb65e" integrity sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ== @@ -1506,6 +1514,11 @@ ansi-regex@^5.0.0: resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.0.tgz#388539f55179bf39339c81af30a654d69f87cb75" integrity sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg== +ansi-regex@^6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.0.1.tgz#3183e38fae9a65d7cb5e53945cd5897d0260a06a" + integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== + ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" @@ -1525,6 +1538,11 @@ ansi-styles@^5.0.0: resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-5.2.0.tgz#07449690ad45777d1924ac2abb2fc8895dba836b" integrity sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA== +ansi-styles@^6.0.0: + version "6.1.0" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-6.1.0.tgz#87313c102b8118abd57371afab34618bf7350ed3" + integrity sha512-VbqNsoz55SYGczauuup0MFUyXNQviSpFTj1RQtFzmQLk18qbVSpTFFGMT293rmDaQuKCT6InmbuEyUne4mTuxQ== + anymatch@^3.0.3: version "3.1.2" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.2.tgz#c0557c096af32f106198f4f4e2a383537e378716" @@ -1540,6 +1558,11 @@ argparse@^1.0.7: dependencies: sprintf-js "~1.0.2" +astral-regex@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-2.0.0.tgz#483143c567aeed4785759c0865786dc77d7d2e31" + integrity sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ== + asynckit@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" @@ -1750,6 +1773,34 @@ cjs-module-lexer@^1.0.0: resolved "https://registry.yarnpkg.com/cjs-module-lexer/-/cjs-module-lexer-1.2.1.tgz#2fd46d9906a126965aa541345c499aaa18e8cd73" integrity sha512-jVamGdJPDeuQilKhvVn1h3knuMOZzr8QDnpk+M9aMlCaMkTDd6fBWPhiDqFvFZ07pL0liqabAiuy8SY4jGHeaw== +clean-stack@^2.0.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-2.2.0.tgz#ee8472dbb129e727b31e8a10a427dee9dfe4008b" + integrity sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A== + +cli-cursor@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-3.1.0.tgz#264305a7ae490d1d03bf0c9ba7c925d1753af307" + integrity sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw== + dependencies: + restore-cursor "^3.1.0" + +cli-truncate@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/cli-truncate/-/cli-truncate-2.1.0.tgz#c39e28bf05edcde5be3b98992a22deed5a2b93c7" + integrity sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg== + dependencies: + slice-ansi "^3.0.0" + string-width "^4.2.0" + +cli-truncate@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/cli-truncate/-/cli-truncate-3.1.0.tgz#3f23ab12535e3d73e839bb43e73c9de487db1389" + integrity sha512-wfOBkjXteqSnI59oPcJkcPl/ZmwvMMOj340qUIY1SKZCv0B9Cf4D4fAucRkIKQmsIuYK3x1rrgU7MeGRruiuiA== + dependencies: + slice-ansi "^5.0.0" + string-width "^5.0.0" + cliui@^7.0.2: version "7.0.4" resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f" @@ -1798,6 +1849,11 @@ colorette@^1.2.2: resolved "https://registry.yarnpkg.com/colorette/-/colorette-1.2.2.tgz#cbcc79d5e99caea2dbf10eb3a26fd8b3e6acfa94" integrity sha512-MKGMzyfeuutC/ZJ1cba9NqcNpfeqMUcYmyF1ZFY6/Cn7CNSAKx6a+s48sqLqyAiZuaP2TcqMhoo+dlwFnVxT9w== +colorette@^2.0.16: + version "2.0.16" + resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.16.tgz#713b9af84fdb000139f04546bd4a93f62a5085da" + integrity sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g== + combined-stream@^1.0.8: version "1.0.8" resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" @@ -1805,6 +1861,11 @@ combined-stream@^1.0.8: dependencies: delayed-stream "~1.0.0" +commander@^8.3.0: + version "8.3.0" + resolved "https://registry.yarnpkg.com/commander/-/commander-8.3.0.tgz#4837ea1b2da67b9c616a67afbb0fafee567bca66" + integrity sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww== + concat-map@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" @@ -1892,6 +1953,13 @@ debug@^4.1.0: dependencies: ms "2.1.2" +debug@^4.3.3: + version "4.3.3" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.3.tgz#04266e0b70a98d4462e6e288e38259213332b664" + integrity sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q== + dependencies: + ms "2.1.2" + decimal.js@^10.2.1: version "10.3.1" resolved "https://registry.yarnpkg.com/decimal.js/-/decimal.js-10.3.1.tgz#d8c3a444a9c6774ba60ca6ad7261c3a94fd5e783" @@ -1946,6 +2014,11 @@ domexception@^2.0.1: dependencies: webidl-conversions "^5.0.0" +eastasianwidth@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/eastasianwidth/-/eastasianwidth-0.2.0.tgz#696ce2ec0aa0e6ea93a397ffcf24aa7840c827cb" + integrity sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA== + electron-to-chromium@^1.3.723: version "1.3.770" resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.770.tgz#a9e705a73315f4900880622b3ab76cf1d7221b77" @@ -1961,6 +2034,11 @@ emoji-regex@^8.0.0: resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== +emoji-regex@^9.2.2: + version "9.2.2" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-9.2.2.tgz#840c8803b0d8047f4ff0cf963176b32d4ef3ed72" + integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== + escalade@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.1.tgz#d8cfdc7000965c5a0174b4a82eaa5c0552742e40" @@ -2003,7 +2081,7 @@ esutils@^2.0.2: resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== -execa@^5.0.0: +execa@^5.0.0, execa@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/execa/-/execa-5.1.1.tgz#f80ad9cbf4298f7bd1d4c9555c21e93741c411dd" integrity sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg== @@ -2214,6 +2292,11 @@ human-signals@^2.1.0: resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-2.1.0.tgz#dc91fcba42e4d06e4abaed33b3e7a3c02f514ea0" integrity sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw== +husky@>=6: + version "7.0.4" + resolved "https://registry.yarnpkg.com/husky/-/husky-7.0.4.tgz#242048245dc49c8fb1bf0cc7cfb98dd722531535" + integrity sha512-vbaCKN2QLtP/vD4yvs6iz6hBEo6wkSzs8HpRah1Z6aGmF2KW5PdYuAd7uX5a+OyBZHBhd+TFLqgjUgytQr4RvQ== + iconv-lite@0.4.24: version "0.4.24" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" @@ -2234,6 +2317,11 @@ imurmurhash@^0.1.4: resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" integrity sha1-khi5srkoojixPcT7a21XbyMUU+o= +indent-string@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-4.0.0.tgz#624f8f4497d619b2d9768531d58f4122854d7251" + integrity sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg== + inflight@^1.0.4: version "1.0.6" resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" @@ -2278,6 +2366,11 @@ is-fullwidth-code-point@^3.0.0: resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== +is-fullwidth-code-point@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz#fae3167c729e7463f8461ce512b080a49268aa88" + integrity sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ== + is-generator-fn@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/is-generator-fn/-/is-generator-fn-2.1.0.tgz#7d140adc389aaf3011a8f2a2a4cfa6faadffb118" @@ -2875,6 +2968,44 @@ levn@~0.3.0: prelude-ls "~1.1.2" type-check "~0.3.2" +lilconfig@2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/lilconfig/-/lilconfig-2.0.4.tgz#f4507d043d7058b380b6a8f5cb7bcd4b34cee082" + integrity sha512-bfTIN7lEsiooCocSISTWXkiWJkRqtL9wYtYy+8EK3Y41qh3mpwPU0ycTOgjdY9ErwXCc8QyrQp82bdL0Xkm9yA== + +lint-staged@>=10: + version "12.3.4" + resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-12.3.4.tgz#4b1ff8c394c3e6da436aaec5afd4db18b5dac360" + integrity sha512-yv/iK4WwZ7/v0GtVkNb3R82pdL9M+ScpIbJLJNyCXkJ1FGaXvRCOg/SeL59SZtPpqZhE7BD6kPKFLIDUhDx2/w== + dependencies: + cli-truncate "^3.1.0" + colorette "^2.0.16" + commander "^8.3.0" + debug "^4.3.3" + execa "^5.1.1" + lilconfig "2.0.4" + listr2 "^4.0.1" + micromatch "^4.0.4" + normalize-path "^3.0.0" + object-inspect "^1.12.0" + string-argv "^0.3.1" + supports-color "^9.2.1" + yaml "^1.10.2" + +listr2@^4.0.1: + version "4.0.4" + resolved "https://registry.yarnpkg.com/listr2/-/listr2-4.0.4.tgz#d098a1c419284fb26e184b5d5889b235e8912245" + integrity sha512-vJOm5KD6uZXjSsrwajr+mNacIjf87gWvlBEltPWLbTkslUscWAzquyK4xfe9Zd4RDgO5nnwFyV06FC+uVR+5mg== + dependencies: + cli-truncate "^2.1.0" + colorette "^2.0.16" + log-update "^4.0.0" + p-map "^4.0.0" + rfdc "^1.3.0" + rxjs "^7.5.4" + through "^2.3.8" + wrap-ansi "^7.0.0" + locate-path@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" @@ -2897,6 +3028,16 @@ lodash@^4.7.0: resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== +log-update@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/log-update/-/log-update-4.0.0.tgz#589ecd352471f2a1c0c570287543a64dfd20e0a1" + integrity sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg== + dependencies: + ansi-escapes "^4.3.0" + cli-cursor "^3.1.0" + slice-ansi "^4.0.0" + wrap-ansi "^6.2.0" + lru-cache@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" @@ -3007,6 +3148,11 @@ nwsapi@^2.2.0: resolved "https://registry.yarnpkg.com/nwsapi/-/nwsapi-2.2.0.tgz#204879a9e3d068ff2a55139c2c772780681a38b7" integrity sha512-h2AatdwYH+JHiZpv7pt/gSX1XoRGb7L/qSIeuqA6GwYoF9w1vP1cw42TO0aI2pNyshRK5893hNSl+1//vHK7hQ== +object-inspect@^1.12.0: + version "1.12.0" + resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.0.tgz#6e2c120e868fd1fd18cb4f18c31741d0d6e776f0" + integrity sha512-Ho2z80bVIvJloH+YzRmpZVQe87+qASmBUKZDWgx9cu+KDrX2ZDH/3tMy+gXbZETVGs2M8YdxObOh7XAtim9Y0g== + object-keys@^1.0.12, object-keys@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" @@ -3029,7 +3175,7 @@ once@^1.3.0: dependencies: wrappy "1" -onetime@^5.1.2: +onetime@^5.1.0, onetime@^5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.2.tgz#d0e96ebb56b07476df1dd9c4806e5237985ca45e" integrity sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg== @@ -3080,6 +3226,13 @@ p-locate@^4.1.0: dependencies: p-limit "^2.2.0" +p-map@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/p-map/-/p-map-4.0.0.tgz#bb2f95a5eda2ec168ec9274e06a747c3e2904d2b" + integrity sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ== + dependencies: + aggregate-error "^3.0.0" + p-try@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" @@ -3158,6 +3311,11 @@ prelude-ls@~1.1.2: resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54" integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ= +prettier@^2.5.1: + version "2.5.1" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.5.1.tgz#fff75fa9d519c54cf0fce328c1017d94546bc56a" + integrity sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg== + pretty-format@^26.0.0, pretty-format@^26.6.2: version "26.6.2" resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-26.6.2.tgz#e35c2705f14cb7fe2fe94fa078345b444120fc93" @@ -3274,6 +3432,19 @@ resolve@^1.14.2, resolve@^1.20.0: is-core-module "^2.2.0" path-parse "^1.0.6" +restore-cursor@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-3.1.0.tgz#39f67c54b3a7a58cea5236d95cf0034239631f7e" + integrity sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA== + dependencies: + onetime "^5.1.0" + signal-exit "^3.0.2" + +rfdc@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/rfdc/-/rfdc-1.3.0.tgz#d0b7c441ab2720d05dc4cf26e01c89631d9da08b" + integrity sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA== + rimraf@^2.6.3: version "2.7.1" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" @@ -3288,6 +3459,13 @@ rimraf@^3.0.0: dependencies: glob "^7.1.3" +rxjs@^7.5.4: + version "7.5.4" + resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-7.5.4.tgz#3d6bd407e6b7ce9a123e76b1e770dc5761aa368d" + integrity sha512-h5M3Hk78r6wAheJF0a5YahB1yRQKCsZ4MsGdZ5O9ETbVtjPcScGfrMmoOq7EBsCRzd4BDkvDJ7ogP8Sz5tTFiQ== + dependencies: + tslib "^2.1.0" + safe-buffer@~5.1.1: version "5.1.2" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" @@ -3371,6 +3549,32 @@ slash@^3.0.0: resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== +slice-ansi@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-3.0.0.tgz#31ddc10930a1b7e0b67b08c96c2f49b77a789787" + integrity sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ== + dependencies: + ansi-styles "^4.0.0" + astral-regex "^2.0.0" + is-fullwidth-code-point "^3.0.0" + +slice-ansi@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-4.0.0.tgz#500e8dd0fd55b05815086255b3195adf2a45fe6b" + integrity sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ== + dependencies: + ansi-styles "^4.0.0" + astral-regex "^2.0.0" + is-fullwidth-code-point "^3.0.0" + +slice-ansi@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-5.0.0.tgz#b73063c57aa96f9cd881654b15294d95d285c42a" + integrity sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ== + dependencies: + ansi-styles "^6.0.0" + is-fullwidth-code-point "^4.0.0" + source-map-support@^0.5.6: version "0.5.19" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.19.tgz#a98b62f86dcaf4f67399648c085291ab9e8fed61" @@ -3406,6 +3610,11 @@ stack-utils@^2.0.3: dependencies: escape-string-regexp "^2.0.0" +string-argv@^0.3.1: + version "0.3.1" + resolved "https://registry.yarnpkg.com/string-argv/-/string-argv-0.3.1.tgz#95e2fbec0427ae19184935f816d74aaa4c5c19da" + integrity sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg== + string-length@^4.0.1: version "4.0.2" resolved "https://registry.yarnpkg.com/string-length/-/string-length-4.0.2.tgz#a8a8dc7bd5c1a82b9b3c8b87e125f66871b6e57a" @@ -3423,6 +3632,15 @@ string-width@^4.1.0, string-width@^4.2.0: is-fullwidth-code-point "^3.0.0" strip-ansi "^6.0.0" +string-width@^5.0.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.1.0.tgz#5ab00980cfb29f43e736b113a120a73a0fb569d3" + integrity sha512-7x54QnN21P+XL/v8SuNKvfgsUre6PXpN7mc77N3HlZv+f1SBRGmjxtOud2Z6FZ8DmdkD/IdjCaf9XXbnqmTZGQ== + dependencies: + eastasianwidth "^0.2.0" + emoji-regex "^9.2.2" + strip-ansi "^7.0.1" + strip-ansi@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.0.tgz#0b1571dd7669ccd4f3e06e14ef1eed26225ae532" @@ -3430,6 +3648,13 @@ strip-ansi@^6.0.0: dependencies: ansi-regex "^5.0.0" +strip-ansi@^7.0.1: + version "7.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.0.1.tgz#61740a08ce36b61e50e65653f07060d000975fb2" + integrity sha512-cXNxvT8dFNRVfhVME3JAe98mkXDYN2O1l7jmcwMnOslDeESg1rF/OZMtK0nRAhiari1unG5cD4jG3rapUAkLbw== + dependencies: + ansi-regex "^6.0.1" + strip-bom@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-4.0.0.tgz#9c3505c1db45bcedca3d9cf7a16f5c5aa3901878" @@ -3461,6 +3686,11 @@ supports-color@^8.0.0: dependencies: has-flag "^4.0.0" +supports-color@^9.2.1: + version "9.2.1" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-9.2.1.tgz#599dc9d45acf74c6176e0d880bab1d7d718fe891" + integrity sha512-Obv7ycoCTG51N7y175StI9BlAXrmgZrFhZOb0/PyjHBher/NmsdBgbbQ1Inhq+gIhz6+7Gb+jWF2Vqi7Mf1xnQ== + supports-hyperlinks@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/supports-hyperlinks/-/supports-hyperlinks-2.2.0.tgz#4f77b42488765891774b70c79babd87f9bd594bb" @@ -3496,6 +3726,11 @@ throat@^6.0.1: resolved "https://registry.yarnpkg.com/throat/-/throat-6.0.1.tgz#d514fedad95740c12c2d7fc70ea863eb51ade375" integrity sha512-8hmiGIJMDlwjg7dlJ4yKGLK8EsYqKgPWbG3b4wjJddKNwc7N7Dpn08Df4szr/sZdMVeOstrdYSsqzX6BYbcB+w== +through@^2.3.8: + version "2.3.8" + resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" + integrity sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU= + tmp@^0.0.33: version "0.0.33" resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" @@ -3536,6 +3771,11 @@ tr46@^2.1.0: dependencies: punycode "^2.1.1" +tslib@^2.1.0: + version "2.3.1" + resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" + integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== + type-check@~0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72" @@ -3673,6 +3913,15 @@ word-wrap@~1.2.3: resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c" integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== +wrap-ansi@^6.2.0: + version "6.2.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz#e9393ba07102e6c91a3b221478f0257cd2856e53" + integrity sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + wrap-ansi@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" @@ -3727,6 +3976,11 @@ yallist@^4.0.0: resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== +yaml@^1.10.2: + version "1.10.2" + resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.2.tgz#2301c5ffbf12b467de8da2333a459e29e7920e4b" + integrity sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg== + yargs-parser@^20.2.2: version "20.2.9" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.9.tgz#2eb7dc3b0289718fc295f362753845c41a0c94ee"