0
# Environment and Global Access
1
2
Cross-environment utilities for accessing global objects, handling platform differences, and managing allowed global variables in Vue templates.
3
4
## Capabilities
5
6
### Global Object Access
7
8
Functions for safely accessing the global object across different JavaScript environments.
9
10
```typescript { .api }
11
/**
12
* Get the global object in a cross-environment way
13
* Handles globalThis, self, window, global, and fallback cases
14
* @returns The global object for the current environment
15
*/
16
function getGlobalThis(): any;
17
```
18
19
### Global Variable Allowlist
20
21
Functions for controlling which global variables can be accessed in Vue templates for security.
22
23
```typescript { .api }
24
/**
25
* Check if a global variable name is allowed in Vue templates
26
* Prevents access to potentially dangerous globals
27
* @param key - Global variable name to check
28
* @returns True if the global is safe to access
29
*/
30
function isGloballyAllowed(key: string): boolean;
31
32
/**
33
* @deprecated Use isGloballyAllowed instead
34
* Legacy name for isGloballyAllowed function
35
*/
36
function isGloballyWhitelisted(key: string): boolean;
37
```
38
39
### Utility Functions
40
41
Additional environment-related utilities.
42
43
```typescript { .api }
44
/**
45
* Create a map-based lookup function from comma-separated string
46
* Used internally for creating fast lookup functions
47
* @param str - Comma-separated string of keys
48
* @returns Function that checks if key exists in the map
49
*/
50
function makeMap(str: string): (key: string) => boolean;
51
```
52
53
**Usage Examples:**
54
55
```typescript
56
import {
57
getGlobalThis,
58
isGloballyAllowed,
59
isGloballyWhitelisted,
60
makeMap
61
} from "@vue/shared";
62
63
// Global object access across environments
64
const globalObj = getGlobalThis();
65
66
// In browser environment
67
if (typeof window !== 'undefined') {
68
console.log(globalObj === window); // true
69
}
70
71
// In Node.js environment
72
if (typeof global !== 'undefined') {
73
console.log(globalObj === global); // true
74
}
75
76
// In Web Worker environment
77
if (typeof self !== 'undefined') {
78
console.log(globalObj === self); // true
79
}
80
81
// Modern environments with globalThis
82
if (typeof globalThis !== 'undefined') {
83
console.log(globalObj === globalThis); // true
84
}
85
86
// Global variable allowlist checking
87
console.log(isGloballyAllowed("Math")); // true - Math is allowed
88
console.log(isGloballyAllowed("console")); // true - console is allowed
89
console.log(isGloballyAllowed("Date")); // true - Date is allowed
90
console.log(isGloballyAllowed("Array")); // true - Array is allowed
91
console.log(isGloballyAllowed("Object")); // true - Object is allowed
92
93
// Security - potentially dangerous globals are blocked
94
console.log(isGloballyAllowed("eval")); // false - eval is not allowed
95
console.log(isGloballyAllowed("Function")); // false - Function constructor blocked
96
console.log(isGloballyAllowed("window")); // false - direct window access blocked
97
console.log(isGloballyAllowed("document")); // false - document access blocked
98
console.log(isGloballyAllowed("localStorage")); // false - localStorage blocked
99
100
// Template usage simulation
101
function evaluateTemplateExpression(expr: string, globals: Record<string, any>) {
102
// Check if global variables in expression are allowed
103
const globalRefs = extractGlobalReferences(expr); // hypothetical function
104
105
for (const ref of globalRefs) {
106
if (!isGloballyAllowed(ref)) {
107
throw new Error(`Global '${ref}' is not allowed in templates`);
108
}
109
}
110
111
// Safe to evaluate expression
112
return evaluateExpression(expr, globals);
113
}
114
115
// Legacy function (deprecated)
116
console.log(isGloballyWhitelisted("Math")); // true - same as isGloballyAllowed
117
// Note: This function is deprecated, use isGloballyAllowed instead
118
119
// Creating custom lookup maps
120
const allowedProps = makeMap("id,class,style,title,alt");
121
console.log(allowedProps("class")); // true
122
console.log(allowedProps("onclick")); // false
123
124
const htmlTags = makeMap("div,span,p,h1,h2,h3,button,input");
125
console.log(htmlTags("div")); // true
126
console.log(htmlTags("custom-element")); // false
127
```
128
129
### Allowed Global Variables
130
131
The following global variables are permitted in Vue templates:
132
133
**JavaScript Built-ins:**
134
- `Infinity`, `undefined`, `NaN`
135
- `isFinite`, `isNaN`, `parseFloat`, `parseInt`
136
- `decodeURI`, `decodeURIComponent`, `encodeURI`, `encodeURIComponent`
137
138
**Standard Objects:**
139
- `Math`, `Number`, `Date`, `Array`, `Object`, `Boolean`, `String`, `RegExp`
140
- `Map`, `Set`, `JSON`, `Intl`, `BigInt`
141
142
**Debugging:**
143
- `console`, `Error`
144
145
**Symbols:**
146
- `Symbol`
147
148
### Security Rationale
149
150
The allowlist prevents template injection attacks by blocking access to:
151
152
- **Code Execution**: `eval`, `Function`, `setTimeout`, `setInterval`
153
- **DOM Access**: `window`, `document`, `location`
154
- **Storage**: `localStorage`, `sessionStorage`, `indexedDB`
155
- **Network**: `fetch`, `XMLHttpRequest`, `WebSocket`
156
- **Node.js Globals**: `process`, `require`, `module`, `exports`
157
158
### Environment Detection Patterns
159
160
```typescript
161
// Safe global access pattern
162
const global = getGlobalThis();
163
164
// Feature detection
165
if ('fetch' in global) {
166
// Fetch API available
167
}
168
169
if ('process' in global && global.process?.env) {
170
// Node.js environment
171
}
172
173
// Environment-specific setup
174
function setupEnvironment() {
175
const global = getGlobalThis();
176
177
if (typeof window !== 'undefined') {
178
// Browser environment
179
setupBrowser(global);
180
} else if (typeof global.process !== 'undefined') {
181
// Node.js environment
182
setupNode(global);
183
} else {
184
// Other environment (Web Worker, etc.)
185
setupGeneric(global);
186
}
187
}
188
```
189
190
### Performance Characteristics
191
192
- **getGlobalThis**: Cached after first call - subsequent calls return cached value
193
- **isGloballyAllowed**: O(1) lookup using internal map created by `makeMap`
194
- **makeMap**: Creates optimized lookup with `Object.create(null)` for fast property access
195
196
### Integration with Vue
197
198
These utilities enable Vue's secure template system:
199
200
- **Template Compilation**: Global references are validated against the allowlist
201
- **Expression Evaluation**: Only safe globals can be accessed in template expressions
202
- **SSR Compatibility**: Works across server and client environments
203
- **Development Tools**: Global access provides platform-specific debugging capabilities