Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | 2x 2x 2x 2x 2x 2x 10x 2x 37x 37x 37x 37x 5x 24x 23x 21x 21x 1x 20x 8x 4x 4x 2x 216x 2x 12x 12x 2x 2x 2x 14x 14x 14x 14x 14x 2x 6x 6x 6x 6x 6x 6x 6x 6x 5x 20x 20x 15x 15x 20x 216x 216x 15x 15x 15x 10x 10x 10x 10x 10x 10x 201x 7x 7x 7x 7x 5x 20x 14x 14x 14x 15x 14x | import { composeSourcemap } from "../utils/compose-sourcemap";
import { isolateExternalImports } from "../utils/isolate-external-imports";
import type {
ExportAllDeclaration,
ExportNamedDeclaration,
ImportAttribute,
ImportDeclaration,
ImportExpression,
Literal,
Node,
ObjectExpression,
Property,
} from "estree";
import type { Plugin } from "vite";
import { walk } from "estree-walker";
/**
* The Vite counterpart of the rollup `seismic` plugin, and its replacement in
* `servicenowVitePlugins` -- it owns uxasset external resolution in both dev and
* build, so the rollup plugin is no longer in the Vite list at all.
*
* import "@servicenow/now-button" assert { external: "uxasset" };
*
* becomes
*
* import "/uxasset/externals/@servicenow/now-button/index.jsdbx";
*
* marked external, so in dev the browser fetches it through the dev proxy
* (`/uxasset/externals` is in `DEFAULT_PROXY_PATHS`) rather than Vite trying to
* bundle it, and in build it is left as an external import.
*/
import { UXASSET_EXTERNAL_PREFIX } from "../utils/constants";
const EXTENSION_FILTER = /\.(js|jsx|ts|tsx|mjs|mts|cjs|cts)($|\?)/;
/**
* Prefixes Vite's `base` onto an absolute path. A relative base (`"./"`)
* cannot be combined with an absolute path, so it is left alone.
* Only exported for testability.
*/
export const withBase = (base: string, absolutePath: string): string =>
!base || base === "/" || base.startsWith(".")
? absolutePath
: `${base.replace(/\/+$/, "")}${absolutePath}`;
export type ServicenowSeismicPluginOptions = {
filter?: (id: string) => boolean;
};
/**
* Vite plugin that rewrites `assert { external: "uxasset" }` /
* `with { external: "uxasset" }` imports to the ServiceNow externals path
* (`/uxasset/externals/<specifier>/index.jsdbx`).
*
* **Important:** packages that contain uxasset-external imports must be added
* to {@link https://vite.dev/config/dep-optimization-options.html#optimizedeps-exclude optimizeDeps.exclude}
* in the consuming project's Vite config. The dep optimizer runs its own
* Rolldown pipeline that does **not** invoke environment plugin `transform`
* hooks, so without the exclusion the import attributes are silently stripped
* and the imports are left un-transformed in dev.
*/
export function servicenowSeismicPlugin(
options: ServicenowSeismicPluginOptions = {},
): Plugin {
const { filter = (id: string) => EXTENSION_FILTER.test(id) } = options;
let externalPrefix = UXASSET_EXTERNAL_PREFIX;
// Separate plugin injected via the options hook so its generateBundle
// runs after all minifiers (SWC, esbuild, Vite's internal esbuild).
const isolateImportsPlugin: Plugin = {
name: "seismic:isolate-imports",
enforce: "post",
async generateBundle(_options, bundle) {
for (const chunk of Object.values(bundle)) {
if (chunk.type !== "chunk") continue;
const result = await isolateExternalImports(chunk.code, externalPrefix);
if (result) {
chunk.code = result.code;
composeSourcemap(chunk, result.map, bundle);
}
}
},
};
return {
name: "seismic",
enforce: "pre",
options(config) {
const plugins = config.plugins ?? [];
(plugins as Plugin[]).unshift(isolateImportsPlugin);
return { ...config, plugins };
},
configResolved(config) {
/**
* The externals prefix, including `base` in a build. In dev the dev server's
* import-analysis prefixes `base` onto every root-relative url it rewrites,
* so here it is only applied for builds.
*/
externalPrefix =
config.command === "build"
? withBase(config.base, UXASSET_EXTERNAL_PREFIX)
: UXASSET_EXTERNAL_PREFIX;
},
transform(code, id) {
if (!filter(id)) return null;
// Cheap bail before paying for a parse.
if (!code.includes("assert") && !code.includes("with")) return null;
let parsed;
try {
parsed = this.parse(code);
} catch {
// Leave malformed input to Vite's own parse, which reports it properly.
return null;
}
return rewriteExternals(code, parsed as Node, externalPrefix);
},
resolveId(source: string) {
if (!source.startsWith(externalPrefix)) {
return null;
}
return { id: source, external: true, resolvedBy: "seismic" };
},
// In build, `external: true` prevents load from ever being called.
// In dev, Vite still tries to load the module for its module graph;
// return an empty module so it doesn't error -- the browser fetches the
// real module through the dev proxy.
load(id) {
if (id.startsWith(UXASSET_EXTERNAL_PREFIX)) {
return "";
}
},
};
}
/**
* Rollup and Rolldown attach byte offsets to every AST node; `@types/estree`
* models positions as the optional `range`/`loc` instead, so the offsets are
* layered back on here.
*/
type Position<T> = T & { start: number; end: number };
/** A static import or re-export -- the declarations that take an attribute clause. */
type AttributeDeclaration =
| ImportDeclaration
| ExportAllDeclaration
| ExportNamedDeclaration;
const isAttributeDeclaration = (node: Node): node is AttributeDeclaration =>
node.type === "ImportDeclaration" ||
node.type === "ExportAllDeclaration" ||
node.type === "ExportNamedDeclaration";
const propertyKeyName = (property: Property): string | undefined => {
const { key } = property;
Eif (key.type === "Identifier") return key.name;
if (key.type === "Literal" && typeof key.value === "string") return key.value;
return undefined;
};
/** The attribute marking an import as a uxasset external. */
const externalAttribute = { key: "external", value: "uxasset" } as const;
/** The keys holding attributes on a dynamic `import(spec, { ... })`. */
const attributeSpecifiers: Set<string | undefined> = new Set([
"with",
"assert",
]);
/** True when an `ImportAttribute` list carries `external: "uxasset"`. */
const importHasExternal = (attributes: readonly ImportAttribute[]): boolean =>
attributes.some((attribute) => {
const { key, value } = attribute;
let name: string | undefined;
if (key.type === "Identifier") {
name = key.name;
} else Eif (key.type === "Literal" && typeof key.value === "string") {
name = key.value;
}
return (
name === externalAttribute.key && value.value === externalAttribute.value
);
});
/** The same check for a dynamic import's `{ with: { ... } }` options object. */
const dynamicImportHasExternal = (options: ObjectExpression): boolean =>
options.properties.some((property) => {
Iif (property.type !== "Property") return false;
Iif (!attributeSpecifiers.has(propertyKeyName(property))) {
return false;
}
const value = property.value;
Iif (value.type !== "ObjectExpression") return false;
return value.properties.some((attribute) => {
Iif (attribute.type !== "Property") return false;
if (propertyKeyName(attribute) !== externalAttribute.key) return false;
return (
attribute.value.type === "Literal" &&
attribute.value.value === externalAttribute.value
);
});
});
/**
* Walks `program`, rewriting every uxasset-external import/re-export so the
* specifier points at its externals path and the attribute clause is removed.
*
* Returns `{ code, map }` when at least one node was rewritten, `null` otherwise.
*/
function rewriteExternals(
code: string,
program: Node,
externalPrefix: string,
): { code: string; map: null } | null {
/** Edits collected during the walk, applied back-to-front afterwards. */
const edits: { start: number; end: number; replacement: string }[] = [];
/**
* Repoints a specifier at its externals path and removes the attributes
* that follow it, up to `removeThrough`.
*/
const externalize = (source: Position<Literal>, removeThrough: number) => {
Iif (typeof source.value !== "string") return;
edits.push({
start: source.start,
end: removeThrough,
replacement: JSON.stringify(
`${externalPrefix}${source.value}/index.jsdbx`,
),
});
};
walk(program, {
enter(n) {
const node = n as Node;
if (isAttributeDeclaration(node)) {
const attributes = node.attributes as Position<ImportAttribute>[];
const source = node.source as Position<Literal> | null;
if (source && attributes.length && importHasExternal(attributes)) {
// The clause-closing `}` sits between the last attribute and the
// declaration end. Search backward from the declaration end so we
// skip any `}` that might appear inside a comment between the two.
const lastEnd = attributes[attributes.length - 1].end;
const declEnd = (node as Position<Node>).end;
let clauseEnd = declEnd - 1;
while (clauseEnd >= lastEnd && code[clauseEnd] !== "}") clauseEnd--;
Eif (clauseEnd >= lastEnd) {
externalize(source, clauseEnd + 1);
}
}
} else if (node.type === "ImportExpression") {
const expression = node as Position<ImportExpression>;
const optionsArgument = expression.options as
| Position<ObjectExpression>
| undefined;
const { source } = expression;
// A non-literal specifier -- `import(name, ...)` -- cannot be rewritten
// statically, and is left for the runtime, as in a rollup build.
if (
optionsArgument?.type === "ObjectExpression" &&
source.type === "Literal" &&
dynamicImportHasExternal(optionsArgument)
) {
// Drop the whole options argument, comma included.
externalize(source as Position<Literal>, optionsArgument.end);
}
}
},
});
if (!edits.length) return null;
// Apply edits back-to-front so earlier offsets stay valid.
edits.sort((a, b) => b.start - a.start);
let result = code;
for (const { start, end, replacement } of edits) {
result = result.slice(0, start) + replacement + result.slice(end);
}
return { code: result, map: null };
}
|