Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 92
feat(globals): runtime disable + scripts:globals hook#808
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
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
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
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 |
|---|---|---|
| @@ -26,6 +26,9 @@ declare module '#app' { | ||
| } | ||
| interface RuntimeNuxtHooks { | ||
| 'scripts:updated': (ctx: { scripts: Record<string, import('#nuxt-scripts/types').NuxtDevToolsScriptInstance> }) => void | Promise<void> | ||
| // Index signature (not a literal-key Record) so listeners can both \`delete globals[key]\` | ||
| // and mutate \`globals[key].src\` without TS2790 / possibly-undefined errors. | ||
| 'scripts:globals': (globals: Record<string, Record<string, any>>) => void | Promise<void> | ||
| } | ||
| } | ||
| ${globalsKeys.length | ||
| @@ -113,6 +116,10 @@ export function templatePlugin(config: Partial<ModuleOptions>, registry: Require | ||
| } | ||
| const imports = [] | ||
| const inits = [] | ||
| // Globals are split out so the resolved inputs can be collected into a mutable map, | ||
| // passed through the `scripts:globals` runtime hook, then registered. | ||
| const globalMapEntries: string[] = [] | ||
| const globalInits: string[] = [] | ||
| const resolvedRegistryKeys: string[] = [] | ||
| let needsIdleTimeoutImport = false | ||
| let needsInteractionImport = false | ||
| @@ -211,7 +218,13 @@ export function templatePlugin(config: Partial<ModuleOptions>, registry: Require | ||
| } | ||
| const useFn = `use: () => ({ ${k}: window.${k} })` | ||
| const optionsArg = optionsJson ? `{ ...${optionsJson}, ${useFn} }` : `{ ${useFn} }` | ||
| inits.push(`const ${k} = useScript(${inputExpr}, ${optionsArg})`) | ||
| // Resolved input goes into the mutable `__globals` map keyed by its global key, so the | ||
| // `scripts:globals` hook can rewrite/delete/add entries before registration. | ||
| globalMapEntries.push(`${JSON.stringify(k)}: ${inputExpr}`) | ||
| // Registration is guarded so a runtime override (env or hook) can disable an entry | ||
| // per-instance (multi-tenant single-build): set `enabled: false` or an empty/null `src` | ||
| // and the script is never registered. See https://github.com/nuxt/scripts/issues/759. | ||
| globalInits.push(`const ${k} = __registerGlobal(__globals[${JSON.stringify(k)}], ${optionsArg})`) | ||
| } | ||
| // Add conditional imports for trigger composables | ||
| const triggerImports = [] | ||
| @@ -226,8 +239,20 @@ export function templatePlugin(config: Partial<ModuleOptions>, registry: Require | ||
| } | ||
| const setupBody: string[] = [] | ||
| if (hasGlobals) | ||
| if (hasGlobals) { | ||
| setupBody.push(` const __scriptsGlobals = useRuntimeConfig().public.scriptsGlobals || {}`) | ||
| // A global is skipped when the merged input disables it: `enabled === false`, or an | ||
| // empty/null `src` (the env-overridable way to drop an unused integration per instance). | ||
| setupBody.push(` const __registerGlobal = (input, options) => { if (!input) return undefined; const { enabled, ...rest } = input; return (enabled === false || rest.src === '' || rest.src === null) ? undefined : useScript(rest, options) }`) | ||
| // Resolved inputs (build-time default <- env override) collected into a mutable map. | ||
| setupBody.push(` const __globals = {`) | ||
| setupBody.push(...globalMapEntries.map(e => ` ${e},`)) | ||
| setupBody.push(` }`) | ||
| // Runtime hook: userland may rewrite `src`/attrs, delete keys, or add new entries before | ||
| // registration. Register the listener from an `enforce: 'pre'` plugin so it runs first. | ||
| setupBody.push(` await nuxtApp.hooks.callHook('scripts:globals', __globals)`) | ||
| setupBody.push(...globalInits.map(i => ` ${i}`)) | ||
| } | ||
| setupBody.push(...inits.map(i => ` ${i}`)) | ||
| setupBody.push(` return { provide: { scripts: { ${[...Object.keys(config.globals || {}), ...resolvedRegistryKeys].join(', ')} } } }`) | ||
coderabbitai[bot] marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| return [ | ||
| @@ -240,7 +265,7 @@ export function templatePlugin(config: Partial<ModuleOptions>, registry: Require | ||
| ` name: "scripts:init",`, | ||
| ` env: { islands: false },`, | ||
| ` parallel: true,`, | ||
| ` setup() {`, | ||
| ` ${hasGlobals ? 'async setup(nuxtApp) {' : 'setup() {'}`, | ||
| ...setupBody, | ||
| ` }`, | ||
| `})`, | ||
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
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,12 @@ | ||
| // `enforce: 'pre'` so the listener is registered before the module's scripts:init plugin | ||
| // runs and fires the hook. Proves runtime mutation of globals per instance (issue #759). | ||
| export default defineNuxtPlugin({ | ||
| enforce: 'pre', | ||
| setup(nuxtApp) { | ||
| nuxtApp.hooks.hook('scripts:globals', (globals) => { | ||
| globals.scrads.src = 'https://scrads.example/from-hook.js' | ||
| // Removing an entry must skip its registration without crashing setup. | ||
| delete globals.legacy | ||
| }) | ||
| }, | ||
| }) |
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.
Uh oh!
There was an error while loading. Please reload this page.
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.