Any way to run editor code in safe mode?

Short of writing an entirely standalone executable, is there any way to run code when a project is in safe mode?

We have shared libraries that rely on certain packages to be installed, and we could easily resolve many safe mode errors by checking if the packages exist, and if not, installing them through the package manager API. But, we cannot seem to run any code in safe mode to make this happen.

Is it possible?

OR, is there any way to assign and resolve dependencies when we are using assemblies (with assembly definitions in Unity) that rely on things like com_unity_nuget_newtonsoft-json, but our library isn’t being distributed through Package-Manager?

Last time I checked, the safe mode used a built-in whitelist of packages that are allowed to run, with no mechanism to influence it.

The only way I can see is to use Define Constraints and Version Defines on your Assembly Definitions to only conditionally include the code that depends on your potentially missing dependencies. So that your libraries disable themselves when those dependencies are not included, without causing any compiler errors.

Then you can add an additional assembly definition that uses the reverse conditions, runs when any dependencies are missing, and prompts the user to install them / installs them automatically.

You could launch the editor with -ignoreCompilerErrors to bypass the safe mode.

Alternatively, you can disable it in Preferences: Asset Pipeline => Show Enter Safe Mode Dialog

Safe mode behaviour is explained in the manual

If the issue is really pervasive and you cannot disable safe mode (eg customers) then you have to do what Adrian said, namely using Version Defines to disable any dependent code. This however can quickly result in a high complexity and lots of code that’s enclosed in preprocessor conditionals. I would rather opt for creating my own, custom importer for those packages.

You could request that users only install “your library X” via an associated editor menu item or external tool. This would then read the library’s dependency requirements from its provided json, and compare it with manifest.json to see which dependencies are missing, and the missing ones are injected into manifest.json. Modifying manifest.json should automatically trigger an import but if not, you may have to call AssetDatabase.ImportAsset("Packages/manifest.json") or call RequestScriptCompilation.