@ms-cloudpack/api-server 0.56.7 → 0.56.8

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 +1 @@
1
- {"version":3,"file":"bundleTask.d.ts","sourceRoot":"","sources":["../../src/utilities/bundleTask.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAOvE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D,MAAM,MAAM,yBAAyB,GAAG,iBAAiB,GAAG;IAAE,aAAa,EAAE,aAAa,CAAA;CAAE,CAAC;AAC7F,MAAM,MAAM,yBAAyB,GAAG,cAAc,CACpD,UAAU,GAAG,eAAe,GAAG,UAAU,GAAG,iBAAiB,EAC7D,YAAY,GAAG,QAAQ,GAAG,UAAU,GAAG,WAAW,CACnD,CAAC;AAEF;;GAEG;AACH,wBAAsB,UAAU,CAC9B,OAAO,EAAE,yBAAyB,EAClC,OAAO,EAAE,yBAAyB,GACjC,OAAO,CAAC,IAAI,CAAC,CAiIf"}
1
+ {"version":3,"file":"bundleTask.d.ts","sourceRoot":"","sources":["../../src/utilities/bundleTask.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAOvE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D,MAAM,MAAM,yBAAyB,GAAG,iBAAiB,GAAG;IAAE,aAAa,EAAE,aAAa,CAAA;CAAE,CAAC;AAC7F,MAAM,MAAM,yBAAyB,GAAG,cAAc,CACpD,UAAU,GAAG,eAAe,GAAG,UAAU,GAAG,iBAAiB,EAC7D,YAAY,GAAG,QAAQ,GAAG,UAAU,GAAG,WAAW,CACnD,CAAC;AAEF;;GAEG;AACH,wBAAsB,UAAU,CAC9B,OAAO,EAAE,yBAAyB,EAClC,OAAO,EAAE,yBAAyB,GACjC,OAAO,CAAC,IAAI,CAAC,CAoIf"}
@@ -78,6 +78,9 @@ export async function bundleTask(options, context) {
78
78
  bundlerCapabilities,
79
79
  };
80
80
  const bundleInternalResult = await bundle(bundleOptions, { config });
81
+ if (bundleInternalResult.bundler) {
82
+ span.setAttribute('bundler', bundleInternalResult.bundler);
83
+ }
81
84
  bundleRequest.result = {
82
85
  ...bundleInternalResult,
83
86
  outputPath: bundleOptions.outputPath ?? outputPath,
@@ -1 +1 @@
1
- {"version":3,"file":"bundleTask.js","sourceRoot":"","sources":["../../src/utilities/bundleTask.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAElG,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAGnE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AASrE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAC9B,OAAkC,EAClC,OAAkC;IAElC,MAAM,EAAE,aAAa,EAAE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AAE,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;gBAE9E,MAAM,UAAU,GAAG,MAAM,aAAa,CAAC;oBACrC,UAAU;oBACV,WAAW,EAAE,aAAa,CAAC,MAAM,CAAC,WAAW;oBAC7C,UAAU;oBACV,UAAU;oBACV,WAAW;iBACZ,CAAC,CAAC;gBAEH,aAAa,CAAC,MAAM,CAAC,IAAI,GAAG,UAAU,CAAC;gBAEvC,8DAA8D;gBAC9D,mEAAmE;gBACnE,SAAS,CAAC,cAAc,EAAE,UAAU,CAAC,CAAC;YACxC,CAAC;YAED,IAAI,CAAC,aAAa,CAAC;gBACjB,QAAQ;gBACR,UAAU,EAAE,CAAC,CAAC,aAAa,CAAC,eAAe;gBAC3C,UAAU,EAAE,aAAa,CAAC,UAAU;aACrC,CAAC,CAAC;YAEH,MAAM,UAAU,GAAG,sBAAsB,CAAC,aAAa,CAAC,CAAC;YAEzD,OAAO,UAAU,CAAC;QACpB,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { bundle, getEntriesMapFromPackage, getExternalsFromPackage } from '@ms-cloudpack/bundler';\nimport type { BundleOptions } from '@ms-cloudpack/common-types';\nimport { writeJson } from '@ms-cloudpack/json-utilities';\nimport { getExportsMap } from '@ms-cloudpack/package-utilities';\nimport { formatPackageName } from '@ms-cloudpack/task-reporter';\nimport path from 'path';\nimport { prepareOutputPath } from '../common/prepareOutputPath.js';\nimport type { BundleRequest } from '../types/BundleRequest.js';\nimport type { BundleTaskOptions } from '../types/BundleTaskOptions.js';\nimport { getBundleInfo } from './getBundleInfo.js';\nimport { getBundleLocation } from './getBundleLocation.js';\nimport { isCachedResultValid } from './isCachedResultValid.js';\nimport { readResultFromCache } from './readResultFromCache.js';\nimport { saveResultToCache } from './saveResultToCache.js';\nimport { formatBundleTaskResult } from './formatBundleTaskResult.js';\nimport type { PartialContext } from '../types/Context.js';\n\nexport type BundleTaskInternalOptions = BundleTaskOptions & { bundleRequest: BundleRequest };\nexport type BundleTaskInternalContext = PartialContext<\n 'packages' | 'packageHashes' | 'reporter' | 'telemetryClient',\n 'resolveMap' | 'config' | 'sequence' | 'cachePath'\n>;\n\n/**\n * Create and run a TaskReporter task which calls `bundle()` from `@ms-cloudpack/bundler` and formats the result.\n */\nexport async function bundleTask(\n options: BundleTaskInternalOptions,\n context: BundleTaskInternalContext,\n): Promise<void> {\n const { bundleRequest, force, hash, sourceHash } = options;\n const { packageName, version } = bundleRequest;\n const { reporter, telemetryClient, packageHashes, packages, session } = context;\n const { config, sequence } = session;\n const { mode } = config;\n const { retryCount } = options;\n\n const taskName = `Bundle ${formatPackageName({\n name: packageName,\n version,\n })}${retryCount ? ` (retry ${retryCount})` : ''}`;\n\n await reporter.runTask(taskName, async () => {\n await telemetryClient.tracer.startActiveSpan('BUNDLE_TASK', async (span) => {\n // If force is set, dispose the existing result.\n if (force && bundleRequest?.result?.dispose) {\n bundleRequest.result.dispose();\n bundleRequest.result = undefined;\n }\n\n const { packagePath, isExternal, isIncremental, disableSourceMaps, shouldGetBundleInfo } = bundleRequest;\n\n const outputPath =\n bundleRequest.outputPath ??\n (await getBundleLocation({ packagePath, shouldRecalculate: force, hash }, context)).path;\n\n // Rehydrate the result if not incremental.\n if (bundleRequest.result === undefined && !force) {\n bundleRequest.result = await readResultFromCache(outputPath, {\n inputPath: packagePath,\n });\n }\n\n const cacheValidationHash = !isExternal\n ? sourceHash ||\n (await packageHashes.get({ packagePath, isSourceHashingEnabled: true, shouldRecalculate: true }))\n : undefined;\n\n // if the cached result is valid, use it.\n if (!force && isCachedResultValid({ bundleRequest, hash: cacheValidationHash })) {\n console.debug(`Using cached result for ${bundleRequest.packageName}@${bundleRequest.version}`);\n bundleRequest.resultFromCache = true;\n } else {\n bundleRequest.resultFromCache = false;\n\n // Only use cached result if it's successful.\n await prepareOutputPath(outputPath);\n\n if (bundleRequest.result?.rebuild) {\n bundleRequest.result = {\n ...(await bundleRequest.result.rebuild()),\n outputPath: bundleRequest.result.outputPath,\n hash: cacheValidationHash,\n };\n } else {\n const {\n bundler,\n bundlerOptions,\n inlinedDependencies,\n dynamicImports,\n bundlerCapabilities,\n ignoredBundlerWarnings,\n } = (await packages.get(packagePath)).cloudpack || {};\n\n const bundleOptions: BundleOptions = {\n bundler,\n minify: mode === 'production',\n bundlerOptions,\n inputPath: packagePath,\n outputPath,\n incremental: isIncremental !== undefined ? isIncremental : false,\n sourcemap: !disableSourceMaps,\n entries: await getEntriesMapFromPackage({ inputPath: packagePath }, { packages, config }),\n inlined: inlinedDependencies,\n external: await getExternalsFromPackage({ inputPath: packagePath }, { packages }),\n dynamicImports,\n ignoredBundlerWarnings,\n bundlerCapabilities,\n };\n\n const bundleInternalResult = await bundle(bundleOptions, { config });\n bundleRequest.result = {\n ...bundleInternalResult,\n outputPath: bundleOptions.outputPath ?? outputPath,\n hash: cacheValidationHash,\n };\n }\n\n // Write the result to disk.\n await saveResultToCache(bundleRequest.result);\n }\n\n // If we should find required imports and exports per bundle\n if (shouldGetBundleInfo && !bundleRequest.result?.errors?.length && bundleRequest.result?.outputFiles?.length) {\n const bundleInfoPath = path.join(outputPath, 'bundle-info.json');\n\n // Exports map is needed to find the bundle info per entry we intend to bundle.\n // Exports map is used instead of bundleRequest.entries since it is easier to use\n // because it contains the paths other packages use to import the entry and\n // the relative location of the bundled files.\n const exportsMap = await getExportsMap({ packagePath }, { packages, config });\n\n const bundleInfo = await getBundleInfo({\n outputPath,\n outputFiles: bundleRequest.result.outputFiles,\n exportsMap,\n isExternal,\n packagePath,\n });\n\n bundleRequest.result.info = bundleInfo;\n\n // Write to cache for future use. (Ignore the promise result.)\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n writeJson(bundleInfoPath, bundleInfo);\n }\n\n span.setAttributes({\n sequence,\n isCacheHit: !!bundleRequest.resultFromCache,\n isExternal: bundleRequest.isExternal,\n });\n\n const taskResult = formatBundleTaskResult(bundleRequest);\n\n return taskResult;\n });\n });\n}\n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CAAC;gBAEvC,8DAA8D;gBAC9D,mEAAmE;gBACnE,SAAS,CAAC,cAAc,EAAE,UAAU,CAAC,CAAC;YACxC,CAAC;YAED,IAAI,CAAC,aAAa,CAAC;gBACjB,QAAQ;gBACR,UAAU,EAAE,CAAC,CAAC,aAAa,CAAC,eAAe;gBAC3C,UAAU,EAAE,aAAa,CAAC,UAAU;aACrC,CAAC,CAAC;YAEH,MAAM,UAAU,GAAG,sBAAsB,CAAC,aAAa,CAAC,CAAC;YAEzD,OAAO,UAAU,CAAC;QACpB,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { bundle, getEntriesMapFromPackage, getExternalsFromPackage } from '@ms-cloudpack/bundler';\nimport type { BundleOptions } from '@ms-cloudpack/common-types';\nimport { writeJson } from '@ms-cloudpack/json-utilities';\nimport { getExportsMap } from '@ms-cloudpack/package-utilities';\nimport { formatPackageName } from '@ms-cloudpack/task-reporter';\nimport path from 'path';\nimport { prepareOutputPath } from '../common/prepareOutputPath.js';\nimport type { BundleRequest } from '../types/BundleRequest.js';\nimport type { BundleTaskOptions } from '../types/BundleTaskOptions.js';\nimport { getBundleInfo } from './getBundleInfo.js';\nimport { getBundleLocation } from './getBundleLocation.js';\nimport { isCachedResultValid } from './isCachedResultValid.js';\nimport { readResultFromCache } from './readResultFromCache.js';\nimport { saveResultToCache } from './saveResultToCache.js';\nimport { formatBundleTaskResult } from './formatBundleTaskResult.js';\nimport type { PartialContext } from '../types/Context.js';\n\nexport type BundleTaskInternalOptions = BundleTaskOptions & { bundleRequest: BundleRequest };\nexport type BundleTaskInternalContext = PartialContext<\n 'packages' | 'packageHashes' | 'reporter' | 'telemetryClient',\n 'resolveMap' | 'config' | 'sequence' | 'cachePath'\n>;\n\n/**\n * Create and run a TaskReporter task which calls `bundle()` from `@ms-cloudpack/bundler` and formats the result.\n */\nexport async function bundleTask(\n options: BundleTaskInternalOptions,\n context: BundleTaskInternalContext,\n): Promise<void> {\n const { bundleRequest, force, hash, sourceHash } = options;\n const { packageName, version } = bundleRequest;\n const { reporter, telemetryClient, packageHashes, packages, session } = context;\n const { config, sequence } = session;\n const { mode } = config;\n const { retryCount } = options;\n\n const taskName = `Bundle ${formatPackageName({\n name: packageName,\n version,\n })}${retryCount ? ` (retry ${retryCount})` : ''}`;\n\n await reporter.runTask(taskName, async () => {\n await telemetryClient.tracer.startActiveSpan('BUNDLE_TASK', async (span) => {\n // If force is set, dispose the existing result.\n if (force && bundleRequest?.result?.dispose) {\n bundleRequest.result.dispose();\n bundleRequest.result = undefined;\n }\n\n const { packagePath, isExternal, isIncremental, disableSourceMaps, shouldGetBundleInfo } = bundleRequest;\n\n const outputPath =\n bundleRequest.outputPath ??\n (await getBundleLocation({ packagePath, shouldRecalculate: force, hash }, context)).path;\n\n // Rehydrate the result if not incremental.\n if (bundleRequest.result === undefined && !force) {\n bundleRequest.result = await readResultFromCache(outputPath, {\n inputPath: packagePath,\n });\n }\n\n const cacheValidationHash = !isExternal\n ? sourceHash ||\n (await packageHashes.get({ packagePath, isSourceHashingEnabled: true, shouldRecalculate: true }))\n : undefined;\n\n // if the cached result is valid, use it.\n if (!force && isCachedResultValid({ bundleRequest, hash: cacheValidationHash })) {\n console.debug(`Using cached result for ${bundleRequest.packageName}@${bundleRequest.version}`);\n bundleRequest.resultFromCache = true;\n } else {\n bundleRequest.resultFromCache = false;\n\n // Only use cached result if it's successful.\n await prepareOutputPath(outputPath);\n\n if (bundleRequest.result?.rebuild) {\n bundleRequest.result = {\n ...(await bundleRequest.result.rebuild()),\n outputPath: bundleRequest.result.outputPath,\n hash: cacheValidationHash,\n };\n } else {\n const {\n bundler,\n bundlerOptions,\n inlinedDependencies,\n dynamicImports,\n bundlerCapabilities,\n ignoredBundlerWarnings,\n } = (await packages.get(packagePath)).cloudpack || {};\n\n const bundleOptions: BundleOptions = {\n bundler,\n minify: mode === 'production',\n bundlerOptions,\n inputPath: packagePath,\n outputPath,\n incremental: isIncremental !== undefined ? isIncremental : false,\n sourcemap: !disableSourceMaps,\n entries: await getEntriesMapFromPackage({ inputPath: packagePath }, { packages, config }),\n inlined: inlinedDependencies,\n external: await getExternalsFromPackage({ inputPath: packagePath }, { packages }),\n dynamicImports,\n ignoredBundlerWarnings,\n bundlerCapabilities,\n };\n\n const bundleInternalResult = await bundle(bundleOptions, { config });\n if (bundleInternalResult.bundler) {\n span.setAttribute('bundler', bundleInternalResult.bundler);\n }\n bundleRequest.result = {\n ...bundleInternalResult,\n outputPath: bundleOptions.outputPath ?? outputPath,\n hash: cacheValidationHash,\n };\n }\n\n // Write the result to disk.\n await saveResultToCache(bundleRequest.result);\n }\n\n // If we should find required imports and exports per bundle\n if (shouldGetBundleInfo && !bundleRequest.result?.errors?.length && bundleRequest.result?.outputFiles?.length) {\n const bundleInfoPath = path.join(outputPath, 'bundle-info.json');\n\n // Exports map is needed to find the bundle info per entry we intend to bundle.\n // Exports map is used instead of bundleRequest.entries since it is easier to use\n // because it contains the paths other packages use to import the entry and\n // the relative location of the bundled files.\n const exportsMap = await getExportsMap({ packagePath }, { packages, config });\n\n const bundleInfo = await getBundleInfo({\n outputPath,\n outputFiles: bundleRequest.result.outputFiles,\n exportsMap,\n isExternal,\n packagePath,\n });\n\n bundleRequest.result.info = bundleInfo;\n\n // Write to cache for future use. (Ignore the promise result.)\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n writeJson(bundleInfoPath, bundleInfo);\n }\n\n span.setAttributes({\n sequence,\n isCacheHit: !!bundleRequest.resultFromCache,\n isExternal: bundleRequest.isExternal,\n });\n\n const taskResult = formatBundleTaskResult(bundleRequest);\n\n return taskResult;\n });\n });\n}\n"]}
@@ -1,7 +1,8 @@
1
1
  import type { BundleOutputFile, PackageJsonExports } from '@ms-cloudpack/common-types';
2
2
  import type { BundleInfo } from '../types/BundleInfo.js';
3
3
  /**
4
- * Returns a mapping from entry file path to list of paths that are produced and consumed in the searched files.
4
+ * Returns a mapping from entry file path (exports map key) to list of paths that are produced
5
+ * and consumed in that file.
5
6
  */
6
7
  export declare function getBundleInfo(params: {
7
8
  packagePath: string;
@@ -1 +1 @@
1
- {"version":3,"file":"getBundleInfo.d.ts","sourceRoot":"","sources":["../../src/utilities/getBundleInfo.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAIvF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEzD;;GAEG;AACH,wBAAsB,aAAa,CAAC,MAAM,EAAE;IAC1C,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,gBAAgB,EAAE,CAAC;IAChC,UAAU,EAAE,kBAAkB,CAAC;IAC/B,UAAU,EAAE,OAAO,CAAC;CACrB,GAAG,OAAO,CAAC,UAAU,CAAC,CAuHtB"}
1
+ {"version":3,"file":"getBundleInfo.d.ts","sourceRoot":"","sources":["../../src/utilities/getBundleInfo.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAIvF,OAAO,KAAK,EAAmB,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAG1E;;;GAGG;AACH,wBAAsB,aAAa,CAAC,MAAM,EAAE;IAC1C,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,gBAAgB,EAAE,CAAC;IAChC,UAAU,EAAE,kBAAkB,CAAC;IAC/B,UAAU,EAAE,OAAO,CAAC;CACrB,GAAG,OAAO,CAAC,UAAU,CAAC,CA+FtB"}
@@ -1,9 +1,10 @@
1
1
  import { getRuntimeEntryPaths } from '@ms-cloudpack/import-map';
2
- import { normalizeRelativePath } from '@ms-cloudpack/path-string-parsing';
2
+ import { normalizedPathRelativeTo } from '@ms-cloudpack/path-utilities';
3
3
  import path from 'path';
4
4
  import { getImportsAndExports } from './getImportsAndExports.js';
5
5
  /**
6
- * Returns a mapping from entry file path to list of paths that are produced and consumed in the searched files.
6
+ * Returns a mapping from entry file path (exports map key) to list of paths that are produced
7
+ * and consumed in that file.
7
8
  */
8
9
  export async function getBundleInfo(params) {
9
10
  const { packagePath, outputPath, outputFiles, exportsMap, isExternal } = params;
@@ -12,97 +13,74 @@ export async function getBundleInfo(params) {
12
13
  if (!outputFiles.length) {
13
14
  return bundleInfo;
14
15
  }
15
- /** Mapping from output file (safe/normalized relative path) to possible entry path and exports. */
16
- const outputFileInfo = {};
17
- outputFiles.forEach((file) => {
18
- // Normalize the path to start with ./ (or . for an empty path)
19
- const safePath = normalizeRelativePath(file.outputPath);
20
- // Store safe path to possible entry path and exports.
21
- outputFileInfo[safePath] = {
22
- entry: safePath,
23
- produces: new Set(file.exports),
24
- };
25
- });
26
- const repeatedExports = {};
27
- const entryPaths = getRuntimeEntryPaths({ packagePath, isExternal, exportsMap });
28
- for (const [importPath, actualEntryPath] of Object.entries(entryPaths)) {
29
- const safePath = normalizeRelativePath(actualEntryPath);
30
- if (outputFileInfo[safePath]) {
31
- if (repeatedExports[safePath]) {
32
- repeatedExports[safePath].push(importPath);
33
- }
34
- else {
35
- // Change best guess entry path to exports map entry.
36
- outputFileInfo[safePath].entry = importPath;
37
- repeatedExports[safePath] = [importPath];
38
- }
39
- }
16
+ /** Mapping from normalized relative output file path to info about which entry paths
17
+ * (exports map keys) pointed to that file, and what export names it produces.
18
+ * Usually there's at most one entry path per output file. */
19
+ const outputFileInfo = Object.fromEntries(outputFiles.map((file) => [
20
+ file.outputPath,
21
+ { exportsKeys: [], produces: new Set(file.exports) },
22
+ ]));
23
+ // For each entry path (exports map key), get the normalized relative path to the output file
24
+ // that will be used at runtime based on conditions.
25
+ const entryToOutputFile = getRuntimeEntryPaths({ packagePath, isExternal, exportsMap });
26
+ // Update the output file info with the entry paths (exports keys) that point to each output file.
27
+ // Usually there's at most one per output file (or none if it's a shared chunk).
28
+ for (const [entryPath, relOutputFile] of Object.entries(entryToOutputFile)) {
29
+ outputFileInfo[relOutputFile]?.exportsKeys.push(entryPath);
40
30
  }
41
- const localPathToSafe = {};
42
- Object.keys(outputFileInfo).forEach((safePath) => {
43
- localPathToSafe[path.resolve(outputPath, safePath)] = safePath;
44
- });
45
- const filePaths = Object.keys(localPathToSafe);
46
- const visitedPaths = new Set(filePaths);
47
- const pathsToParse = [...filePaths];
48
- while (pathsToParse.length) {
49
- const filePath = pathsToParse.shift();
31
+ // Build the bundle info based on imports and exports for each output file.
32
+ // exportsKeys are the export map key(s) that point to the output file.
33
+ for (const [relOutputFile, { exportsKeys, produces }] of Object.entries(outputFileInfo)) {
50
34
  // Ignore any non-JS/TS files such as SVGs and sourcemaps
51
- if (!filePath || path.extname(filePath) !== '.js') {
35
+ if (path.extname(relOutputFile) !== '.js') {
52
36
  continue;
53
37
  }
54
- const safePath = localPathToSafe[filePath];
55
- if (safePath === undefined || !outputFileInfo[safePath]) {
56
- throw new Error(`Found file that was not expected to be processed: ${filePath}`);
57
- }
58
- const parseResult = await getImportsAndExports(filePath, packagePath);
38
+ const absOutputFile = path.resolve(outputPath, relOutputFile);
39
+ const parseResult = await getImportsAndExports(absOutputFile, packagePath);
59
40
  if (!parseResult) {
60
41
  continue;
61
42
  }
62
43
  const { exportNames, imports, dynamicImports } = parseResult;
63
- const { entry, produces } = outputFileInfo[safePath];
64
44
  exportNames.forEach((name) => produces.add(name));
65
- bundleInfo[entry] ??= {
66
- bundlePath: safePath,
45
+ // Create a bundle info entry for this output file.
46
+ // If there wasn't an exports map key pointing to this file, just use the output path.
47
+ const pathsInBundleInfo = exportsKeys.length ? exportsKeys : [relOutputFile];
48
+ const fileBundleInfo = bundleInfo[pathsInBundleInfo[0]] || {
49
+ bundlePath: relOutputFile,
67
50
  produces: Array.from(produces),
68
51
  consumes: [],
69
52
  };
53
+ // Use the same object for all paths that point to this file.
54
+ pathsInBundleInfo.forEach((p) => (bundleInfo[p] = fileBundleInfo));
70
55
  if (dynamicImports.length) {
71
- bundleInfo[entry].dynamicImports = dynamicImports;
56
+ fileBundleInfo.dynamicImports = dynamicImports;
72
57
  }
73
58
  for (const { packageName, importPath, names } of imports) {
74
- if (packageName?.startsWith('.')) {
75
- const localPath = path.resolve(path.dirname(filePath), packageName, importPath || '');
76
- if (!visitedPaths.has(localPath)) {
77
- visitedPaths.add(localPath);
78
- pathsToParse.push(localPath);
79
- localPathToSafe[localPath] = importPath;
59
+ if (packageName === '.') {
60
+ const localPath = normalizedPathRelativeTo(outputPath, path.resolve(path.dirname(absOutputFile), importPath));
61
+ // Pretty sure any path in the current package which is imported in the bundle output should be
62
+ // in outputFiles, but make it obvious if not.
63
+ if (!outputFileInfo[localPath]) {
64
+ throw new Error(`Imported local file not found in output files for ${outputPath}: ${localPath} ` +
65
+ `(imported from ${absOutputFile} with import path "${importPath}")`);
80
66
  }
81
67
  }
82
- else if (packageName && !packageName.startsWith('node:')) {
83
- // Find if the import is already in the consumes list.
84
- const entryIndex = bundleInfo[entry].consumes.findIndex((c) => c.packageName === packageName && c.importPath === importPath);
85
- if (entryIndex < 0) {
86
- // If not, add it.
87
- bundleInfo[entry].consumes.push({
68
+ else if (!packageName.startsWith('node:')) {
69
+ // Find if the imported package is already in the consumes list.
70
+ const consumesFromPackage = fileBundleInfo.consumes.find((c) => c.packageName === packageName && c.importPath === importPath);
71
+ if (consumesFromPackage) {
72
+ // If so, add the names to the existing entry.
73
+ // This is necessary because the same import may be used in multiple places.
74
+ consumesFromPackage.names = Array.from(new Set([...names, ...consumesFromPackage.names]));
75
+ }
76
+ else {
77
+ // Otherwise, add it.
78
+ fileBundleInfo.consumes.push({
88
79
  packageName: packageName,
89
80
  importPath: importPath || '.',
90
81
  names: [...names],
91
82
  });
92
83
  }
93
- else {
94
- // If so, add the names to the existing entry.
95
- // This is necessary because the same import may be used in multiple places.
96
- bundleInfo[entry].consumes[entryIndex].names = Array.from(new Set([...names, ...bundleInfo[entry].consumes[entryIndex].names]));
97
- }
98
- }
99
- }
100
- if (repeatedExports[safePath]?.length > 1) {
101
- // Multiple entries for the same path.
102
- for (const repeatedEntry of repeatedExports[safePath]) {
103
- if (repeatedEntry !== entry) {
104
- bundleInfo[repeatedEntry] = bundleInfo[entry];
105
- }
106
84
  }
107
85
  }
108
86
  }
@@ -1 +1 @@
1
- {"version":3,"file":"getBundleInfo.js","sourceRoot":"","sources":["../../src/utilities/getBundleInfo.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AAC1E,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,MAMnC;IACC,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC;IAChF,MAAM,UAAU,GAAe,EAAE,CAAC;IAElC,8DAA8D;IAC9D,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC;QACxB,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,mGAAmG;IACnG,MAAM,cAAc,GAA6D,EAAE,CAAC;IACpF,WAAW,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QAC3B,+DAA+D;QAC/D,MAAM,QAAQ,GAAG,qBAAqB,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACxD,sDAAsD;QACtD,cAAc,CAAC,QAAQ,CAAC,GAAG;YACzB,KAAK,EAAE,QAAQ;YACf,QAAQ,EAAE,IAAI,GAAG,CAAS,IAAI,CAAC,OAAO,CAAC;SACxC,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,MAAM,eAAe,GAA6B,EAAE,CAAC;IACrD,MAAM,UAAU,GAAG,oBAAoB,CAAC,EAAE,WAAW,EAAE,UAAU,EAAE,UAA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AAa,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC;gBAChD,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import type { BundleOutputFile, PackageJsonExports } from '@ms-cloudpack/common-types';\nimport { getRuntimeEntryPaths } from '@ms-cloudpack/import-map';\nimport { normalizeRelativePath } from '@ms-cloudpack/path-string-parsing';\nimport path from 'path';\nimport type { BundleInfo } from '../types/BundleInfo.js';\nimport { getImportsAndExports } from './getImportsAndExports.js';\n/**\n * Returns a mapping from entry file path to list of paths that are produced and consumed in the searched files.\n */\nexport async function getBundleInfo(params: {\n packagePath: string;\n outputPath: string;\n outputFiles: BundleOutputFile[];\n exportsMap: PackageJsonExports;\n isExternal: boolean;\n}): Promise<BundleInfo> {\n const { packagePath, outputPath, outputFiles, exportsMap, isExternal } = params;\n const bundleInfo: BundleInfo = {};\n\n // If there are no output files, return the empty bundle info.\n if (!outputFiles.length) {\n return bundleInfo;\n }\n\n /** Mapping from output file (safe/normalized relative path) to possible entry path and exports. */\n const outputFileInfo: Record<string, { entry: string; produces: Set<string> }> = {};\n outputFiles.forEach((file) => {\n // Normalize the path to start with ./ (or . for an empty path)\n const safePath = normalizeRelativePath(file.outputPath);\n // Store safe path to possible entry path and exports.\n outputFileInfo[safePath] = {\n entry: safePath,\n produces: new Set<string>(file.exports),\n };\n });\n\n const repeatedExports: Record<string, string[]> = {};\n const entryPaths = getRuntimeEntryPaths({ packagePath, isExternal, exportsMap });\n\n for (const [importPath, actualEntryPath] of Object.entries(entryPaths)) {\n const safePath = normalizeRelativePath(actualEntryPath);\n\n if (outputFileInfo[safePath]) {\n if (repeatedExports[safePath]) {\n repeatedExports[safePath].push(importPath);\n } else {\n // Change best guess entry path to exports map entry.\n outputFileInfo[safePath].entry = importPath;\n repeatedExports[safePath] = [importPath];\n }\n }\n }\n\n const localPathToSafe: Record<string, string> = {};\n Object.keys(outputFileInfo).forEach((safePath) => {\n localPathToSafe[path.resolve(outputPath, safePath)] = safePath;\n });\n\n const filePaths = Object.keys(localPathToSafe);\n const visitedPaths = new Set(filePaths);\n const pathsToParse = [...filePaths];\n\n while (pathsToParse.length) {\n const filePath = pathsToParse.shift();\n // Ignore any non-JS/TS files such as SVGs and sourcemaps\n if (!filePath || path.extname(filePath) !== '.js') {\n continue;\n }\n\n const safePath = localPathToSafe[filePath];\n if (safePath === undefined || !outputFileInfo[safePath]) {\n throw new Error(`Found file that was not expected to be processed: ${filePath}`);\n }\n\n const parseResult = await getImportsAndExports(filePath, packagePath);\n if (!parseResult) {\n continue;\n }\n const { exportNames, imports, dynamicImports } = parseResult;\n\n const { entry, produces } = outputFileInfo[safePath];\n exportNames.forEach((name) => produces.add(name));\n\n bundleInfo[entry] ??= {\n bundlePath: safePath,\n produces: Array.from(produces),\n consumes: [],\n };\n\n if (dynamicImports.length) {\n bundleInfo[entry].dynamicImports = dynamicImports;\n }\n\n for (const { packageName, importPath, names } of imports) {\n if (packageName?.startsWith('.')) {\n const localPath = path.resolve(path.dirname(filePath), packageName, importPath || '');\n\n if (!visitedPaths.has(localPath)) {\n visitedPaths.add(localPath);\n pathsToParse.push(localPath);\n localPathToSafe[localPath] = importPath;\n }\n } else if (packageName && !packageName.startsWith('node:')) {\n // Find if the import is already in the consumes list.\n const entryIndex = bundleInfo[entry].consumes.findIndex(\n (c) => c.packageName === packageName && c.importPath === importPath,\n );\n if (entryIndex < 0) {\n // If not, add it.\n bundleInfo[entry].consumes.push({\n packageName: packageName,\n importPath: importPath || '.',\n names: [...names],\n });\n } else {\n // If so, add the names to the existing entry.\n // This is necessary because the same import may be used in multiple places.\n bundleInfo[entry].consumes[entryIndex].names = Array.from(\n new Set([...names, ...bundleInfo[entry].consumes[entryIndex].names]),\n );\n }\n }\n }\n if (repeatedExports[safePath]?.length > 1) {\n // Multiple entries for the same path.\n for (const repeatedEntry of repeatedExports[safePath]) {\n if (repeatedEntry !== entry) {\n bundleInfo[repeatedEntry] = bundleInfo[entry];\n }\n }\n }\n }\n\n return bundleInfo;\n}\n"]}
1
+ {"version":3,"file":"getBundleInfo.js","sourceRoot":"","sources":["../../src/utilities/getBundleInfo.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEjE;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,MAMnC;IACC,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC;IAChF,MAAM,UAAU,GAAe,EAAE,CAAC;IAElC,8DAA8D;IAC9D,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC;QACxB,OAAO,UAAU,CAAC;IACpB,CAAC;IAED;;iEAE6D;IAC7D,MAAM,cAAc,GAAG,MAAM,CAAC,WAAW,CACvC,WAAW,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QACxB,IAAI,CAAC,UAAU;QACf,EAAE,WAAW,EAAE,EAAc,EAAE,QAAQ,EAAE,IAAI,GAAG,CAAS,IAAI,CAAC,OAAO,CAAC,EAAE;KACzE,CAAC,CACH,CAAC;IAEF,6FAA6F;IAC7F,oDAAoD;IACpD,MAAM,iBAAiB,GAAG,oBAAoB,CAAC,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC,CAAC;IAExF,kGAAkG;IAClG,gFAAgF;IAChF,KAAK,MAAM,CAAC,SAAS,EAAE,aAAa,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAAE,CAAC;QAC3E,cAAc,CAAC,aAAa,CAAC,EAAE,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC7D,CAA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AAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import type { BundleOutputFile, PackageJsonExports } from '@ms-cloudpack/common-types';\nimport { getRuntimeEntryPaths } from '@ms-cloudpack/import-map';\nimport { normalizedPathRelativeTo } from '@ms-cloudpack/path-utilities';\nimport path from 'path';\nimport type { BundleEntryInfo, BundleInfo } from '../types/BundleInfo.js';\nimport { getImportsAndExports } from './getImportsAndExports.js';\n\n/**\n * Returns a mapping from entry file path (exports map key) to list of paths that are produced\n * and consumed in that file.\n */\nexport async function getBundleInfo(params: {\n packagePath: string;\n outputPath: string;\n outputFiles: BundleOutputFile[];\n exportsMap: PackageJsonExports;\n isExternal: boolean;\n}): Promise<BundleInfo> {\n const { packagePath, outputPath, outputFiles, exportsMap, isExternal } = params;\n const bundleInfo: BundleInfo = {};\n\n // If there are no output files, return the empty bundle info.\n if (!outputFiles.length) {\n return bundleInfo;\n }\n\n /** Mapping from normalized relative output file path to info about which entry paths\n * (exports map keys) pointed to that file, and what export names it produces.\n * Usually there's at most one entry path per output file. */\n const outputFileInfo = Object.fromEntries(\n outputFiles.map((file) => [\n file.outputPath,\n { exportsKeys: [] as string[], produces: new Set<string>(file.exports) },\n ]),\n );\n\n // For each entry path (exports map key), get the normalized relative path to the output file\n // that will be used at runtime based on conditions.\n const entryToOutputFile = getRuntimeEntryPaths({ packagePath, isExternal, exportsMap });\n\n // Update the output file info with the entry paths (exports keys) that point to each output file.\n // Usually there's at most one per output file (or none if it's a shared chunk).\n for (const [entryPath, relOutputFile] of Object.entries(entryToOutputFile)) {\n outputFileInfo[relOutputFile]?.exportsKeys.push(entryPath);\n }\n\n // Build the bundle info based on imports and exports for each output file.\n // exportsKeys are the export map key(s) that point to the output file.\n for (const [relOutputFile, { exportsKeys, produces }] of Object.entries(outputFileInfo)) {\n // Ignore any non-JS/TS files such as SVGs and sourcemaps\n if (path.extname(relOutputFile) !== '.js') {\n continue;\n }\n\n const absOutputFile = path.resolve(outputPath, relOutputFile);\n\n const parseResult = await getImportsAndExports(absOutputFile, packagePath);\n if (!parseResult) {\n continue;\n }\n const { exportNames, imports, dynamicImports } = parseResult;\n\n exportNames.forEach((name) => produces.add(name));\n\n // Create a bundle info entry for this output file.\n // If there wasn't an exports map key pointing to this file, just use the output path.\n const pathsInBundleInfo = exportsKeys.length ? exportsKeys : [relOutputFile];\n const fileBundleInfo: BundleEntryInfo = bundleInfo[pathsInBundleInfo[0]] || {\n bundlePath: relOutputFile,\n produces: Array.from(produces),\n consumes: [],\n };\n // Use the same object for all paths that point to this file.\n pathsInBundleInfo.forEach((p) => (bundleInfo[p] = fileBundleInfo));\n\n if (dynamicImports.length) {\n fileBundleInfo.dynamicImports = dynamicImports;\n }\n\n for (const { packageName, importPath, names } of imports) {\n if (packageName === '.') {\n const localPath = normalizedPathRelativeTo(outputPath, path.resolve(path.dirname(absOutputFile), importPath));\n // Pretty sure any path in the current package which is imported in the bundle output should be\n // in outputFiles, but make it obvious if not.\n if (!outputFileInfo[localPath]) {\n throw new Error(\n `Imported local file not found in output files for ${outputPath}: ${localPath} ` +\n `(imported from ${absOutputFile} with import path \"${importPath}\")`,\n );\n }\n } else if (!packageName.startsWith('node:')) {\n // Find if the imported package is already in the consumes list.\n const consumesFromPackage = fileBundleInfo.consumes.find(\n (c) => c.packageName === packageName && c.importPath === importPath,\n );\n if (consumesFromPackage) {\n // If so, add the names to the existing entry.\n // This is necessary because the same import may be used in multiple places.\n consumesFromPackage.names = Array.from(new Set([...names, ...consumesFromPackage.names]));\n } else {\n // Otherwise, add it.\n fileBundleInfo.consumes.push({\n packageName: packageName,\n importPath: importPath || '.',\n names: [...names],\n });\n }\n }\n }\n }\n\n return bundleInfo;\n}\n"]}
@@ -6,6 +6,7 @@ import type { ConsumedImport, DynamicImport } from '../types/BundleInfo.js';
6
6
  export declare function getImportsAndExports(filePath: string, packagePath?: string): Promise<{
7
7
  exportNames: Set<string>;
8
8
  imports: ConsumedImport[];
9
+ /** Dynamic (async) imports with non-literal paths consumed by this file. */
9
10
  dynamicImports: DynamicImport[];
10
11
  } | undefined>;
11
12
  //# sourceMappingURL=getImportsAndExports.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"getImportsAndExports.d.ts","sourceRoot":"","sources":["../../src/utilities/getImportsAndExports.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAE5E;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,QAAQ,EAAE,MAAM,EAChB,WAAW,CAAC,EAAE,MAAM,GACnB,OAAO,CACN;IACE,WAAW,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACzB,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,cAAc,EAAE,aAAa,EAAE,CAAC;CACjC,GACD,SAAS,CACZ,CAuIA"}
1
+ {"version":3,"file":"getImportsAndExports.d.ts","sourceRoot":"","sources":["../../src/utilities/getImportsAndExports.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAE5E;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,QAAQ,EAAE,MAAM,EAChB,WAAW,CAAC,EAAE,MAAM,GACnB,OAAO,CACN;IACE,WAAW,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACzB,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,4EAA4E;IAC5E,cAAc,EAAE,aAAa,EAAE,CAAC;CACjC,GACD,SAAS,CACZ,CAqIA"}
@@ -34,85 +34,86 @@ export async function getImportsAndExports(filePath, packagePath) {
34
34
  // es-module-lexer doesn't handle export * from statements correctly as it parses them as
35
35
  // imports but not as exports. We need to handle them separately.
36
36
  // TODO: Remove when https://github.com/guybedford/es-module-lexer/issues/76 is fixed
37
- const exportStarImport = [];
37
+ const exportStarPaths = [];
38
38
  const imports = [];
39
39
  const dynamicImports = [];
40
40
  for (const imprt of new Set(rawImports)) {
41
- // es-module-lexer returns entries where the "n" property equals the import source.
42
- // This includes the package name and path. For example, in this case:
41
+ if (imprt.d === -2) {
42
+ continue; // -2 means import.meta, which we don't care about
43
+ }
44
+ // es-module-lexer returns objects where the "n" property is the import source,
45
+ // e.g. "@fluentui/react/lib/Button" for this import:
43
46
  // import { Button } from '@fluentui/react/lib/Button';
44
- // imprt.n is "@fluentui/react/lib/Button"
47
+ // However, "n" will be undefined for import() if isn't a plain string literal.
45
48
  let importPath = imprt.n;
46
49
  // ss and se point to the entire import string's start/end
47
50
  const importCode = source.slice(imprt.ss, imprt.se);
48
51
  // s and e point to the specificer's start/end, including quotes -- e.g. "@fluentui/react/lib/Button"
49
52
  const importSpecifier = source.slice(imprt.s, imprt.e);
50
- if (!importPath) {
51
- if (imprt.d === -2) {
52
- continue; // -2 means import.meta, which we don't care about
53
- }
54
- // Currently when the import source is a backtick string, the path ("n" property) is undefined.
55
- // This is a limitation in es-module-lexer.
56
- if (/^`[^$`]+`$/.test(importSpecifier)) {
57
- // If it's a static string which happened to use backticks for some reason, we can parse that.
58
- importPath = importSpecifier.slice(1, -1);
53
+ // Currently when the import source is a backtick string, the path ("n" property) is undefined.
54
+ // This is a limitation in es-module-lexer.
55
+ if (/^`[^$`]+`$/.test(importSpecifier)) {
56
+ // If it's a static string which happened to use backticks for some reason, we can parse that.
57
+ importPath = importSpecifier.slice(1, -1);
58
+ }
59
+ // Handle literal paths first
60
+ if (importPath) {
61
+ // Handling `export * from` import statements
62
+ if (/export\s*\*\s*from/.test(importCode)) {
63
+ exportStarPaths.push(importPath);
59
64
  }
60
- else if (packagePath) {
61
- // Find the original source of the import.
62
- let rawSourceMap;
63
- let originalSource = null;
64
- try {
65
- rawSourceMap = JSON.parse(await fsPromises.readFile(`${filePath}.map`, 'utf-8'));
66
- const consumer = await new SourceMapConsumer(rawSourceMap);
67
- const pos = getLineAndColumn(source, imprt.s);
68
- const originalPos = consumer.originalPositionFor(pos);
69
- originalSource = originalPos.source;
70
- consumer.destroy(); // Clean up the consumer
71
- if (originalSource === null) {
72
- console.debug(`Failed to find original source for import:\nFilename:${filePath}\nImport:\n ${importCode}`);
73
- }
74
- }
75
- catch (err) {
76
- console.debug(`Failed to read sourcemap for import:\nFilename:${filePath}\nImport:\n ${importCode}`, err);
77
- }
78
- // Original source where the import was found.
79
- const absoluteImportSpecifier = originalSource
80
- ? path.resolve(path.dirname(filePath), originalSource)
81
- : filePath;
82
- let packageName = '.'; // Default to local package
83
- // Remove leading quote from the import specifier if it exists.
84
- const lazyCleanImportSpecifier = importSpecifier.replace(/^["'`]/, '');
85
- if (!lazyCleanImportSpecifier.startsWith('.')) {
86
- packageName = parseImportString(lazyCleanImportSpecifier).packageName;
87
- }
88
- dynamicImports.push({
89
- packageName,
90
- // Relative path from package path to file with import. Prefer original source if available.
91
- // or use the file path if original source is not available.
92
- importOrigin: normalizedPathRelativeTo(packagePath, absoluteImportSpecifier),
93
- importSpecifier,
94
- });
95
- continue;
65
+ let importedNames;
66
+ if (imprt.d >= 0) {
67
+ // This is a dynamic import. In this case we don't know which names are used, so assume all of them.
68
+ importedNames = ['*'];
96
69
  }
97
70
  else {
98
- console.debug(`Found an import that didn't have a static path:\nFilename:${filePath}\nImport:\n ${importCode}`);
99
- continue;
71
+ // Parse the import string into its component parts.
72
+ importedNames = parseNamedImports(importCode);
100
73
  }
74
+ imports.push({
75
+ ...parseImportString(importPath),
76
+ names: Array.from(new Set(importedNames)),
77
+ });
101
78
  }
102
- // Handling export * from import statements
103
- if (importCode.includes('export * from')) {
104
- exportStarImport.push(importPath);
79
+ else if (packagePath) {
80
+ // Non-literal path.
81
+ // Find the original source of the import.
82
+ let rawSourceMap;
83
+ let originalSource = null;
84
+ try {
85
+ rawSourceMap = JSON.parse(await fsPromises.readFile(`${filePath}.map`, 'utf-8'));
86
+ const consumer = await new SourceMapConsumer(rawSourceMap);
87
+ const pos = getLineAndColumn(source, imprt.s);
88
+ originalSource = consumer.originalPositionFor(pos).source;
89
+ consumer.destroy(); // Clean up the consumer
90
+ if (originalSource === null) {
91
+ console.debug(`Failed to find original source for import:\nFilename:${filePath}\nImport:\n ${importCode}`);
92
+ }
93
+ }
94
+ catch (err) {
95
+ console.debug(`Failed to read sourcemap for import:\nFilename:${filePath}\nImport:\n ${importCode}`, err);
96
+ }
97
+ // Original source where the import was found.
98
+ const absoluteImportSpecifier = originalSource ? path.resolve(path.dirname(filePath), originalSource) : filePath;
99
+ // TODO: This will give a bad path for a lot of template or concatenated strings
100
+ let packageName = '.'; // Default to local package
101
+ // Remove leading quote from the import specifier if it exists.
102
+ const cleanImportSpecifier = importSpecifier.replace(/^["'`]/, '');
103
+ if (!cleanImportSpecifier.startsWith('.')) {
104
+ packageName = parseImportString(cleanImportSpecifier).packageName;
105
+ }
106
+ dynamicImports.push({
107
+ packageName,
108
+ // Relative path from package path to file with import. Prefer original source if available.
109
+ // or use the file path if original source is not available.
110
+ importOrigin: normalizedPathRelativeTo(packagePath, absoluteImportSpecifier),
111
+ importSpecifier,
112
+ });
105
113
  }
106
- // Parse the import string into its component parts.
107
- const importedNames = parseNamedImports(importCode);
108
- if (imprt.d >= 0 && !importedNames.length) {
109
- // This is a dynamic import. In this case we don't know which names are used, so assume all of them.
110
- importedNames.push('*');
114
+ else {
115
+ console.debug(`Found an import that didn't have a static path:\nFilename:${filePath}\nImport:\n ${importCode}`);
111
116
  }
112
- imports.push({
113
- ...parseImportString(importPath),
114
- names: Array.from(new Set(importedNames)),
115
- });
116
117
  }
117
118
  // Processing exports is cheap as we already have to parse the source.
118
119
  // Helps find exports uncaught by output files.
@@ -127,7 +128,7 @@ export async function getImportsAndExports(filePath, packagePath) {
127
128
  console.debug(`Found an export that didn't parse correctly:\nFilename: ${filePath}\nExport:\n ${source.slice(exprt.s, exprt.e)}`);
128
129
  }
129
130
  }
130
- for (const exportPath of exportStarImport) {
131
+ for (const exportPath of exportStarPaths) {
131
132
  // This follows the following convention: https://github.com/guybedford/es-module-lexer/issues/76#issuecomment-868561807
132
133
  exportNames.add(`*${exportPath}`);
133
134
  }
@@ -1 +1 @@
1
- {"version":3,"file":"getImportsAndExports.js","sourceRoot":"","sources":["../../src/utilities/getImportsAndExports.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,KAAK,EAA8C,MAAM,iBAAiB,CAAC;AACpF,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAqB,MAAM,YAAY,CAAC;AAClE,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAGxE;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,QAAgB,EAChB,WAAoB;IASpB,IAAI,MAAc,CAAC;IACnB,IAAI,CAAC;QACH,MAAM,GAAG,MAAM,UAAU,CAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IACxD,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,oDAAoD;QACpD,OAAO,CAAC,IAAI,CAAC,kBAAkB,QAAQ,GAAG,EAAE,GAAG,CAAC,CAAC;QACjD,OAAO;IACT,CAAC;IAED,IAAI,UAAsC,CAAC;IAC3C,IAAI,UAAsC,CAAC;IAC3C,IAAI,CAAC;QACH,8DAA8D;QAC9D,2DAA2D;QAC3D,6DAA6D;QAC7D,CAAC,UAAU,EAAE,UAAU,CAAC,GAAG,MAAM,KAAK,CAAC,MAAM,CAAC,CAAC;IACjD,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,sDAAsD;QACtD,OAAO,CAAC,IAAI,CAAC,mBAAmB,QAAQ,KAAK,GAAG,iBAAiB,MAAM,EAAE,CAAC,CAAC;QAC3E,OAAO;IACT,CAAC;IAED,yFAAyF;IACzF,iEAAiE;IACjE,qFAAqF;IACrF,MAAM,gBAAgB,GAAG,EAAE,CAAC;IAE5B,MAAM,OAAO,GA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AC,MAAc,EAAE,QAAgB;IACxD,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,MAAM,GAAG,CAAC,CAAC;IAEf,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,EAAE,CAAC,EAAE,EAAE,CAAC;QAClC,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;YACvB,IAAI,EAAE,CAAC;YACP,MAAM,GAAG,CAAC,CAAC;QACb,CAAC;aAAM,CAAC;YACN,MAAM,EAAE,CAAC;QACX,CAAC;IACH,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["import { parseImportString, parseNamedImports } from '@ms-cloudpack/path-string-parsing';\nimport { parse, type ImportSpecifier, type ExportSpecifier } from 'es-module-lexer';\nimport fsPromises from 'fs/promises';\nimport { SourceMapConsumer, type RawSourceMap } from 'source-map';\nimport path from 'path';\nimport { normalizedPathRelativeTo } from '@ms-cloudpack/path-utilities';\nimport type { ConsumedImport, DynamicImport } from '../types/BundleInfo.js';\n\n/**\n * Get info about imports and exports from a file.\n * Returns undefined if the file doesn't exist or can't be parsed.\n */\nexport async function getImportsAndExports(\n filePath: string,\n packagePath?: string,\n): Promise<\n | {\n exportNames: Set<string>;\n imports: ConsumedImport[];\n dynamicImports: DynamicImport[];\n }\n | undefined\n> {\n let source: string;\n try {\n source = await fsPromises.readFile(filePath, 'utf-8');\n } catch (err) {\n // This could happen if a package is missing a file.\n console.warn(`Failed to read ${filePath}:`, err);\n return;\n }\n\n let rawImports: readonly ImportSpecifier[];\n let rawExports: readonly ExportSpecifier[];\n try {\n // es-module-lexer/parse may return Promise in some conditions\n // https://github.com/guybedford/es-module-lexer/issues/155\n // eslint-disable-next-line @typescript-eslint/await-thenable\n [rawImports, rawExports] = await parse(source);\n } catch (err) {\n // This could happen if the source file isn't valid JS\n console.warn(`Failed to parse ${filePath}: ${err}\\nSource is:\\n${source}`);\n return;\n }\n\n // es-module-lexer doesn't handle export * from statements correctly as it parses them as\n // imports but not as exports. We need to handle them separately.\n // TODO: Remove when https://github.com/guybedford/es-module-lexer/issues/76 is fixed\n const exportStarImport = [];\n\n const imports: ConsumedImport[] = [];\n const dynamicImports: DynamicImport[] = [];\n for (const imprt of new Set(rawImports)) {\n // es-module-lexer returns entries where the \"n\" property equals the import source.\n // This includes the package name and path. For example, in this case:\n // import { Button } from '@fluentui/react/lib/Button';\n // imprt.n is \"@fluentui/react/lib/Button\"\n let importPath = imprt.n;\n // ss and se point to the entire import string's start/end\n const importCode = source.slice(imprt.ss, imprt.se);\n // s and e point to the specificer's start/end, including quotes -- e.g. \"@fluentui/react/lib/Button\"\n const importSpecifier = source.slice(imprt.s, imprt.e);\n\n if (!importPath) {\n if (imprt.d === -2) {\n continue; // -2 means import.meta, which we don't care about\n }\n\n // Currently when the import source is a backtick string, the path (\"n\" property) is undefined.\n // This is a limitation in es-module-lexer.\n if (/^`[^$`]+`$/.test(importSpecifier)) {\n // If it's a static string which happened to use backticks for some reason, we can parse that.\n importPath = importSpecifier.slice(1, -1);\n } else if (packagePath) {\n // Find the original source of the import.\n let rawSourceMap: RawSourceMap;\n let originalSource: string | null = null;\n try {\n rawSourceMap = JSON.parse(await fsPromises.readFile(`${filePath}.map`, 'utf-8')) as RawSourceMap;\n const consumer = await new SourceMapConsumer(rawSourceMap);\n const pos = getLineAndColumn(source, imprt.s);\n const originalPos = consumer.originalPositionFor(pos);\n originalSource = originalPos.source;\n consumer.destroy(); // Clean up the consumer\n if (originalSource === null) {\n console.debug(`Failed to find original source for import:\\nFilename:${filePath}\\nImport:\\n ${importCode}`);\n }\n } catch (err) {\n console.debug(`Failed to read sourcemap for import:\\nFilename:${filePath}\\nImport:\\n ${importCode}`, err);\n }\n\n // Original source where the import was found.\n const absoluteImportSpecifier = originalSource\n ? path.resolve(path.dirname(filePath), originalSource)\n : filePath;\n\n let packageName = '.'; // Default to local package\n // Remove leading quote from the import specifier if it exists.\n const lazyCleanImportSpecifier = importSpecifier.replace(/^[\"'`]/, '');\n if (!lazyCleanImportSpecifier.startsWith('.')) {\n packageName = parseImportString(lazyCleanImportSpecifier).packageName;\n }\n dynamicImports.push({\n packageName,\n // Relative path from package path to file with import. Prefer original source if available.\n // or use the file path if original source is not available.\n importOrigin: normalizedPathRelativeTo(packagePath, absoluteImportSpecifier),\n importSpecifier,\n });\n continue;\n } else {\n console.debug(\n `Found an import that didn't have a static path:\\nFilename:${filePath}\\nImport:\\n ${importCode}`,\n );\n continue;\n }\n }\n\n // Handling export * from import statements\n if (importCode.includes('export * from')) {\n exportStarImport.push(importPath);\n }\n\n // Parse the import string into its component parts.\n const importedNames = parseNamedImports(importCode);\n if (imprt.d >= 0 && !importedNames.length) {\n // This is a dynamic import. In this case we don't know which names are used, so assume all of them.\n importedNames.push('*');\n }\n\n imports.push({\n ...parseImportString(importPath),\n names: Array.from(new Set<string>(importedNames)),\n });\n }\n\n // Processing exports is cheap as we already have to parse the source.\n // Helps find exports uncaught by output files.\n const exportNames = new Set<string>();\n for (const exprt of rawExports) {\n if (exprt.n) {\n // Exports don't need to be parsed as it is\n // already in the format we need.\n exportNames.add(exprt.n);\n } else {\n console.debug(\n `Found an export that didn't parse correctly:\\nFilename: ${filePath}\\nExport:\\n ${source.slice(exprt.s, exprt.e)}`,\n );\n }\n }\n\n for (const exportPath of exportStarImport) {\n // This follows the following convention: https://github.com/guybedford/es-module-lexer/issues/76#issuecomment-868561807\n exportNames.add(`*${exportPath}`);\n }\n\n return { exportNames, imports, dynamicImports };\n}\n\nfunction getLineAndColumn(source: string, position: number): { line: number; column: number } {\n let line = 1;\n let column = 1;\n\n for (let i = 0; i < position; i++) {\n if (source[i] === '\\n') {\n line++;\n column = 1;\n } else {\n column++;\n }\n }\n\n return { line, column };\n}\n"]}
1
+ {"version":3,"file":"getImportsAndExports.js","sourceRoot":"","sources":["../../src/utilities/getImportsAndExports.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,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,EAAE,CAAC;QAClC,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;YACvB,IAAI,EAAE,CAAC;YACP,MAAM,GAAG,CAAC,CAAC;QACb,CAAC;aAAM,CAAC;YACN,MAAM,EAAE,CAAC;QACX,CAAC;IACH,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["import { parseImportString, parseNamedImports } from '@ms-cloudpack/path-string-parsing';\nimport { parse, type ImportSpecifier, type ExportSpecifier } from 'es-module-lexer';\nimport fsPromises from 'fs/promises';\nimport { SourceMapConsumer, type RawSourceMap } from 'source-map';\nimport path from 'path';\nimport { normalizedPathRelativeTo } from '@ms-cloudpack/path-utilities';\nimport type { ConsumedImport, DynamicImport } from '../types/BundleInfo.js';\n\n/**\n * Get info about imports and exports from a file.\n * Returns undefined if the file doesn't exist or can't be parsed.\n */\nexport async function getImportsAndExports(\n filePath: string,\n packagePath?: string,\n): Promise<\n | {\n exportNames: Set<string>;\n imports: ConsumedImport[];\n /** Dynamic (async) imports with non-literal paths consumed by this file. */\n dynamicImports: DynamicImport[];\n }\n | undefined\n> {\n let source: string;\n try {\n source = await fsPromises.readFile(filePath, 'utf-8');\n } catch (err) {\n // This could happen if a package is missing a file.\n console.warn(`Failed to read ${filePath}:`, err);\n return;\n }\n\n let rawImports: readonly ImportSpecifier[];\n let rawExports: readonly ExportSpecifier[];\n try {\n // es-module-lexer/parse may return Promise in some conditions\n // https://github.com/guybedford/es-module-lexer/issues/155\n // eslint-disable-next-line @typescript-eslint/await-thenable\n [rawImports, rawExports] = await parse(source);\n } catch (err) {\n // This could happen if the source file isn't valid JS\n console.warn(`Failed to parse ${filePath}: ${err}\\nSource is:\\n${source}`);\n return;\n }\n\n // es-module-lexer doesn't handle export * from statements correctly as it parses them as\n // imports but not as exports. We need to handle them separately.\n // TODO: Remove when https://github.com/guybedford/es-module-lexer/issues/76 is fixed\n const exportStarPaths: string[] = [];\n\n const imports: ConsumedImport[] = [];\n const dynamicImports: DynamicImport[] = [];\n for (const imprt of new Set(rawImports)) {\n if (imprt.d === -2) {\n continue; // -2 means import.meta, which we don't care about\n }\n\n // es-module-lexer returns objects where the \"n\" property is the import source,\n // e.g. \"@fluentui/react/lib/Button\" for this import:\n // import { Button } from '@fluentui/react/lib/Button';\n // However, \"n\" will be undefined for import() if isn't a plain string literal.\n let importPath = imprt.n;\n // ss and se point to the entire import string's start/end\n const importCode = source.slice(imprt.ss, imprt.se);\n // s and e point to the specificer's start/end, including quotes -- e.g. \"@fluentui/react/lib/Button\"\n const importSpecifier = source.slice(imprt.s, imprt.e);\n\n // Currently when the import source is a backtick string, the path (\"n\" property) is undefined.\n // This is a limitation in es-module-lexer.\n if (/^`[^$`]+`$/.test(importSpecifier)) {\n // If it's a static string which happened to use backticks for some reason, we can parse that.\n importPath = importSpecifier.slice(1, -1);\n }\n\n // Handle literal paths first\n if (importPath) {\n // Handling `export * from` import statements\n if (/export\\s*\\*\\s*from/.test(importCode)) {\n exportStarPaths.push(importPath);\n }\n\n let importedNames: string[];\n if (imprt.d >= 0) {\n // This is a dynamic import. In this case we don't know which names are used, so assume all of them.\n importedNames = ['*'];\n } else {\n // Parse the import string into its component parts.\n importedNames = parseNamedImports(importCode);\n }\n\n imports.push({\n ...parseImportString(importPath),\n names: Array.from(new Set(importedNames)),\n });\n } else if (packagePath) {\n // Non-literal path.\n // Find the original source of the import.\n let rawSourceMap: RawSourceMap;\n let originalSource: string | null = null;\n try {\n rawSourceMap = JSON.parse(await fsPromises.readFile(`${filePath}.map`, 'utf-8')) as RawSourceMap;\n const consumer = await new SourceMapConsumer(rawSourceMap);\n const pos = getLineAndColumn(source, imprt.s);\n originalSource = consumer.originalPositionFor(pos).source;\n consumer.destroy(); // Clean up the consumer\n if (originalSource === null) {\n console.debug(`Failed to find original source for import:\\nFilename:${filePath}\\nImport:\\n ${importCode}`);\n }\n } catch (err) {\n console.debug(`Failed to read sourcemap for import:\\nFilename:${filePath}\\nImport:\\n ${importCode}`, err);\n }\n\n // Original source where the import was found.\n const absoluteImportSpecifier = originalSource ? path.resolve(path.dirname(filePath), originalSource) : filePath;\n\n // TODO: This will give a bad path for a lot of template or concatenated strings\n let packageName = '.'; // Default to local package\n // Remove leading quote from the import specifier if it exists.\n const cleanImportSpecifier = importSpecifier.replace(/^[\"'`]/, '');\n if (!cleanImportSpecifier.startsWith('.')) {\n packageName = parseImportString(cleanImportSpecifier).packageName;\n }\n dynamicImports.push({\n packageName,\n // Relative path from package path to file with import. Prefer original source if available.\n // or use the file path if original source is not available.\n importOrigin: normalizedPathRelativeTo(packagePath, absoluteImportSpecifier),\n importSpecifier,\n });\n } else {\n console.debug(`Found an import that didn't have a static path:\\nFilename:${filePath}\\nImport:\\n ${importCode}`);\n }\n }\n\n // Processing exports is cheap as we already have to parse the source.\n // Helps find exports uncaught by output files.\n const exportNames = new Set<string>();\n for (const exprt of rawExports) {\n if (exprt.n) {\n // Exports don't need to be parsed as it is\n // already in the format we need.\n exportNames.add(exprt.n);\n } else {\n console.debug(\n `Found an export that didn't parse correctly:\\nFilename: ${filePath}\\nExport:\\n ${source.slice(exprt.s, exprt.e)}`,\n );\n }\n }\n\n for (const exportPath of exportStarPaths) {\n // This follows the following convention: https://github.com/guybedford/es-module-lexer/issues/76#issuecomment-868561807\n exportNames.add(`*${exportPath}`);\n }\n\n return { exportNames, imports, dynamicImports };\n}\n\nfunction getLineAndColumn(source: string, position: number): { line: number; column: number } {\n let line = 1;\n let column = 1;\n\n for (let i = 0; i < position; i++) {\n if (source[i] === '\\n') {\n line++;\n column = 1;\n } else {\n column++;\n }\n }\n\n return { line, column };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ms-cloudpack/api-server",
3
- "version": "0.56.7",
3
+ "version": "0.56.8",
4
4
  "description": "An implementation of the API server that does interacts with a task scheduler.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -27,21 +27,21 @@
27
27
  "@lage-run/logger": "^1.3.0",
28
28
  "@lage-run/scheduler": "^1.2.1",
29
29
  "@lage-run/target-graph": "^0.9.0",
30
- "@ms-cloudpack/bundler": "^0.23.17",
30
+ "@ms-cloudpack/bundler": "^0.23.18",
31
31
  "@ms-cloudpack/common-types": "^0.23.4",
32
- "@ms-cloudpack/config": "^0.33.0",
32
+ "@ms-cloudpack/config": "^0.33.1",
33
33
  "@ms-cloudpack/create-express-app": "^1.10.6",
34
34
  "@ms-cloudpack/data-bus": "^0.4.2",
35
35
  "@ms-cloudpack/file-watcher": "^0.1.2",
36
- "@ms-cloudpack/import-map": "^0.8.15",
36
+ "@ms-cloudpack/import-map": "^0.8.16",
37
37
  "@ms-cloudpack/json-utilities": "^0.1.8",
38
- "@ms-cloudpack/package-hashes": "^0.7.11",
39
- "@ms-cloudpack/package-utilities": "^10.3.0",
38
+ "@ms-cloudpack/package-hashes": "^0.7.12",
39
+ "@ms-cloudpack/package-utilities": "^10.4.0",
40
40
  "@ms-cloudpack/path-string-parsing": "^1.2.5",
41
41
  "@ms-cloudpack/path-utilities": "^2.7.54",
42
- "@ms-cloudpack/remote-cache": "^0.9.10",
42
+ "@ms-cloudpack/remote-cache": "^0.9.11",
43
43
  "@ms-cloudpack/task-reporter": "^0.14.6",
44
- "@ms-cloudpack/telemetry": "^0.9.4",
44
+ "@ms-cloudpack/telemetry": "^0.9.5",
45
45
  "@trpc/client": "11.0.0-rc.608",
46
46
  "@trpc/server": "11.0.0-rc.608",
47
47
  "cors": "^2.8.5",