@netlify/edge-bundler 14.9.10 → 14.9.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,4 @@
1
- import { promises as fs } from 'fs';
2
- import { builtinModules } from 'module';
1
+ import { promises as fs, existsSync } from 'fs';
3
2
  import path from 'path';
4
3
  import { fileURLToPath, pathToFileURL } from 'url';
5
4
  import commonPathPrefix from 'common-path-prefix';
@@ -22,29 +21,59 @@ export const bundle = async ({ buildID, deno, distDirectory, functions, importMa
22
21
  // Use deno info to get the module graph and identify which local files are actually needed.
23
22
  // This avoids copying unnecessary files (like node_modules) that happen to be under commonPath.
24
23
  // If module graph analysis fails, fall back to copying files from entry point directories.
25
- const sourceFiles = await getRequiredSourceFiles(deno, entryPoints, importMap);
24
+ const sourceFilesSet = await getRequiredSourceFiles(deno, entryPoints, importMap);
25
+ // Build prefix mappings to transform file:// URLs to relative paths
26
+ const npmVendorDir = '.netlify-npm-vendor';
27
+ const prefixes = {};
28
+ // Copy pre-bundled npm modules from vendorDirectory if present.
29
+ // This supports the legacy approach where npm packages are pre-bundled and mapped
30
+ // via import map. Modern code could use npm: specifiers instead, which Deno handles
31
+ // natively via `deno install --vendor`.
32
+ if (vendorDirectory) {
33
+ prefixes[pathToFileURL(vendorDirectory + path.sep).href] = `./${npmVendorDir}/`;
34
+ // Copy files from vendor directory
35
+ const vendorFiles = await listRecursively(vendorDirectory);
36
+ for (const vendorFile of vendorFiles) {
37
+ const relativePath = path.relative(vendorDirectory, vendorFile);
38
+ const destPath = path.join(bundleDir.path, npmVendorDir, relativePath);
39
+ await fs.mkdir(path.dirname(destPath), { recursive: true });
40
+ // Rewrite import assertions in npm vendor directory
41
+ await rewriteImportAssertions(vendorFile, destPath);
42
+ // Remove original bundled npm from source files,
43
+ // rewritten ones will be included in tarball because they will be under bundleDir
44
+ sourceFilesSet.delete(vendorFile);
45
+ }
46
+ }
26
47
  // Find the common path prefix for all source files (entry points + their local imports).
27
48
  // This ensures imports to sibling directories (e.g., ../internal/) are included.
28
49
  // When using a single file, `commonPathPrefix` returns an empty string, so we use
29
50
  // the path of the first entry point's directory.
30
- const commonPath = commonPathPrefix(sourceFiles) || path.dirname(entryPoints[0]);
51
+ const commonPath = commonPathPrefix(Array.from(sourceFilesSet).sort()) || path.dirname(entryPoints[0]);
31
52
  // Build the manifest mapping function names to their relative paths
32
53
  for (const func of functions) {
33
54
  const relativePath = path.relative(commonPath, func.path);
34
55
  manifest.functions[func.name] = getUnixPath(relativePath);
35
56
  }
36
- for (const sourceFile of sourceFiles) {
57
+ for (const sourceFile of sourceFilesSet) {
37
58
  const relativePath = path.relative(commonPath, sourceFile);
38
59
  const destPath = path.join(bundleDir.path, relativePath);
39
60
  await fs.mkdir(path.dirname(destPath), { recursive: true });
40
- // Deno 2.x dropped support for import for import assertions
61
+ // Rewrite import assertions in user files
41
62
  await rewriteImportAssertions(sourceFile, destPath);
42
63
  }
64
+ // Map common path to relative paths
65
+ prefixes[pathToFileURL(commonPath + path.sep).href] = './';
66
+ // Get import map contents with file:// URLs transformed to relative paths
67
+ const importMapContents = importMap.getContents(prefixes);
68
+ // Create deno.json with import map contents for runtime resolution
69
+ const denoConfigPath = path.join(bundleDir.path, 'deno.json');
70
+ const denoConfigContents = JSON.stringify(importMapContents, null, 2);
71
+ await fs.writeFile(denoConfigPath, denoConfigContents);
43
72
  // Vendor all dependencies in the bundle directory
44
73
  await deno.run([
45
74
  'install',
46
75
  '--import-map',
47
- importMap.withNodeBuiltins().toDataURL(),
76
+ denoConfigPath,
48
77
  '--quiet',
49
78
  '--allow-import',
50
79
  '--node-modules-dir=manual',
@@ -54,38 +83,14 @@ export const bundle = async ({ buildID, deno, distDirectory, functions, importMa
54
83
  ], {
55
84
  cwd: bundleDir.path,
56
85
  });
57
- // Build prefix mappings to transform file:// URLs to relative paths
58
- const npmVendorDir = '.netlify-npm-vendor';
59
- const prefixes = {};
60
- // Copy pre-bundled npm modules from vendorDirectory if present.
61
- // This supports the legacy approach where npm packages are pre-bundled and mapped
62
- // via import map. Modern code could use npm: specifiers instead, which Deno handles
63
- // natively via `deno install --vendor`.
64
- if (vendorDirectory) {
65
- prefixes[pathToFileURL(vendorDirectory + path.sep).href] = `./${npmVendorDir}/`;
66
- // Copy files from vendor directory
67
- const vendorFiles = await listRecursively(vendorDirectory);
68
- for (const vendorFile of vendorFiles) {
69
- const relativePath = path.relative(vendorDirectory, vendorFile);
70
- const destPath = path.join(bundleDir.path, npmVendorDir, relativePath);
71
- await fs.mkdir(path.dirname(destPath), { recursive: true });
72
- // Rewrite import assertions in vendored files as well
73
- await rewriteImportAssertions(vendorFile, destPath);
86
+ // Rewrite import assertions in files outputted by deno vendor
87
+ const denoVendorOutput = path.join(bundleDir.path, 'vendor');
88
+ if (existsSync(denoVendorOutput)) {
89
+ const denoVendorFiles = await listRecursively(denoVendorOutput);
90
+ for (const denoVendorFile of denoVendorFiles) {
91
+ await rewriteImportAssertions(denoVendorFile, denoVendorFile);
74
92
  }
75
93
  }
76
- // Map common path to relative paths
77
- prefixes[pathToFileURL(commonPath + path.sep).href] = './';
78
- // Rewrite bare specifier imports to their resolved URLs so they can be
79
- // resolved by Deno's --vendor flag at runtime without needing the customer's import map.
80
- // At runtime, Deno discovers config from /platform/deno.json (the bootstrap entry
81
- // point), not /function/deno.json, so the customer's import map is unreachable.
82
- await rewriteBareSpecifiers(bundleDir.path, sourceFiles, commonPath, importMap, prefixes);
83
- // Get import map contents with file:// URLs transformed to relative paths
84
- const importMapContents = importMap.getContents(prefixes);
85
- // Create deno.json with import map contents for runtime resolution
86
- const denoConfigPath = path.join(bundleDir.path, 'deno.json');
87
- const denoConfigContents = JSON.stringify(importMapContents);
88
- await fs.writeFile(denoConfigPath, denoConfigContents);
89
94
  const manifestPath = path.join(bundleDir.path, '___netlify-edge-functions.json');
90
95
  const manifestContents = JSON.stringify(manifest);
91
96
  await fs.writeFile(manifestPath, manifestContents);
@@ -116,92 +121,8 @@ export const bundle = async ({ buildID, deno, distDirectory, functions, importMa
116
121
  hash,
117
122
  };
118
123
  };
119
- // Specifiers provided by the platform deno.json at runtime - no need to rewrite these.
120
- const PLATFORM_SPECIFIERS = new Set(['@netlify/edge-functions', 'netlify:edge']);
121
124
  // Source file extensions that may contain import statements.
122
125
  const REWRITABLE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.mts']);
123
- /**
124
- * Rewrites bare specifier imports in copied source files to their resolved URLs
125
- * from the import map. This allows Deno's --vendor flag to resolve these imports
126
- * at runtime without needing the customer's import map (which is unreachable
127
- * because Deno discovers config from the platform bootstrap directory, not the
128
- * function directory).
129
- *
130
- * Only rewrites specifiers that:
131
- * - Are bare package specifiers (not relative, absolute, or URL imports)
132
- * - Resolve to http/https or npm: URLs in the import map
133
- * - Are NOT node builtins or platform-provided imports
134
- */
135
- async function rewriteBareSpecifiers(bundleDirPath, sourceFiles, commonPath, importMap, prefixes) {
136
- const contents = importMap.getContents(prefixes);
137
- const builtinSet = new Set(builtinModules);
138
- // Collect bare specifiers that should be rewritten to URLs or relative paths
139
- const specifierEntries = Object.entries(contents.imports)
140
- .filter(([specifier, url]) => {
141
- // Skip node builtins
142
- if (specifier.startsWith('node:') || builtinSet.has(specifier))
143
- return false;
144
- // Skip platform-provided specifiers (handled by platform deno.json)
145
- if (PLATFORM_SPECIFIERS.has(specifier))
146
- return false;
147
- // Skip relative/absolute path specifiers in the specifier itself
148
- if (specifier.startsWith('.') || specifier.startsWith('/'))
149
- return false;
150
- // Rewrite http/https, npm:, or vendored npm modules (relative paths with .netlify-npm-vendor)
151
- if (url.startsWith('http://') ||
152
- url.startsWith('https://') ||
153
- url.startsWith('npm:') ||
154
- url.includes('.netlify-npm-vendor')) {
155
- return true;
156
- }
157
- return false;
158
- })
159
- // Sort longest first so prefix mappings like "lodash/" match before "lodash"
160
- .sort((a, b) => b[0].length - a[0].length);
161
- for (const sourceFile of sourceFiles) {
162
- if (!REWRITABLE_EXTENSIONS.has(path.extname(sourceFile)))
163
- continue;
164
- const relativePath = path.relative(commonPath, sourceFile);
165
- const destPath = path.join(bundleDirPath, relativePath);
166
- let source;
167
- try {
168
- source = await fs.readFile(destPath, 'utf-8');
169
- }
170
- catch {
171
- continue;
172
- }
173
- let modified = source;
174
- for (const [specifier, url] of specifierEntries) {
175
- const escaped = specifier.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
176
- // Convert bundle-root-relative paths to source-file-relative paths
177
- let targetUrl = url;
178
- if (url.startsWith('./') || url.startsWith('../')) {
179
- // URL is relative to bundle root (e.g., "./.netlify-npm-vendor/bundled-parent-1.js")
180
- // Convert to absolute path in bundle, then to relative from source file
181
- const targetAbsolutePath = path.resolve(bundleDirPath, url);
182
- const relativeImport = path.relative(path.dirname(destPath), targetAbsolutePath);
183
- // Ensure forward slashes and ./ prefix for clarity
184
- targetUrl = relativeImport.startsWith('.') ? relativeImport : `./${relativeImport}`;
185
- targetUrl = targetUrl.replace(/\\/g, '/');
186
- }
187
- // Escape $ in URL for use in replacement string
188
- const safeUrl = targetUrl.replace(/\$/g, '$$$$');
189
- for (const quote of ['"', "'"]) {
190
- if (specifier.endsWith('/')) {
191
- // Prefix mapping: "specifier/subpath" -> "url/subpath"
192
- modified = modified.replace(new RegExp(`(\\bfrom\\s+|\\bimport\\s+|\\bimport\\s*\\(\\s*)${quote}${escaped}([^${quote}]*)${quote}`, 'g'), `$1${quote}${safeUrl}$2${quote}`);
193
- }
194
- else {
195
- // Exact mapping: "specifier" -> "url"
196
- modified = modified.replace(new RegExp(`(\\bfrom\\s+|\\bimport\\s+|\\bimport\\s*\\(\\s*)${quote}${escaped}${quote}`, 'g'), `$1${quote}${safeUrl}${quote}`);
197
- }
198
- }
199
- }
200
- if (modified !== source) {
201
- await fs.writeFile(destPath, modified);
202
- }
203
- }
204
- }
205
126
  /**
206
127
  * Uses deno info to get the module graph and extract only the local source files
207
128
  * that are actually needed by the entry points. This avoids copying unnecessary
@@ -242,7 +163,7 @@ async function getRequiredSourceFiles(deno, entryPoints, importMap) {
242
163
  }
243
164
  }
244
165
  }
245
- return Array.from(localFiles).sort();
166
+ return localFiles;
246
167
  }
247
168
  /**
248
169
  * Rewrites import assert into import with in the bundle directory
@@ -250,15 +171,12 @@ async function getRequiredSourceFiles(deno, entryPoints, importMap) {
250
171
  */
251
172
  export async function rewriteImportAssertions(sourceFile, destPath) {
252
173
  if (!REWRITABLE_EXTENSIONS.has(path.extname(sourceFile))) {
253
- await fs.copyFile(sourceFile, destPath);
174
+ if (sourceFile !== destPath) {
175
+ await fs.copyFile(sourceFile, destPath);
176
+ }
254
177
  return;
255
178
  }
256
- try {
257
- const source = await fs.readFile(sourceFile, 'utf-8');
258
- const modified = rewriteSourceImportAssertions(source);
259
- await fs.writeFile(destPath, modified);
260
- }
261
- catch {
262
- await fs.copyFile(sourceFile, destPath);
263
- }
179
+ const source = await fs.readFile(sourceFile, 'utf-8');
180
+ const modified = rewriteSourceImportAssertions(source);
181
+ await fs.writeFile(destPath, modified);
264
182
  }
@@ -42,8 +42,10 @@ export function rewriteSourceImportAssertions(source) {
42
42
  });
43
43
  return modified;
44
44
  }
45
- catch {
46
- // Gracefully fail and still replace where possible
47
- return modified;
45
+ catch (error) {
46
+ if (!modified.includes('assert')) {
47
+ return modified;
48
+ }
49
+ throw error;
48
50
  }
49
51
  }
package/dist/test/util.js CHANGED
@@ -118,7 +118,7 @@ export const runTarball = async (tarballPath) => {
118
118
  cwd: tmpDir.path,
119
119
  file: tarballPath,
120
120
  });
121
- const evalCommand = execa('deno', ['eval', inspectTarballFunction()], {
121
+ const evalCommand = execa('deno', ['eval', '--vendor', inspectTarballFunction()], {
122
122
  cwd: tmpDir.path,
123
123
  });
124
124
  evalCommand.stderr?.pipe(stderr);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netlify/edge-bundler",
3
- "version": "14.9.10",
3
+ "version": "14.9.11",
4
4
  "description": "Intelligently prepare Netlify Edge Functions for deployment",
5
5
  "type": "module",
6
6
  "main": "./dist/node/index.js",
@@ -82,5 +82,5 @@
82
82
  "urlpattern-polyfill": "8.0.2",
83
83
  "uuid": "^11.0.0"
84
84
  },
85
- "gitHead": "0e726c9159c64a5f000104faacca5ad09a4eb27b"
85
+ "gitHead": "16f1f4db9008cca184d7113f9c55aefcf1b8239f"
86
86
  }