@@ -118,3 +118,51 @@ describe("writeEnvFile", () => {
118118 expect ( filename2 ) . toBe ( ".dev.vars" ) ;
119119 } ) ;
120120} ) ;
121+
122+ describe ( "integration: pull + existing .env" , ( ) => {
123+ test ( "full pull scenario: existing .env preserved, new keys merged, updated keys changed" , async ( ) => {
124+ writeFileSync (
125+ join ( TMP , ".env" ) ,
126+ [
127+ "DATABASE_URL=postgres://localhost:5432/mydb" ,
128+ "REDIS_URL=redis://localhost:6379" ,
129+ "EXISTING_SECRET=should-not-be-lost" ,
130+ "" ,
131+ ] . join ( "\n" )
132+ ) ;
133+
134+ // Simulate pull: 2 new keys + 1 existing key updated
135+ const pulled = {
136+ COINBASE_API_KEY : "test-key-123" ,
137+ COINBASE_API_SECRET : "test-secret-456" ,
138+ REDIS_URL : "redis://new-host:6379" ,
139+ } ;
140+
141+ const file = await writeEnvFile ( TMP , pulled ) ;
142+ expect ( file ) . toBe ( ".env" ) ;
143+
144+ const content = readFileSync ( join ( TMP , ".env" ) , "utf-8" ) ;
145+ // Existing untouched key preserved
146+ expect ( content ) . toContain ( "DATABASE_URL=postgres://localhost:5432/mydb" ) ;
147+ expect ( content ) . toContain ( "EXISTING_SECRET=should-not-be-lost" ) ;
148+ // Updated key
149+ expect ( content ) . toContain ( "REDIS_URL=redis://new-host:6379" ) ;
150+ expect ( content ) . not . toContain ( "redis://localhost:6379" ) ;
151+ // New keys appended
152+ expect ( content ) . toContain ( "COINBASE_API_KEY=test-key-123" ) ;
153+ expect ( content ) . toContain ( "COINBASE_API_SECRET=test-secret-456" ) ;
154+ } ) ;
155+
156+ test ( "multiple pulls don't duplicate keys" , async ( ) => {
157+ writeFileSync ( join ( TMP , ".env" ) , "DB=postgres\n" ) ;
158+
159+ await writeEnvFile ( TMP , { API_KEY : "v1" } ) ;
160+ await writeEnvFile ( TMP , { API_KEY : "v2" } ) ;
161+
162+ const content = readFileSync ( join ( TMP , ".env" ) , "utf-8" ) ;
163+ const matches = content . match ( / A P I _ K E Y = / g) ;
164+ expect ( matches ) . toHaveLength ( 1 ) ;
165+ expect ( content ) . toContain ( "API_KEY=v2" ) ;
166+ expect ( content ) . toContain ( "DB=postgres" ) ;
167+ } ) ;
168+ } ) ;
0 commit comments