Giter Site home page Giter Site logo

daltonmenezes / interprocess Goto Github PK

View Code? Open in Web Editor NEW
93.0 2.0 2.0 856 KB

๐Ÿ’ฌโ€A scalable and type-safe Electron IPC management tool with enhanced DX

Home Page: https://interprocess.daltonmenezes.com

License: MIT License

Shell 0.11% TypeScript 88.26% HTML 1.42% JavaScript 1.71% MDX 8.49%
electron dx interprocess-communication ipc scalable type-safe typescript

interprocess's People

Contributors

daltonmenezes avatar guilherssousa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

interprocess's Issues

error when `main` or `renderer` option is `undefined`

description

main and renderer options will make an error if one of them is empty. but the type says that both are optional.

image

example

invalid (will produce the error above)

const { ipcMain, ipcRenderer, exposeApiToGlobalWindow } = createInterprocess({
  main: {},
})

valid

const { ipcMain, ipcRenderer, exposeApiToGlobalWindow } = createInterprocess({
  main: {},
  renderer: {},
})

Dev environment documentation won't open on Windows

Thanks to Windows using backslashes instead of forward slashes in paths, the documentation won't open on development environment.

This is a sample value from a parsedDocPaths item, executed on /docs/ getStaticPaths.

{
    path: '\\getting-started\\overview.mdx',
    fullPath: 'D:\\git\\interprocess\\apps\\web\\docs\\getting-started\\overview.mdx',
    url: 'D:\\git\\interprocess\\apps\\web\\docs\\getting-started\\overview',
    slug: 'overview'
}

When spliting data to generate the final paths on the getStaticPaths function, a / is used as separator, but this won't work on Windows, since it uses backslashes:

export const getStaticPaths: GetStaticPaths = async () => {
  const docs = await getParsedDocPaths()

  const paths = docs.map((doc) => ({
    params: {
      doc: doc.url.split('/'),
    },
  }))

  return { paths, fallback: false }
}

A very straightforward method to solve this is to use a .replace method after path resolving, to ensure all separators are POSIX's forward slashes, but this may have edge cases that shoundn't be handled on frontend. So I suggest adding the normalize-path package, which has only 331B gzipped+minified and deals with known edge cases.

After the function being used, the sample function returns:

{
    path: '/getting-started/overview.mdx',
    fullPath: 'D:/git/interprocess/apps/web/getting-started/overview.mdx',
    url: 'getting-started/overview',
    slug: 'overview'
}

I wrote a PR that adds the dependency, its type definitions and solves the problem: #11

sandbox option

Hey there! What an awesome project here, thank you for the great work.
I have just one question about the sandbox option. You use contextBridge and all setup required to make sandbox enabled but your documentation say that it need to be false.
There is no way to use Interprocess with sandbox enabled? I need to keep my app securised with sandbox, but it really hard to have typescript definitions for ipc events.
Thank you!

Using main objects in the handler

I am not sure to fully understand the correct usage of the interprocess library.

Let's have a situation where your main electron process have some objects instance, for example a connection and allow to get some data from a database. This connection object is created in the src/main/index.ts file inside the createWindow function.

Now, I want to create a getData channel, fully typed, however in my src/shared/ipcs/index.ts, when I am running the createInterprocess I do not have access to the main objects.

On this desktop example there is the following

export function registerIpcHandlers(window: Electron.BrowserWindow) {
// execute the getPing registration with another handler and use the previous handler lazily if needed to perform some other tasks
handle.getPing(async (_, { getPing, data }) => {
const response = await getPing(_, data)
console.log(response)
// invoke the getPong from renderer process
await invoke.getPong(window, 'pong')
// remove the getPing IPC handler
remove.getPing()
return 'The getPong ipc was removed'
})

It seems that it is possible to redefine the handler, but what's should the other one return if it is something that should never be used (because no access to the database object) ?

Is there a reason for not using a proprietary documentation generator?

Title basically explains. Currently, the preject uses its own documentation generator built with Next.js, but there is a reason for not using a generator like Nextra, Docussaurus or Mintlify? Based on the project's development stage, it's way more suitable to use already battle-tested tools to build this parts that are not inherently related to the main project.

I was looking forward to contribute writing the documentations, but during the readings to spot some field to improve, I found that there are a bunch of things, specially Accessibility related like Line heights, ARIA attributes, layout shifts happening on the website.

It woundn't make more sense to use one of these previously mentioned tools to simplify the documenting process, leaving more time to spend on the main library development?

Unable to declare multiple parameters

Hi, according to type definitions, we can't use multiple parameters on main handlers however, multiple parameters are getting passed at runtime.

Here's an example

export const {
  ipcMain,
  ipcRenderer,
  exposeApiToGlobalWindow
} = createInterprocess({
  main: {
    async test(_, param1: string, param2: string) {
      return param1 + param2;
    }
  },

  renderer: {},
});

and the error
image

The only workaround is expecting an object with parameters/props. I'm not fan of using object for some curtain cases and it'd be best to have this DX improvement.

How to use this project with IoC ?

Hello,

this project is very promising, congrats โœจ

I'm wondering how to use it in a project that follows the Inversion of Control principle (through dependency injection).

Instead of this structure :

export const getPingIpcSlice = createIpcSlice({
  main: {
    async getPing(_, data: 'ping') {
      return `from renderer: ${data} on main process`
    },
  },
})

I have something like :

export class MyController {
  constructor(private myService: MyService) {}

  async getPing(_, data: 'ping') {
    const res = await this.myService.doSomething(data)
    return `from renderer: ${res} on main process`
  }
}

But with this I don't see how I can import these methods into a shared file that uses combineIpcs.
What do you think ?

`Module parse failed: Unexpected token` error

vue2 + electron-builder, and compilation error:

1

here are compilation packages info:

yarn list ts-loader
yarn list v1.22.19
warning Filtering by arguments is deprecated. Please use the pattern option instead.
โ”œโ”€ @vue/[email protected]
โ”‚  โ””โ”€ [email protected]
โ””โ”€ [email protected]

yarn list webpack
yarn list v1.22.19
warning Filtering by arguments is deprecated. Please use the pattern option instead.
โ”œโ”€ [email protected]
โ”‚  โ””โ”€ [email protected]
โ””โ”€ [email protected]

yarn list vue
yarn list v1.22.19
warning Filtering by arguments is deprecated. Please use the pattern option instead.
โ””โ”€ [email protected]

i tried to modify vue.config.js, but i got the same error.

configureWebpack: {
    module: {
      rules: [
        {
          include: /node_modules\/interprocess/,
          use: [
            {
              loader: 'ts-loader',
              options: {
                context: path.resolve(__dirname, './'),
                configFile: 'tsconfig.json',
              },
            },
          ],
        },
      ],
    },
  },

Typescript bug around empty parameters

Given this example:

import { createInterprocess } from '../interprocess';

export const { ipcMain: utilsIpcMain, ipcRenderer: utilsIpcRenderer } = createInterprocess({
  main: {
    /**
     * Returns the electron application version
     */
    async getElectronVersion() {
      return '1.0.0';
    },
  },
  renderer: {
    /**
     * Prints a log message in the frontend console.
     * The first parameter is always an IPC event object.
     */
    async logMessage(_, _msg: string) {
      return;
    },
  },
});

If I want to implement the invoker directly to the context bridge:

import { contextBridge } from 'electron';
import { utilsIpcRenderer } from '../ipc/handlers/utils.ipc';

const api = {
  utils: {
    // typescript complains about the first parameter even though the handler is defined without any params
    // so I have to satisfy it by using undefined
    getElectronVersion: () => utilsIpcRenderer.invoke.getElectronVersion(undefined),
    onLogMessage: (callback) => {
      utilsIpcRenderer.handle.logMessage(async (_, { data: msg }) => {
        callback(msg);
      });
    },
  },
};

try {
  contextBridge.exposeInMainWorld('native', api);
} catch (error) {
  console.error(error);
}

image

  • I'm using Typescript 4.9.5
  • I'm not using the package installed as an npm module but copied the src files to my project to get around sandbox: true limitations

Typescript bug around types/index.ts

This is with me copying the src files directly to my project to get around sandbox: true, and using typescript 4.9.

The IPC type doesn't do anything with the infer variables, so TS complains.

image

SVG backgrounds cause performance issues with Ultrawide monitors

Hi Dalton, I've been looking to your project since the very early days you open sourced it.

Many were the times I opened up the project homepages, I felt like there was something on it that was draining my PC RAM, but I never thought of diagnosing this myself to write a Issue because I knew the project was recently released, so these kind of problems would be normal.

But here I am again, I felt the browser rally slow after opening the website, but today I took a time to fork and clone the repo to find where this performance issue is coming from, here's what I found:

Your <Background /> component from apps\web\src\components\Layout\Background\index.ts has a background-image rule that renders a really big vector (1878x1500) that contains a bunch of logo repetitions and some blurred colors to add more brand.

The problem is, really big and complex SVGs brings bad performance, thanks to their rendering nature, especially for big monitors that have to replicate these graphs all over their big screens.

Solution

I forked your project and made some alterations to solve this problem: guilherssousa/interprocess

Instead of using this single big vector, what I did was separating the two contents in different files: blur.jpg (17 kB) and pattern.svg (1 kB) (you can view the new Background styles file here)

Also in this repo I fixed some typos on documentation and removed a unused import, I haven't opened a PR yet because of community guidelines about contributing. Hope it helps your ultrawide monitor users.

Unsubscribe from handle

Hi, is there a way to unsubscribe from an event?
Let's say, I have the following methods

// ipcs.ts

export const {
  ipcMain,
  ipcRenderer,
  exposeApiToGlobalWindow
} = createInterprocess({
  main: {
    async doSomething() {
      console.log('some logic here and call window');

      const mainWindow = BrowserWindow.getAllWindows().find(
        window => window.title === '[main]'
      );

      if (mainWindow) {
        ipcMain.invoke.sendToWindow(mainWindow, `here's the data`);
      }
    }
  },

  renderer: {
    async sendToWindow(_, data: string) {
      console.log('incoming data', data);
    }
  },
});
// renderer.ts

window.api.handle.sendToWindow(async () => {
  console.log('this is second handler');
  window.api.remove.sendToWindow();
})
window.api.invoke.doSomething();
setTimeout(() => {
  window.api.invoke.doSomething();
}, 5000)

When it runs, the first callback suppose to remove sendToWindow and then after 5 seconds, it should pop an error says, there's no handler available but it doesn't. Because the latest event handler window.api.handle.sendToWindow(async () => { }); has been registered in memory.
I believe this can also cause memory leak issue.

Can a handle call window.api.handle.sendToWindow(async () => {}); return a function to unsubscribe itself later on?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.