@prosopo/config 0.2.11 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,212 @@
1
+ import { AliasOptions, UserConfig } from 'vite'
2
+ import { default as ClosePlugin } from './vite-plugin-close-and-copy.js'
3
+ import { builtinModules } from 'module'
4
+ import { filterDependencies, getDependencies } from '../dependencies.js'
5
+ import { getLogger } from '@prosopo/common'
6
+ import { nodeResolve } from '@rollup/plugin-node-resolve'
7
+ import { viteStaticCopy } from 'vite-plugin-static-copy'
8
+ import { wasm } from '@rollup/plugin-wasm'
9
+ import VitePluginFixAbsoluteImports from './vite-plugin-fix-absolute-imports.js'
10
+ import css from 'rollup-plugin-import-css'
11
+ import nativePlugin from 'rollup-plugin-natives'
12
+ import path from 'path'
13
+ import replace from 'vite-plugin-filter-replace'
14
+
15
+ const logger = getLogger(`Info`, `vite.backend.config.js`)
16
+
17
+ const nodeJsPolarsDeps = [
18
+ 'nodejs-polars.android-arm64.node',
19
+ 'nodejs-polars.android-arm-eabi.node',
20
+ 'nodejs-polars.win32-x64-msvc.node',
21
+ 'nodejs-polars.win32-ia32-msvc.node',
22
+ 'nodejs-polars.win32-arm64-msvc.node',
23
+ 'nodejs-polars.darwin-x64.node',
24
+ 'nodejs-polars.darwin-arm64.node',
25
+ 'nodejs-polars.freebsd-x64.node',
26
+ 'nodejs-polars.linux-x64-musl.node',
27
+ //'nodejs-polars.linux-x64-gnu.node', // - this is the only file that will be present
28
+ 'nodejs-polars.linux-arm64-musl.node',
29
+ 'nodejs-polars.linux-arm64-gnu.node',
30
+ 'nodejs-polars.linux-arm-gnueabihf.node',
31
+ ]
32
+
33
+ const aliasOptions: AliasOptions = [
34
+ // Replace the nodejs-polars dependency with the copied .node file to avoid complaints when bundling
35
+ ...nodeJsPolarsDeps.map((dep) => ({
36
+ find: `./${dep}`,
37
+ replacement: 'nodejs-polars.linux-x64-gnu.node',
38
+ })),
39
+ ]
40
+
41
+ export default async function (
42
+ packageName: string,
43
+ packageVersion: string,
44
+ bundleName: string,
45
+ packageDir: string,
46
+ entry: string,
47
+ command?: string,
48
+ mode?: string
49
+ ): Promise<UserConfig> {
50
+ // Get all dependencies of the current package
51
+ const { dependencies: deps, optionalPeerDependencies } = await getDependencies(packageName, true)
52
+
53
+ // Assuming node_modules are at the root of the workspace
54
+ const baseDir = path.resolve('../..')
55
+ const nodeModulesDir = path.resolve(baseDir, 'node_modules')
56
+
57
+ // Output directory is relative to directory of the package
58
+ const outDir = path.resolve(packageDir, 'dist/bundle')
59
+
60
+ // Get rid of any dependencies we don't want to bundle
61
+ const { external, internal } = filterDependencies(deps, ['aws', 'webpack', 'vite', 'eslint'])
62
+
63
+ // Add the node builtins (path, fs, os, etc.) to the external list
64
+ const allExternal = [
65
+ ...builtinModules,
66
+ ...builtinModules.map((m) => `node:${m}`),
67
+ ...external,
68
+ ...optionalPeerDependencies,
69
+ ]
70
+
71
+ console.log('allExternal', allExternal)
72
+
73
+ logger.info(`Bundling. ${JSON.stringify(internal.slice(0, 10), null, 2)}... ${internal.length} deps`)
74
+
75
+ const nodeJsNodeFileToCopy = path.resolve(
76
+ nodeModulesDir,
77
+ './nodejs-polars-linux-x64-gnu/nodejs-polars.linux-x64-gnu.node'
78
+ )
79
+ logger.info(`.node files to copy ${nodeJsNodeFileToCopy}`)
80
+
81
+ const define = {
82
+ 'process.env.WS_NO_BUFFER_UTIL': 'true',
83
+ 'process.env.WS_NO_UTF_8_VALIDATE': 'true',
84
+ 'process.env.PROSOPO_PACKAGE_VERSION': JSON.stringify(packageVersion),
85
+ }
86
+
87
+ logger.info(`Defined vars ${JSON.stringify(define, null, 2)}`)
88
+
89
+ const entryAbsolute = path.resolve(packageDir, entry)
90
+
91
+ const packageNameShort = packageName.replace('@prosopo/', '')
92
+
93
+ const filterEntry = `^${baseDir}/packages/(?!${packageNameShort}/src/${entry.replace(
94
+ './src/',
95
+ ''
96
+ )}$)(?!.*/node_modules/.*$).*$`
97
+
98
+ return {
99
+ resolve: {
100
+ alias: aliasOptions,
101
+ },
102
+ ssr: {
103
+ noExternal: internal,
104
+ external: allExternal,
105
+ },
106
+ optimizeDeps: {
107
+ include: ['linked-dep', 'node_modules'],
108
+ esbuildOptions: {
109
+ loader: {
110
+ '.node': 'file',
111
+ },
112
+ },
113
+ },
114
+ esbuild: {
115
+ platform: 'node',
116
+ target: 'node16',
117
+ },
118
+ define,
119
+ build: {
120
+ outDir,
121
+ minify: false,
122
+ ssr: true,
123
+ target: 'node16',
124
+
125
+ lib: {
126
+ entry: entryAbsolute,
127
+ name: bundleName,
128
+ fileName: `${bundleName}.[name].bundle.js`,
129
+ formats: ['es'],
130
+ },
131
+ modulePreload: { polyfill: false },
132
+ commonjsOptions: {
133
+ ignore: function (id) {
134
+ // Ignore Executable and Linkable Format (ELF) files from being interpreted as CommonJS. These are
135
+ // .node files that contain WebAssembly code. They are not CommonJS modules.
136
+ return id.indexOf('nodejs-polars-linux-x64-gnu') > -1
137
+ },
138
+ },
139
+ rollupOptions: {
140
+ treeshake: 'smallest',
141
+ external: allExternal,
142
+ watch: false,
143
+ output: {
144
+ entryFileNames: `${bundleName}.[name].bundle.js`,
145
+ },
146
+
147
+ plugins: [
148
+ // This plugin copies .node files but doesn't work for nodejs-polars. Leaving it here in case it's
149
+ // useful in the future.
150
+ nativePlugin({
151
+ // Where we want to physically put the extracted .node files
152
+ copyTo: outDir,
153
+
154
+ // Path to the same folder, relative to the output bundle js
155
+ destDir: '.',
156
+
157
+ // Generate sourcemap
158
+ sourcemap: true,
159
+
160
+ // If the target is ESM, so we can't use `require` (and .node is not supported in `import` anyway), we will need to use `createRequire` instead.
161
+ targetEsm: true,
162
+ }),
163
+ css(),
164
+ wasm(),
165
+ nodeResolve(),
166
+ ],
167
+ },
168
+ },
169
+ plugins: [
170
+ // plugin to replace stuff like import blah from string_encoder/lib/string_encoder.js with import blah from string_encoder
171
+ VitePluginFixAbsoluteImports(),
172
+ replace.default([
173
+ // nodejs-polars is not being transformed by commonjsOptions (above) so we need to do a manual replace of
174
+ // __dirname here
175
+ {
176
+ filter: ['node_modules/nodejs-polars/bin/native-polars.js'],
177
+ replace: {
178
+ from: '__dirname',
179
+ to: "new URL(import.meta.url).pathname.split('/').slice(0,-1).join('/')",
180
+ },
181
+ },
182
+ // replace this import
183
+ {
184
+ filter: ['node_modules/nodejs-polars/bin/native-polars.js'],
185
+ replace: {
186
+ from: '__dirname',
187
+ to: "new URL(import.meta.url).pathname.split('/').slice(0,-1).join('/')",
188
+ },
189
+ },
190
+ // replace any references to main process where we are not expecting it
191
+ {
192
+ filter: new RegExp(filterEntry),
193
+ replace: {
194
+ from: 'esMain(import.meta)',
195
+ to: 'false',
196
+ },
197
+ },
198
+ ]),
199
+ // We need the .node files to be available to the bundle
200
+ viteStaticCopy({
201
+ targets: [
202
+ {
203
+ src: nodeJsNodeFileToCopy,
204
+ dest: outDir,
205
+ },
206
+ ],
207
+ }),
208
+ // plugin to close the bundle after build if not in serve mode
209
+ command !== 'serve' ? ClosePlugin() : undefined,
210
+ ],
211
+ }
212
+ }
@@ -0,0 +1,42 @@
1
+ import { UserConfig, defineConfig } from 'vite'
2
+ import { builtinModules } from 'module'
3
+ import { getExternalsFromReferences } from '../dependencies.js'
4
+ import { getLogger } from '@prosopo/common'
5
+ import { default as noBundlePlugin } from 'vite-plugin-no-bundle'
6
+ import VitePluginCloseAndCopy from './vite-plugin-close-and-copy.js'
7
+ import path from 'path'
8
+ import tsconfigPaths from 'vite-tsconfig-paths'
9
+ const log = getLogger(`Info`, `vite.commonjs.config.ts`)
10
+ export default async function (name: string, tsConfigPath: string, entry?: string): Promise<UserConfig> {
11
+ log.info(`ViteCommonJSConfig: ${name}`)
12
+ const projectExternal = await getExternalsFromReferences(tsConfigPath, [/dev/])
13
+ const allExternal = [...builtinModules, ...builtinModules.map((m) => `node:${m}`), ...projectExternal]
14
+ return defineConfig({
15
+ ssr: { external: allExternal },
16
+ plugins: [
17
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
18
+ // @ts-ignore
19
+ noBundlePlugin({
20
+ root: 'src',
21
+ copy: '**/*.css',
22
+ }),
23
+ tsconfigPaths({ projects: [path.resolve('./tsconfig.cjs.json')] }),
24
+ VitePluginCloseAndCopy(),
25
+ ],
26
+ build: {
27
+ emptyOutDir: true,
28
+ ssr: true,
29
+ target: 'node16',
30
+ outDir: 'dist/cjs',
31
+ lib: {
32
+ name,
33
+ formats: ['cjs'],
34
+ entry: entry || 'src/index.ts', // required
35
+ },
36
+ rollupOptions: {
37
+ treeshake: false,
38
+ external: allExternal,
39
+ },
40
+ },
41
+ })
42
+ }
@@ -0,0 +1,153 @@
1
+ import { ClosePluginOptions } from './vite-plugin-close-and-copy.js'
2
+ import { Drop } from 'esbuild'
3
+ import { UserConfig } from 'vite'
4
+ import { VitePluginCloseAndCopy } from './index.js'
5
+ import { builtinModules } from 'module'
6
+ import { filterDependencies, getDependencies } from '../dependencies.js'
7
+ import { getAliases } from '../polkadot/index.js'
8
+ import { getLogger } from '@prosopo/common'
9
+ import { nodeResolve } from '@rollup/plugin-node-resolve'
10
+ import { viteCommonjs } from '@originjs/vite-plugin-commonjs'
11
+ import { default as viteReact } from '@vitejs/plugin-react'
12
+ import { wasm } from '@rollup/plugin-wasm'
13
+ import css from 'rollup-plugin-import-css'
14
+ import path from 'path'
15
+ import viteTsconfigPaths from 'vite-tsconfig-paths'
16
+ const logger = getLogger(`Info`, `vite.config.js`)
17
+
18
+ export default async function (
19
+ packageName: string,
20
+ bundleName: string,
21
+ dir: string,
22
+ entry: string,
23
+ command?: string,
24
+ mode?: string,
25
+ copyOptions?: ClosePluginOptions,
26
+ tsConfigPaths?: string[]
27
+ ): Promise<UserConfig> {
28
+ logger.info(`Running at ${dir} in ${mode} mode`)
29
+ const isProduction = mode === 'production'
30
+ // NODE_ENV must be wrapped in quotes. We just set it to the mode and ignore what's in the env file, otherwise the
31
+ // mode and NODE_ENV can end up out of sync (one set to development and the other set to production, which causes
32
+ // issues like this: https://github.com/hashicorp/next-mdx-remote/pull/323
33
+ process.env.NODE_ENV = `${mode}`
34
+ logger.info(`NODE_ENV: ${process.env.NODE_ENV}`)
35
+
36
+ // Set the env vars that we want to be available in the browser
37
+ const define = {
38
+ // used to stop websockets package from breaking
39
+ 'process.env.WS_NO_BUFFER_UTIL': JSON.stringify('true'),
40
+ 'process.env.WS_NO_UTF_8_VALIDATE': JSON.stringify('true'),
41
+ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
42
+ 'process.env.PROTOCOL_CONTRACT_ADDRESS': JSON.stringify(process.env.PROTOCOL_CONTRACT_ADDRESS),
43
+ 'process.env.SUBSTRATE_NODE_URL': JSON.stringify(process.env.SUBSTRATE_NODE_URL),
44
+ 'process.env.DEFAULT_ENVIRONMENT': JSON.stringify(process.env.DEFAULT_ENVIRONMENT),
45
+ 'process.env.SERVER_URL': JSON.stringify(process.env.SERVER_URL),
46
+ // only needed if bundling with a site key
47
+ 'process.env.PROSOPO_SITE_KEY': JSON.stringify(process.env.PROSOPO_SITE_KEY),
48
+ }
49
+
50
+ logger.info(`Env vars: ${JSON.stringify(define, null, 4)}`)
51
+
52
+ // Get all dependencies of the current package
53
+ const { dependencies: deps, optionalPeerDependencies } = await getDependencies(packageName, isProduction)
54
+
55
+ // Get rid of any dependencies we don't want to bundle
56
+ const { external, internal } = filterDependencies(deps, ['pm2', 'nodejs-polars', 'aws', 'webpack', 'vite'])
57
+
58
+ // Add the node builtins (path, fs, os, etc.) to the external list
59
+ const allExternal = [
60
+ ...builtinModules,
61
+ ...builtinModules.map((m) => `node:${m}`),
62
+ ...external,
63
+ ...optionalPeerDependencies,
64
+ ]
65
+ logger.info(`Bundling. ${JSON.stringify(internal.slice(0, 10), null, 2)}... ${internal.length} deps`)
66
+ const alias = isProduction ? getAliases(dir) : []
67
+
68
+ // Required to print RegExp in console (e.g. alias keys)
69
+ const proto = RegExp.prototype as any
70
+ proto['toJSON'] = RegExp.prototype.toString
71
+ logger.info(`aliases ${JSON.stringify(alias, null, 2)}`)
72
+
73
+ // drop console logs if in production mode
74
+ const drop: Drop[] | undefined = mode === 'production' ? ['console', 'debugger'] : undefined
75
+
76
+ return {
77
+ server: {
78
+ host: '127.0.0.1',
79
+ },
80
+ mode: mode || 'development',
81
+ optimizeDeps: {
82
+ include: ['linked-dep', 'esm-dep > cjs-dep', 'node_modules'], //'node_modules'
83
+ //exclude: ['react', 'react-dom'],
84
+ },
85
+ esbuild: {
86
+ platform: 'browser',
87
+ target: ['es2020', 'chrome60', 'edge18', 'firefox60', 'node12', 'safari11'],
88
+ drop,
89
+ },
90
+ define,
91
+ // resolve: {
92
+ // alias,
93
+ // },
94
+
95
+ build: {
96
+ outDir: path.resolve(dir, 'dist/bundle'),
97
+ minify: isProduction,
98
+ ssr: false,
99
+ lib: {
100
+ entry: path.resolve(dir, entry),
101
+ name: bundleName,
102
+ fileName: `${bundleName}.bundle.js`,
103
+ // sets the bundle to an instantly invoked function expression (IIFE)
104
+ formats: ['iife'],
105
+ },
106
+ modulePreload: { polyfill: true },
107
+ commonjsOptions: {
108
+ exclude: ['mongodb/*'],
109
+ transformMixedEsModules: true,
110
+ },
111
+
112
+ rollupOptions: {
113
+ treeshake: 'smallest',
114
+ external: allExternal,
115
+ watch: false,
116
+ output: {
117
+ dir: path.resolve(dir, 'dist/bundle'),
118
+ entryFileNames: `${bundleName}.bundle.js`,
119
+ },
120
+
121
+ plugins: [
122
+ css(),
123
+ wasm(),
124
+ nodeResolve({
125
+ browser: true,
126
+ preferBuiltins: false,
127
+ rootDir: path.resolve(dir, '../../'),
128
+ dedupe: ['react', 'react-dom'],
129
+ }),
130
+ // I think we can use this plugin to build all packages instead of relying on the tsc step that's
131
+ // currently a precursor in package.json. However, it fails for the following reason:
132
+ // https://github.com/rollup/plugins/issues/243
133
+ // typescript({
134
+ // tsconfig: path.resolve('./tsconfig.json'),
135
+ // compilerOptions: { rootDir: path.resolve('./src') },
136
+ // }),
137
+ ],
138
+ },
139
+ },
140
+ plugins: [
141
+ // Not sure if we need this plugin or not, it works without it
142
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
143
+ // @ts-ignore
144
+ viteReact(),
145
+ viteCommonjs(),
146
+ // Closes the bundler and copies the bundle to the client-bundle-example project unless we're in serve
147
+ // mode, in which case we don't want to close the bundler because it will close the server
148
+ command !== 'serve' ? VitePluginCloseAndCopy(copyOptions) : undefined,
149
+ // Means we can specify index.tsx instead of index.jsx in the index.html file
150
+ viteTsconfigPaths({ projects: tsConfigPaths }),
151
+ ],
152
+ }
153
+ }
@@ -0,0 +1,29 @@
1
+ import { defineConfig } from 'vitest/config'
2
+ import VitePluginSourcemapExclude from './vite-plugin-sourcemap-exclude.js'
3
+
4
+ export default function () {
5
+ return defineConfig({
6
+ build: {
7
+ minify: false,
8
+ sourcemap: false,
9
+ rollupOptions: {
10
+ maxParallelFileOps: 1,
11
+ cache: false,
12
+ output: {
13
+ sourcemap: false,
14
+ },
15
+ },
16
+ },
17
+ test: {
18
+ include: ['../../packages/*/src/**/*.test.ts', '../../contracts/*/src/**/*.test.ts'],
19
+ exclude: ['../../demos/**/*'], // '../!packages/**/*'],
20
+ singleThread: true,
21
+ watchExclude: ['**/node_modules/**', '**/dist/**'],
22
+ logHeapUsage: true,
23
+ coverage: {
24
+ enabled: true,
25
+ },
26
+ },
27
+ plugins: [VitePluginSourcemapExclude({ excludeNodeModules: true })],
28
+ })
29
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "extends": "../../tsconfig.esm.json",
3
+ "compilerOptions": {
4
+ "rootDir": "./src",
5
+ "outDir": "./dist",
6
+ "types": ["vite/client"]
7
+ },
8
+ "include": ["./src/**/*.ts", "./src/**/*.d.ts", "./src/**/*.tsx"],
9
+ "references": [
10
+ {
11
+ "path": "../../packages/common"
12
+ },
13
+ {
14
+ "path": "../../packages/types"
15
+ }
16
+ ]
17
+ }