-
Notifications
You must be signed in to change notification settings - Fork 902
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
Demo of autoinit on App Hosting #8483
Draft
jamesdaniels
wants to merge
5
commits into
main
Choose a base branch
from
jamesdaniels_workingAutoinit
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+123
−2
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
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 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,8 @@ | ||
import { FirebaseOptions } from "@firebase/app-types"; | ||
|
||
declare const FirebaseDefaults: { | ||
config?: FirebaseOptions; | ||
emulatorHosts?: Record<string, string|undefined>; | ||
} | undefined; | ||
|
||
export default FirebaseDefaults; | ||
This file contains 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 @@ | ||
module.exports = undefined |
This file contains 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 @@ | ||
export default undefined |
This file contains 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 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,98 @@ | ||
import { writeFile, readFile } from "node:fs/promises"; | ||
import { pathToFileURL } from "node:url"; | ||
import { isAbsolute, join } from "node:path"; | ||
|
||
async function getWebConfig() { | ||
let configFromEnvironment = undefined; | ||
// $FIREBASE_WEBAPP_CONFIG can be either a JSON representation of FirebaseOptions or the path | ||
// to a filename | ||
if (process.env.FIREBASE_WEBAPP_CONFIG) { | ||
if (process.env.FIREBASE_WEBAPP_CONFIG.startsWith("{\"")) { | ||
try { | ||
configFromEnvironment = JSON.parse(process.env.FIREBASE_WEBAPP_CONFIG); | ||
} catch(e) { | ||
console.error("FIREBASE_WEBAPP_CONFIG could not be parsed.", e); | ||
} | ||
} if (process.env.FIREBASE_WEBAPP_CONFIG.startsWith("{")) { | ||
// TODO temporary | ||
configFromEnvironment = Object.fromEntries( | ||
process.env.FIREBASE_WEBAPP_CONFIG | ||
.match(/^{(.+)}$/)[1] | ||
.split(',') | ||
.map(it => it.match("([^\:]+)\:(.+)")?.slice(1)) | ||
.filter(it => it) | ||
); | ||
} else { | ||
const fileName = process.env.FIREBASE_WEBAPP_CONFIG; | ||
const fileURL = pathToFileURL(isAbsolute(fileName) ? fileName : join(process.cwd(), fileName)); | ||
const fileContents = await readFile(fileURL, "utf-8").catch((err) => { | ||
console.error(err); | ||
return undefined; | ||
}); | ||
if (fileContents) { | ||
try { | ||
configFromEnvironment = JSON.parse(fileContents); | ||
} catch(e) { | ||
console.error(`Contents of ${fileName} could not be parsed.`, e); | ||
} | ||
} | ||
} | ||
} | ||
|
||
// 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 configFromEnvironment; | ||
} | ||
|
||
if (!configFromEnvironment) { | ||
return undefined; | ||
} | ||
const projectId = configFromEnvironment.projectId || "-"; | ||
const appId = configFromEnvironment.appId; | ||
const apiKey = configFromEnvironment.apiKey; | ||
if (!appId || !apiKey) { | ||
console.error("appId and apiKey are needed"); | ||
return undefined; | ||
} | ||
const response = await fetch( | ||
`https://firebase.googleapis.com/v1alpha/projects/${projectId}/apps/${appId}/webConfig`, | ||
{ headers: { "x-goog-api-key": apiKey } } | ||
).catch((e) => { | ||
// TODO add sensible error | ||
console.error(e); | ||
return configFromEnvironment; | ||
}); | ||
if (!response.ok) { | ||
// TODO add sensible error | ||
console.error("yikes."); | ||
return configFromEnvironment; | ||
} | ||
const json = await response.json().catch(() => { | ||
// TODO add sensible error | ||
console.error("also yikes."); | ||
return configFromEnvironment; | ||
}); | ||
return { ...json, apiKey }; | ||
} | ||
|
||
const config = await getWebConfig(); | ||
|
||
const emulatorHosts = { | ||
// TODO: remote config, functions, and data connect emulators? | ||
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, | ||
}; | ||
|
||
const anyEmulatorHosts = Object.values(emulatorHosts).filter(it => it).length > 0; | ||
|
||
// getDefaults() will use this object, rather than fallback to other autoinit suppliers, if it's | ||
// truthy—if we've done nothing here, make it falsy. | ||
const defaults = (config || anyEmulatorHosts) ? { config, emulatorHosts } : undefined; | ||
|
||
await Promise.all([ | ||
writeFile(join(import.meta.dirname, "defaults.js"), `module.exports = ${JSON.stringify(defaults)}`), | ||
writeFile(join(import.meta.dirname, "defaults.mjs"), `export default ${JSON.stringify(defaults)}`), | ||
]); |
This file contains 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a work-around to a bug in Firebase App Hosting today, we will drop