- 
                Notifications
    You must be signed in to change notification settings 
- Fork 984
App Hosting JS SDK autoinit #8483
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            23 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      6470299
              
                First.
              
              
                jamesdaniels cd6d61a
              
                Making postinstall.mjs more robust
              
              
                jamesdaniels 1381961
              
                Catch fetch
              
              
                jamesdaniels 6b0c6b1
              
                Use what we have
              
              
                jamesdaniels 1fb66a5
              
                Clean up and temp fix for escaping issue
              
              
                jamesdaniels c8ffa75
              
                Merge branch 'main' into jamesdaniels_workingAutoinit
              
              
                jamesdaniels 525a4e2
              
                Cleanup
              
              
                jamesdaniels d0ce18e
              
                Move to .js file
              
              
                jamesdaniels 861e5b0
              
                Use rollup plugin replace
              
              
                jamesdaniels 63b449e
              
                Dont use default export
              
              
                jamesdaniels 85b8992
              
                Format
              
              
                jamesdaniels 9a38e30
              
                Add changeset
              
              
                jamesdaniels f247bea
              
                Code format env var
              
              
                jamesdaniels f52116a
              
                Error on network failure
              
              
                jamesdaniels f83c02b
              
                cleanup postinstall
              
              
                jamesdaniels a4a09cf
              
                Fix subtle break, more guardrails to ensure fail open
              
              
                jamesdaniels 2c6344c
              
                Handle demo- projects
              
              
                jamesdaniels 641203d
              
                Return undefined
              
              
                jamesdaniels df72b14
              
                Add catch to file saves
              
              
                jamesdaniels 10f959b
              
                Dry up the catches
              
              
                jamesdaniels 7955cc8
              
                No seperate export, better naming
              
              
                jamesdaniels 939af36
              
                Formattting
              
              
                jamesdaniels 15a35e9
              
                Cleanup error messages, address feedback
              
              
                jamesdaniels File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| '@firebase/util': minor | ||
| 'firebase': minor | ||
| --- | ||
|  | ||
| Add support for the `FIREBASE_WEBAPP_CONFIG` environment variable at install time. | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| /** | ||
| * @license | ||
| * Copyright 2025 Google LLC | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|  | ||
| const { writeFile, readFile } = require('node:fs/promises'); | ||
| const { pathToFileURL } = require('node:url'); | ||
| const { isAbsolute, join } = require('node:path'); | ||
|  | ||
| const ENV_VARIABLE = 'FIREBASE_WEBAPP_CONFIG'; | ||
|  | ||
| async function getPartialConfig() { | ||
| const envVariable = process.env[ENV_VARIABLE]?.trim(); | ||
|  | ||
| if (!envVariable) { | ||
| return undefined; | ||
| } | ||
|  | ||
| // Like FIREBASE_CONFIG (admin autoinit) FIREBASE_WEBAPP_CONFIG can be | ||
| // either a JSON representation of FirebaseOptions or the path to a filename | ||
| if (envVariable.startsWith('{"')) { | ||
| try { | ||
| return JSON.parse(envVariable); | ||
| } catch (e) { | ||
| console.warn( | ||
| `JSON payload in \$${ENV_VARIABLE} could not be parsed, ignoring.\n`, | ||
| e | ||
| ); | ||
| return undefined; | ||
| } | ||
| } | ||
|  | ||
| const fileURL = pathToFileURL( | ||
| isAbsolute(envVariable) ? envVariable : join(process.cwd(), envVariable) | ||
| ); | ||
|  | ||
| try { | ||
| const fileContents = await readFile(fileURL, 'utf-8'); | ||
| return JSON.parse(fileContents); | ||
| } catch (e) { | ||
| console.warn( | ||
| `Contents of "${envVariable}" could not be parsed, ignoring \$${ENV_VARIABLE}.\n`, | ||
| e | ||
| ); | ||
| return undefined; | ||
| } | ||
| } | ||
|  | ||
| async function getFinalConfig(partialConfig) { | ||
| if (!partialConfig) { | ||
| return undefined; | ||
| } | ||
| // In Firebase App Hosting the config provided to the environment variable is up-to-date and | ||
| // "complete" we should not reach out to the webConfig endpoint to freshen it | ||
| if (process.env.X_GOOGLE_TARGET_PLATFORM === 'fah') { | ||
| return partialConfig; | ||
| } | ||
| const projectId = partialConfig.projectId || '-'; | ||
| // If the projectId starts with demo- this is an demo project from the firebase emulators | ||
| // treat the config as whole | ||
| if (projectId.startsWith('demo-')) { | ||
| return partialConfig; | ||
| } | ||
| const appId = partialConfig.appId; | ||
| const apiKey = partialConfig.apiKey; | ||
| if (!appId || !apiKey) { | ||
| console.warn( | ||
| `Unable to fetch Firebase config, appId and apiKey are required, ignoring \$${ENV_VARIABLE}.` | ||
| ); | ||
| return undefined; | ||
| } | ||
|  | ||
| const url = `https://firebase.googleapis.com/v1alpha/projects/${projectId}/apps/${appId}/webConfig`; | ||
|  | ||
| try { | ||
| const response = await fetch(url, { | ||
| headers: { 'x-goog-api-key': apiKey } | ||
| }); | ||
| if (!response.ok) { | ||
| console.warn( | ||
| `Unable to fetch Firebase config, ignoring \$${ENV_VARIABLE}.` | ||
| ); | ||
| console.warn( | ||
| `${url} returned ${response.statusText} (${response.status})` | ||
| ); | ||
| try { | ||
| console.warn((await response.json()).error.message); | ||
| } catch (e) {} | ||
| return undefined; | ||
| } | ||
| const json = await response.json(); | ||
| return { ...json, apiKey }; | ||
| } catch (e) { | ||
| console.warn( | ||
| `Unable to fetch Firebase config, ignoring \$${ENV_VARIABLE}.\n`, | ||
| e | ||
| ); | ||
| return undefined; | ||
| } | ||
| } | ||
|  | ||
| function handleUnexpectedError(e) { | ||
| console.warn( | ||
| `Unexpected error encountered in @firebase/util postinstall script, ignoring \$${ENV_VARIABLE}.` | ||
| ); | ||
| console.warn(e); | ||
| process.exit(0); | ||
| } | ||
|  | ||
| getPartialConfig() | ||
| .catch(handleUnexpectedError) | ||
| .then(getFinalConfig) | ||
| .catch(handleUnexpectedError) | ||
| .then(async finalConfig => { | ||
| const defaults = finalConfig && { | ||
| config: finalConfig, | ||
| emulatorHosts: { | ||
| firestore: process.env.FIRESTORE_EMULATOR_HOST, | ||
| database: process.env.FIREBASE_DATABASE_EMULATOR_HOST, | ||
| storage: process.env.FIREBASE_STORAGE_EMULATOR_HOST, | ||
| auth: process.env.FIREBASE_AUTH_EMULATOR_HOST | ||
| } | ||
| }; | ||
|  | ||
| await Promise.all([ | ||
| writeFile( | ||
| join(__dirname, 'dist', 'postinstall.js'), | ||
| `'use strict'; | ||
| Object.defineProperty(exports, '__esModule', { value: true }); | ||
| exports.getDefaultsFromPostinstall = () => (${JSON.stringify(defaults)});` | ||
| ), | ||
| writeFile( | ||
| join(__dirname, 'dist', 'postinstall.mjs'), | ||
| `const getDefaultsFromPostinstall = () => (${JSON.stringify(defaults)}); | ||
| export { getDefaultsFromPostinstall };` | ||
| ) | ||
| ]); | ||
|  | ||
| process.exit(0); | ||
| }) | ||
| .catch(handleUnexpectedError); | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| /** | ||
| * @license | ||
| * Copyright 2025 Google LLC | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|  | ||
| import type { FirebaseDefaults } from './defaults'; | ||
|  | ||
| // This value is retrieved and hardcoded by the NPM postinstall script | ||
| export const getDefaultsFromPostinstall: () => | ||
| | FirebaseDefaults | ||
| | undefined = () => undefined; | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.