11const fs = require ( 'fs' )
22const path = require ( 'path' )
33
4- // Set production environment for the build
5- process . env . NEXT_PUBLIC_CB_ENVIRONMENT = 'prod'
6-
74const packageJsonPath = path . join ( __dirname , 'package.json' )
85const tempPackageJsonPath = path . join ( __dirname , 'temp.package.json' )
96const indexJsPath = path . join ( __dirname , 'dist' , 'index.js' )
@@ -22,12 +19,8 @@ for (const depType of ['dependencies', 'optionalDependencies']) {
2219 if ( typeof version === 'string' && version . startsWith ( 'workspace:' ) ) {
2320 if ( pkgName === 'common' ) {
2421 delete packageJson [ depType ] [ pkgName ]
25- console . log (
26- `Removed dependency on ${ pkgName } because it's now bundled.`
27- )
2822 } else {
2923 packageJson [ depType ] [ pkgName ] = '1.0.0'
30- console . warn ( `No version found for ${ pkgName } , defaulting to 1.0.0` )
3124 }
3225 }
3326 }
@@ -44,11 +37,25 @@ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
4437if ( fs . existsSync ( indexJsPath ) ) {
4538 let indexJsContent = fs . readFileSync ( indexJsPath , 'utf8' )
4639
40+ // Dynamically get client-side environment variables from env.ts
41+ const envTsContent = fs . readFileSync (
42+ path . join ( __dirname , '..' , 'env.ts' ) ,
43+ 'utf8'
44+ )
45+ const clientKeysMatch = envTsContent . match ( / c l i e n t : { ( [ ^ ] * ?) } / s)
46+ let clientKeys = [ ]
47+ if ( clientKeysMatch ) {
48+ clientKeys =
49+ clientKeysMatch [ 1 ]
50+ . split ( '\n' )
51+ . map ( ( line ) => line . match ( / ^ \s * ( \w + ) : / ) )
52+ . filter ( Boolean )
53+ . map ( ( match ) => match [ 1 ] ) ?? [ ]
54+ }
55+
4756 // Get all environment variables that start with NEXT_PUBLIC_ or are needed for the npm package
4857 const envVarsToInject = Object . entries ( process . env )
49- . filter (
50- ( [ key , value ] ) => key . startsWith ( 'NEXT_PUBLIC_' ) && value !== undefined
51- )
58+ . filter ( ( [ key , value ] ) => clientKeys . includes ( key ) && value !== undefined )
5259 . map ( ( [ key , value ] ) => `process.env.${ key } = '${ value } ';` )
5360
5461 const lines = indexJsContent . split ( '\n' )
@@ -57,12 +64,9 @@ if (fs.existsSync(indexJsPath)) {
5764 indexJsContent = lines . join ( '\n' )
5865 fs . writeFileSync ( indexJsPath , indexJsContent )
5966 console . log (
60- `Injected ${ envVarsToInject . length } environment variables into index.js`
67+ `Injected ${ envVarsToInject . length } environment variables into index.js: `
6168 )
69+ envVarsToInject . forEach ( ( envVar ) => console . log ( `- ${ envVar } ` ) )
6270} else {
6371 console . error ( 'index.js not found in the dist directory' )
6472}
65-
66- console . log (
67- 'package.json has been cleaned for publishing and index.js has been updated.'
68- )
0 commit comments