@parcel/plugin 2.16.3 → 3.0.0-alpha.1

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.
@@ -0,0 +1,27 @@
1
+ import type { DiagnosticOptions, Transformer as TransformerOpts, Resolver as ResolverOpts, Namer as NamerOpts, Optimizer as OptimizerOpts, Reporter as ReporterOpts } from './types';
2
+ export * from './types';
3
+ // Parcel finds a plugin's methods under a key for the kind of plugin it is configured as, which
4
+ // every copy of this package agrees on. A plugin of another kind, or one written for Parcel 2,
5
+ // fails with a diagnostic rather than misbehaving.
6
+ export declare class Transformer<T> {
7
+ constructor(opts: TransformerOpts<T>);
8
+ }
9
+ export declare class Resolver<T> {
10
+ constructor(opts: ResolverOpts<T>);
11
+ }
12
+ export declare class Namer<T> {
13
+ constructor(opts: NamerOpts<T>);
14
+ }
15
+ export declare class Optimizer<T> {
16
+ constructor(opts: OptimizerOpts<T>);
17
+ }
18
+ export declare class Reporter<T> {
19
+ constructor(opts: ReporterOpts<T>);
20
+ }
21
+ /**
22
+ * An error carrying one or more diagnostics. Throw it from a plugin to fail with them, or pass
23
+ * it to a `console` method to log them at that level.
24
+ */ export declare class Diagnostic extends Error {
25
+ readonly diagnostics: Array<DiagnosticOptions>;
26
+ constructor(diagnostic: DiagnosticOptions | Array<DiagnosticOptions>);
27
+ }
package/lib/PluginAPI.js CHANGED
@@ -1,77 +1,54 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
1
+ export * from './types';
2
+ // Parcel finds a plugin's methods under a key for the kind of plugin it is configured as, which
3
+ // every copy of this package agrees on. A plugin of another kind, or one written for Parcel 2,
4
+ // fails with a diagnostic rather than misbehaving.
5
+ export class Transformer {
6
+ constructor(opts){
7
+ // @ts-ignore
8
+ this[Symbol.for('parcel.plugin.v3.transformer')] = opts;
9
+ }
10
+ }
11
+ export class Resolver {
12
+ constructor(opts){
13
+ // @ts-ignore
14
+ this[Symbol.for('parcel.plugin.v3.resolver')] = opts;
15
+ }
16
+ }
17
+ export class Namer {
18
+ constructor(opts){
19
+ // @ts-ignore
20
+ this[Symbol.for('parcel.plugin.v3.namer')] = opts;
21
+ }
22
+ }
23
+ export class Optimizer {
24
+ constructor(opts){
25
+ // @ts-ignore
26
+ this[Symbol.for('parcel.plugin.v3.optimizer')] = opts;
27
+ }
28
+ }
29
+ export class Reporter {
30
+ constructor(opts){
31
+ // @ts-ignore
32
+ this[Symbol.for('parcel.plugin.v3.reporter')] = opts;
33
+ }
34
+ }
35
+ /**
36
+ * An error carrying one or more diagnostics. Throw it from a plugin to fail with them, or pass
37
+ * it to a `console` method to log them at that level.
38
+ */ export class Diagnostic extends Error {
39
+ diagnostics;
40
+ constructor(diagnostic){
41
+ let diagnostics = Array.isArray(diagnostic) ? diagnostic : [
42
+ diagnostic
43
+ ];
44
+ super(diagnostics[0]?.message ?? '');
45
+ this.name = 'Diagnostic';
46
+ this.diagnostics = diagnostics;
47
+ }
48
+ }
49
+ // Parcel reads the diagnostics from this symbol, which every copy of this package agrees on.
50
+ Object.defineProperty(Diagnostic.prototype, Symbol.for('parcel-diagnostics'), {
51
+ get () {
52
+ return this.diagnostics;
53
+ }
5
54
  });
6
- exports.Validator = exports.Transformer = exports.Runtime = exports.Resolver = exports.Reporter = exports.Packager = exports.Optimizer = exports.Namer = exports.Compressor = exports.Bundler = void 0;
7
- const CONFIG = Symbol.for('parcel-plugin-config');
8
- class Transformer {
9
- constructor(opts) {
10
- // $FlowFixMe
11
- this[CONFIG] = opts;
12
- }
13
- }
14
- exports.Transformer = Transformer;
15
- class Resolver {
16
- constructor(opts) {
17
- // $FlowFixMe
18
- this[CONFIG] = opts;
19
- }
20
- }
21
- exports.Resolver = Resolver;
22
- class Bundler {
23
- constructor(opts) {
24
- // $FlowFixMe
25
- this[CONFIG] = opts;
26
- }
27
- }
28
- exports.Bundler = Bundler;
29
- class Namer {
30
- constructor(opts) {
31
- // $FlowFixMe
32
- this[CONFIG] = opts;
33
- }
34
- }
35
- exports.Namer = Namer;
36
- class Runtime {
37
- constructor(opts) {
38
- // $FlowFixMe
39
- this[CONFIG] = opts;
40
- }
41
- }
42
- exports.Runtime = Runtime;
43
- class Validator {
44
- constructor(opts) {
45
- // $FlowFixMe
46
- this[CONFIG] = opts;
47
- }
48
- }
49
- exports.Validator = Validator;
50
- class Packager {
51
- constructor(opts) {
52
- // $FlowFixMe
53
- this[CONFIG] = opts;
54
- }
55
- }
56
- exports.Packager = Packager;
57
- class Optimizer {
58
- constructor(opts) {
59
- // $FlowFixMe
60
- this[CONFIG] = opts;
61
- }
62
- }
63
- exports.Optimizer = Optimizer;
64
- class Compressor {
65
- constructor(opts) {
66
- // $FlowFixMe
67
- this[CONFIG] = opts;
68
- }
69
- }
70
- exports.Compressor = Compressor;
71
- class Reporter {
72
- constructor(opts) {
73
- // $FlowFixMe
74
- this[CONFIG] = opts;
75
- }
76
- }
77
- exports.Reporter = Reporter;
package/lib/types.d.ts ADDED
@@ -0,0 +1,584 @@
1
+ // Plugin API types for Parcel v3. These describe the objects exposed to
2
+ // JavaScript plugins by the QuickJS bindings in crates/plugin-js.
3
+ //
4
+ // Plugins log by calling `console` methods. Passing a `Diagnostic` (exported by
5
+ // `@parcel/plugin`) logs its diagnostics, with a severity matching the method's
6
+ // level unless they set one. Throwing (or rejecting) fails the plugin call. A
7
+ // thrown `Diagnostic` is reported as the diagnostics it was created with. For
8
+ // any other error, the message becomes a diagnostic, with a code frame pointing
9
+ // at `filename`/`fileName`, `line` and `column` if the error has them, or
10
+ // otherwise at the top frame of its stack. Diagnostics are attributed to the
11
+ // plugin unless they set `origin`.
12
+ //
13
+ // A plugin's methods are called with the object passed to its constructor (e.g.
14
+ // `new Transformer({...})`) as `this`, so they can call helper methods on it.
15
+ //
16
+ // Each worker thread runs plugins in its own JavaScript runtime, and calls run
17
+ // concurrently across threads. Module-level state is therefore not shared between
18
+ // calls, not even between a reporter's `log` and `buildSuccess` calls. Timers and
19
+ // I/O callbacks aren't available, so a promise must be settled by other promises
20
+ // or synchronous code.
21
+ export type FilePath = string;
22
+ export type Glob = string;
23
+ export type PackageName = string;
24
+ export type SemverRange = string;
25
+ /** See Dependency */ export type DependencySpecifier = string;
26
+ /** Plugins may return either a value or a promise for it. */ export type Async<T> = T | Promise<T>;
27
+ /** A JSON object (as in "map") */ export type JSONObject = {
28
+ [key: string]: JSONValue;
29
+ };
30
+ export type JSONValue = null | boolean | number | string | Array<JSONValue> | JSONObject;
31
+ /** A source map in the standard JSON format (version 3). */ export type SourceMapJSON = {
32
+ version: number;
33
+ sources: Array<string>;
34
+ mappings: string;
35
+ names?: Array<string>;
36
+ sourcesContent?: Array<string | null>;
37
+ sourceRoot?: string;
38
+ file?: string;
39
+ [key: string]: unknown;
40
+ };
41
+ /** A source map as a JSON object, a JSON string, or UTF-8 encoded JSON. */ export type SourceMapInput = SourceMapJSON | string | Uint8Array;
42
+ /** Line/column positions are 1-based (so <code>1</code> is the first line/column). */ export type Location = {
43
+ readonly line: number;
44
+ readonly column: number;
45
+ };
46
+ export type SourceLocation = {
47
+ readonly filePath: string;
48
+ /** inclusive */ readonly start: Location;
49
+ /** exclusive */ readonly end: Location;
50
+ };
51
+ /**
52
+ * - error: Fails the build.
53
+ * - warning: Logged, but does not fail the build.
54
+ * - sourceError: An error in source code in the project, or a warning in node_modules.
55
+ * - info: An informative message.
56
+ */ export type DiagnosticSeverity = 'error' | 'warning' | 'sourceError' | 'info';
57
+ export type DiagnosticCodeHighlight = {
58
+ /** Location of the first character that should get highlighted for this highlight. */ start: Location;
59
+ /** Location of the last character that should get highlighted for this highlight. Defaults to `start`. */ end?: Location;
60
+ /** A message that should be displayed at this location in the code. */ message?: string | null;
61
+ };
62
+ /**
63
+ * Describes how to format a code frame.
64
+ * A code frame is a visualization of a piece of code with a certain amount of
65
+ * code highlights that point to certain chunk(s) inside the code.
66
+ */ export type DiagnosticCodeFrame = {
67
+ /** The contents of the source file, if different from the file. If omitted, the file is read. */ code?: string | null;
68
+ /**
69
+ * Absolute path of the file this code frame is about. Diagnostics passed to reporters
70
+ * use `url` instead.
71
+ */ filePath?: string | null;
72
+ /** URL of the file this code frame is about. Files on disk use `file:` URLs. */ url?: string | null;
73
+ /** Language (file extension) of the code, used for syntax highlighting. */ language?: string | null;
74
+ codeHighlights: Array<DiagnosticCodeHighlight>;
75
+ };
76
+ /**
77
+ * A style agnostic way of emitting errors, warnings and info.
78
+ * Reporters are responsible for rendering the message, codeframes, hints, ...
79
+ *
80
+ * Diagnostics passed to reporters have every field.
81
+ */ export type DiagnosticOptions = {
82
+ /** This is the message you want to log. */ message: string;
83
+ /** Name of plugin or file that threw this error. Defaults to the plugin's name in .parcelrc. */ origin?: string | null;
84
+ /** Code frames point to certain location(s) in the file(s) this diagnostic is linked to. */ codeFrames?: Array<DiagnosticCodeFrame>;
85
+ /** A list of strings that suggest ways to resolve this issue */ hints?: Array<string>;
86
+ /** @default 'error' */ severity?: DiagnosticSeverity;
87
+ /** A URL to documentation to learn more about the diagnostic. */ documentationURL?: string | null;
88
+ };
89
+ export type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'verbose';
90
+ export type BuildMode = 'development' | 'production' | string;
91
+ export type HMROptions = {
92
+ readonly host: string;
93
+ readonly port: number;
94
+ };
95
+ export interface PluginOptions {
96
+ readonly mode: BuildMode;
97
+ readonly env: Readonly<Record<string, string>>;
98
+ readonly logLevel: LogLevel;
99
+ readonly hmrOptions: HMROptions | undefined;
100
+ readonly projectRoot: FilePath;
101
+ }
102
+ /**
103
+ * Corresponds to <code>pkg#engines</code>, resolved to minimum versions, which are
104
+ * formatted like `>= 18.2`.
105
+ */ export type Engines = {
106
+ /** The minimum browser versions, e.g. `chrome >= 63, firefox >= 67, safari >= 11.1`. Empty if none. */ readonly browsers: string;
107
+ readonly electron: string | null;
108
+ readonly node: string | null;
109
+ readonly parcel: string | null;
110
+ };
111
+ /** Corresponds to <code>pkg#targets.*.sourceMap</code> */ export type TargetSourceMapOptions = {
112
+ readonly sourceRoot: string | null;
113
+ readonly inline: boolean | null;
114
+ readonly inlineSources: boolean | null;
115
+ };
116
+ /** In which environment the output should run (influces e.g. bundle loaders) */ export type EnvironmentContext = 'browser' | 'web-worker' | 'service-worker' | 'worklet' | 'node' | 'electron-main' | 'electron-renderer' | 'react-client' | 'react-server';
117
+ /** The JS module format for the bundle output */ export type OutputFormat = 'esmodule' | 'commonjs' | 'global';
118
+ export type SourceType = 'script' | 'module';
119
+ /**
120
+ * Where and how an asset or bundle will run.
121
+ */ export interface Target {
122
+ /** The output folder */ readonly distDir: FilePath;
123
+ readonly publicUrl: string;
124
+ readonly engines: Engines;
125
+ /** Whether to include all/none packages \
126
+ * (<code>true / false</code>), an array of package names to include, or an object \
127
+ * (of a package is not specified, it's included).
128
+ */ readonly includeNodeModules: boolean | Array<PackageName> | Record<PackageName, boolean>;
129
+ readonly sourceMap: TargetSourceMapOptions | null;
130
+ readonly environment: EnvironmentContext;
131
+ readonly outputFormat: OutputFormat;
132
+ readonly sourceType: SourceType;
133
+ /** Whether this is a library build (e.g. less loaders) */ readonly isLibrary: boolean;
134
+ /** Whether the output should be minified. */ readonly shouldOptimize: boolean;
135
+ /** Whether <code>environment</code> specifies a browser context. */ isBrowser(): boolean;
136
+ /** Whether <code>environment</code> specifies a node context. */ isNode(): boolean;
137
+ /** Whether <code>environment</code> specifies an electron context. */ isElectron(): boolean;
138
+ /** Whether <code>environment</code> specifies a server context (node or react-server). */ isServer(): boolean;
139
+ /** Whether <code>environment</code> specifies a worker context. */ isWorker(): boolean;
140
+ /** Whether <code>environment</code> specifies a worklet context. */ isWorklet(): boolean;
141
+ }
142
+ export type DependencyPriority = 'sync' | 'parallel' | 'lazy';
143
+ export type SpecifierType = 'commonjs' | 'esm' | 'url' | 'custom';
144
+ export type BundleBehavior = 'inline' | 'isolated';
145
+ /**
146
+ * How the resolved asset is used by the importing asset.
147
+ * - javascript: Imported as a JavaScript module.
148
+ * - stylesheet: Imported as a CSS stylesheet.
149
+ * - url: Referenced by URL.
150
+ * - text: Imported as a string.
151
+ * - bytes: Imported as binary data.
152
+ */ export type ImportType = 'javascript' | 'stylesheet' | 'url' | 'text' | 'bytes';
153
+ /** The package.json "exports" and "imports" conditions supported by Parcel. */ export type PackageCondition = 'import' | 'require' | 'module' | 'node' | 'browser' | 'worker' | 'worklet' | 'electron' | 'development' | 'production' | 'types' | 'default' | 'style' | 'sass' | 'less' | 'stylus' | 'react-server' | 'source';
154
+ /**
155
+ * A package.json "exports" or "imports" condition. Parcel knows the `PackageCondition`s; any other
156
+ * string is a custom condition, which matches only itself.
157
+ */ export type PackageConditionName = PackageCondition | (string & {
158
+ });
159
+ /**
160
+ * Used when creating a Dependency, see that.
161
+ * @section transformer
162
+ */ export type DependencyOptions = {
163
+ /** The specifier used to resolve the dependency. */ readonly specifier: DependencySpecifier;
164
+ /**
165
+ * How the specifier should be interpreted.
166
+ * - esm: An ES module specifier. It is parsed as a URL, but bare specifiers are treated as node_modules.
167
+ * - commonjs: A CommonJS specifier. It is not parsed as a URL.
168
+ * - url: A URL that works as in a browser. Bare specifiers are treated as relative URLs.
169
+ * - custom: A custom specifier. Must be handled by a custom resolver plugin.
170
+ * @default 'esm'
171
+ */ readonly specifierType?: SpecifierType | null;
172
+ /**
173
+ * When the dependency should be loaded.
174
+ * - sync: The dependency should be resolvable synchronously. The resolved asset will be placed
175
+ * in the same bundle as the parent, or another bundle that's already on the page.
176
+ * - parallel: The dependency should be placed in a separate bundle that's loaded in parallel
177
+ * with the current bundle.
178
+ * - lazy: The dependency should be placed in a separate bundle that's loaded later.
179
+ * @default 'sync'
180
+ */ readonly priority?: DependencyPriority | null;
181
+ /**
182
+ * Controls the behavior of the bundle the resolved asset is placed into. Use in combination with `priority`
183
+ * to determine when the bundle is loaded.
184
+ * - inline: The resolved asset will be placed into a new inline bundle. Inline bundles are not written
185
+ * to a separate file, but embedded into the parent bundle.
186
+ * - isolated: The resolved asset will be isolated from its parents in a separate bundle.
187
+ * Shared assets will be duplicated.
188
+ */ readonly bundleBehavior?: BundleBehavior | 'none' | null;
189
+ /**
190
+ * How the resolved asset is used by the importing asset.
191
+ * @default 'javascript'
192
+ */ readonly importType?: ImportType | null;
193
+ /**
194
+ * When the dependency is a bundle entry (priority is "parallel" or "lazy"), this controls the naming
195
+ * of that bundle. `needsStableName` indicates that the name should be stable over time, even when the
196
+ * content of the bundle changes. This is useful for entries that a user would manually enter the URL
197
+ * for, as well as for things like service workers or RSS feeds, where the URL must remain consistent
198
+ * over time.
199
+ */ readonly needsStableName?: boolean | null;
200
+ /** Whether the dependency is optional. If the dependency cannot be resolved, this will not fail the build. */ readonly isOptional?: boolean | null;
201
+ /** Whether the dependency is an entry. */ readonly isEntry?: boolean | null;
202
+ /** Whether the dependency has side effects. */ readonly sideEffects?: boolean | null;
203
+ /**
204
+ * The location within the source file where the dependency was found.
205
+ * `filePath` may be an absolute path or a URL, and defaults to the asset's.
206
+ */ readonly loc?: {
207
+ readonly filePath?: string | null;
208
+ readonly start: Location;
209
+ readonly end: Location;
210
+ } | null;
211
+ /**
212
+ * The target to resolve the dependency in. Must be a Target obtained from Parcel,
213
+ * e.g. from an asset or dependency. Defaults to the asset's target.
214
+ */ readonly target?: Target | null;
215
+ /** A list of package.json "exports" and "imports" conditions to use when resolving the dependency. */ readonly packageConditions?: Array<PackageConditionName> | null;
216
+ /** The pipeline defined in .parcelrc that the dependency should be processed with. */ readonly pipeline?: string | null;
217
+ /**
218
+ * The absolute file path or URL where the dependency should be resolved from.
219
+ * By default, this is the source file where the dependency was specified.
220
+ */ readonly resolveFrom?: string | null;
221
+ /** The semver version range expected for the dependency. */ readonly range?: SemverRange | null;
222
+ };
223
+ /**
224
+ * A Dependency denotes a connection between two assets \
225
+ * (likely some effect from the importee is expected - be it a side effect or a value is being imported).
226
+ *
227
+ * @section transformer
228
+ */ export interface Dependency {
229
+ /** The specifier used to resolve the dependency. */ readonly specifier: DependencySpecifier;
230
+ /**
231
+ * How the specifier should be interpreted.
232
+ * - esm: An ES module specifier. It is parsed as a URL, but bare specifiers are treated as node_modules.
233
+ * - commonjs: A CommonJS specifier. It is not parsed as a URL.
234
+ * - url: A URL that works as in a browser. Bare specifiers are treated as relative URLs.
235
+ * - custom: A custom specifier. Must be handled by a custom resolver plugin.
236
+ */ readonly specifierType: SpecifierType;
237
+ /**
238
+ * When the dependency should be loaded.
239
+ * - sync: The dependency should be resolvable synchronously. The resolved asset will be placed
240
+ * in the same bundle as the parent, or another bundle that's already on the page.
241
+ * - parallel: The dependency should be placed in a separate bundle that's loaded in parallel
242
+ * with the current bundle.
243
+ * - lazy: The dependency should be placed in a separate bundle that's loaded later.
244
+ */ readonly priority: DependencyPriority;
245
+ /**
246
+ * Controls the behavior of the bundle the resolved asset is placed into. Use in combination with `priority`
247
+ * to determine when the bundle is loaded.
248
+ * - inline: The resolved asset will be placed into a new inline bundle. Inline bundles are not written
249
+ * to a separate file, but embedded into the parent bundle.
250
+ * - isolated: The resolved asset will be isolated from its parents in a separate bundle.
251
+ * Shared assets will be duplicated.
252
+ */ readonly bundleBehavior: BundleBehavior | undefined;
253
+ /** How the resolved asset is used by the importing asset. */ readonly importType: ImportType;
254
+ /**
255
+ * When the dependency is a bundle entry (priority is "parallel" or "lazy"), this controls the naming
256
+ * of that bundle. `needsStableName` indicates that the name should be stable over time, even when the
257
+ * content of the bundle changes. This is useful for entries that a user would manually enter the URL
258
+ * for, as well as for things like service workers or RSS feeds, where the URL must remain consistent
259
+ * over time.
260
+ */ readonly needsStableName: boolean;
261
+ /** Whether the dependency is optional. If the dependency cannot be resolved, this will not fail the build. */ readonly isOptional: boolean;
262
+ /** Whether the dependency is an entry. */ readonly isEntry: boolean;
263
+ /** Whether the dependency has side effects. */ readonly sideEffects: boolean;
264
+ /** The location within the source file where the dependency was found. */ readonly loc: SourceLocation | undefined;
265
+ /** The target the dependency is resolved in. */ readonly target: Target;
266
+ /** The package.json "exports" and "imports" conditions used to resolve the dependency. */ readonly packageConditions: Array<PackageConditionName>;
267
+ /**
268
+ * The path of the file the dependency is resolved from: the `resolveFrom` it was created with,
269
+ * or else the file it was found in. `undefined` when that is not a file on disk.
270
+ */ readonly resolveFrom: FilePath | undefined;
271
+ /** The semver version range expected for the dependency. */ readonly range: SemverRange | undefined;
272
+ /**
273
+ * A unique string that a transformer can embed in the asset's content to refer to the
274
+ * dependency. It is replaced with the resolved bundle URL or module id during packaging.
275
+ */ readonly placeholder: string | undefined;
276
+ }
277
+ /**
278
+ * An asset represents a file or part of a file. It may represent any data type, including source code,
279
+ * binary data, etc. Assets may exist in the file system or may be virtual.
280
+ *
281
+ * Assets passed to namers, optimizers and reporters are read-only, and can only be
282
+ * accessed during the plugin call they were passed to.
283
+ *
284
+ * @section transformer
285
+ */ export interface Asset {
286
+ /** The URL of the asset, including its query. Files on disk use `file:` URLs. */ readonly url: string;
287
+ /** The file path of the asset. */ readonly filePath: FilePath;
288
+ /**
289
+ * The asset's type. This initially corresponds to the source file extension,
290
+ * but it may be changed during transformation.
291
+ */ readonly type: string;
292
+ /** The target of the asset. */ readonly target: Target;
293
+ /**
294
+ * Whether this asset is part of the project, and not an external dependency (e.g. in node_modules).
295
+ * This indicates that transformation using the project's configuration should be applied.
296
+ */ readonly isSource: boolean;
297
+ /**
298
+ * Controls which bundle the asset is placed into.
299
+ * - inline: The asset will be placed into a new inline bundle. Inline bundles are not written
300
+ * to a separate file, but embedded into the parent bundle.
301
+ * - isolated: The asset will be isolated from its parents in a separate bundle. Shared assets
302
+ * will be duplicated.
303
+ */ readonly bundleBehavior: BundleBehavior | undefined;
304
+ /**
305
+ * Whether this asset can be omitted if none of its exports are being used.
306
+ * This is initially set by the resolver, but can be overridden by transformers.
307
+ */ readonly sideEffects: boolean;
308
+ /** A key that identifies the asset, set by a transformer. */ readonly uniqueKey: string | undefined;
309
+ /** The pipeline defined in .parcelrc that the asset should be processed with. */ readonly pipeline: string | undefined;
310
+ /** Returns the asset contents as a string. */ getCode(): string;
311
+ /** Returns the asset contents as bytes. */ getBuffer(): Uint8Array;
312
+ /** Returns a copy of the source map for the asset, if available. */ getMap(): SourceMapJSON | null;
313
+ /** Returns a snapshot of the asset's dependencies. */ getDependencies(): Array<Dependency>;
314
+ }
315
+ /**
316
+ * A mutable Asset, available during transformation.
317
+ * @section transformer
318
+ */ export interface MutableAsset extends Asset {
319
+ /**
320
+ * The asset's type. This initially corresponds to the source file extension,
321
+ * but it may be changed during transformation.
322
+ */ type: string;
323
+ get bundleBehavior(): BundleBehavior | undefined;
324
+ set bundleBehavior(value: BundleBehavior | 'none' | null | undefined);
325
+ /**
326
+ * Whether this asset can be omitted if none of its exports are being used.
327
+ * This is initially set by the resolver, but can be overridden by transformers.
328
+ */ sideEffects: boolean;
329
+ get uniqueKey(): string | undefined;
330
+ set uniqueKey(value: string | null | undefined);
331
+ get pipeline(): string | undefined;
332
+ set pipeline(value: string | null | undefined);
333
+ /**
334
+ * Adds a dependency to the asset. Returns the dependency's placeholder, which can be
335
+ * embedded in the asset's content to refer to the resolved dependency.
336
+ */ addDependency(options: DependencyOptions): string;
337
+ /**
338
+ * Adds a url dependency to the asset.
339
+ * This is a shortcut for addDependency that defaults the specifierType and importType
340
+ * to 'url' and the priority to 'lazy'. Returns the dependency's placeholder.
341
+ */ addURLDependency(url: string, options?: Partial<Omit<DependencyOptions, 'specifier'>>): string;
342
+ /**
343
+ * Sets the asset contents as a string, and optionally its source map. A map that isn't a JSON
344
+ * object throws a TypeError.
345
+ */ setCode(code: string, map?: SourceMapInput | null): void;
346
+ /**
347
+ * Sets the asset contents as bytes, and optionally its source map. A map that isn't a JSON
348
+ * object throws a TypeError.
349
+ */ setBuffer(buffer: Uint8Array, map?: SourceMapInput | null): void;
350
+ }
351
+ /**
352
+ * A Bundle (a collection of assets)
353
+ *
354
+ * Bundles can only be accessed during the plugin call they were passed to.
355
+ *
356
+ * @section bundler
357
+ */ export interface Bundle {
358
+ /** The type of the bundle. */ readonly type: string;
359
+ /** The bundle's target. */ readonly target: Target;
360
+ /** Whether the bundle is an entry. */ readonly isEntry: boolean;
361
+ /**
362
+ * Indicates that the bundle's file name should be stable over time, even when the content of the bundle
363
+ * changes. This is useful for entries that a user would manually enter the URL for, as well as for things
364
+ * like service workers or RSS feeds, where the URL must remain consistent over time.
365
+ */ readonly needsStableName: boolean;
366
+ /**
367
+ * Controls the behavior of the bundle.
368
+ * - inline: Inline bundles are not written to a separate file, but embedded into the parent bundle.
369
+ * - isolated: The bundle will be isolated from its parents. Shared assets will be duplicated.
370
+ */ readonly bundleBehavior: BundleBehavior | undefined;
371
+ /**
372
+ * A placeholder for the bundle's content hash. A namer must include it exactly once in the
373
+ * name of a bundle that may be content hashed. It is replaced with a content hash of the
374
+ * bundle after packaging and optimizing.
375
+ */ readonly hashReference: string;
376
+ /**
377
+ * The absolute path the bundle is written to, once it is known. `null` for inline bundles,
378
+ * before the bundle is named, and while a content hashed name is unknown.
379
+ */ readonly filePath: FilePath | null;
380
+ /**
381
+ * The bundle's name: its file path relative to its target's <code>distDir</code>.
382
+ * `null` until it can be read, i.e. before the bundle is named, or while a content hashed
383
+ * name is unknown.
384
+ */ readonly name: string | null;
385
+ /**
386
+ * Returns the assets that are executed immediately when the bundle is loaded.
387
+ * Some bundles may not have any entry assets, for example, shared bundles.
388
+ */ getEntryAssets(): Array<Asset>;
389
+ /**
390
+ * Returns the main entry of the bundle, which will provide the bundle's exports.
391
+ * Some bundles do not have a main entry, for example, shared bundles.
392
+ */ getMainEntry(): Asset | undefined;
393
+ /** Returns whether the bundle includes the given asset. */ hasAsset(asset: Asset): boolean;
394
+ }
395
+ /**
396
+ * A Graph that contains Bundle-s.
397
+ * @section bundler
398
+ */ export interface BundleGraph {
399
+ /** Returns a list of bundles in the bundle graph. */ getBundles(): Array<Bundle>;
400
+ /** Returns a list of entry bundles. */ getEntryBundles(): Array<Bundle>;
401
+ /** Returns a list of bundles that are referenced by this bundle. */ getReferencedBundles(bundle: Bundle, options?: {
402
+ recursive?: boolean;
403
+ }): Array<Bundle>;
404
+ /**
405
+ * Returns the bundles that code in the bundle's execution context may load: everything
406
+ * reachable through bundle references and Parcel's loader, without entering other
407
+ * execution contexts (e.g. workers). The bundle itself is not included.
408
+ */ getBundlesInBundleGroup(bundle: Bundle): Array<Bundle>;
409
+ /**
410
+ * Returns the bundles that dependencies of the bundle's assets resolve to,
411
+ * e.g. lazy, isolated, inline and URL references.
412
+ */ getBundleDependencies(bundle: Bundle): Array<Bundle>;
413
+ /** Returns the asset that the dependency resolved to, if any. */ getResolvedAsset(dependency: Dependency): Asset | undefined;
414
+ /** Returns the bundle that the dependency references, if it resolved to another bundle. */ getReferencedBundle(dependency: Dependency): Bundle | undefined;
415
+ }
416
+ /**
417
+ * @section transformer
418
+ */ export type ResolveOptions = {
419
+ /**
420
+ * How the specifier should be interpreted.
421
+ * - esm: An ES module specifier. It is parsed as a URL, but bare specifiers are treated as node_modules.
422
+ * - commonjs: A CommonJS specifier. It is not parsed as a URL.
423
+ * - url: A URL that works as in a browser. Bare specifiers are treated as relative URLs.
424
+ * - custom: A specifier only a resolver plugin knows how to interpret.
425
+ * @default 'esm'
426
+ */ readonly specifierType?: SpecifierType;
427
+ /**
428
+ * How the resolved file is used, as for a dependency. A file resolved as `javascript` must have a
429
+ * transformer that turns it into JavaScript, or resolving it fails. Use `url` to resolve any file,
430
+ * e.g. to read it yourself.
431
+ * @default 'javascript'
432
+ */ readonly importType?: ImportType;
433
+ /** A list of conditions to use when resolving package.json "exports" and "imports". */ readonly packageConditions?: Array<PackageConditionName>;
434
+ };
435
+ /**
436
+ * What a `ResolveFn` resolved a specifier to: a file, or an external or excluded dependency.
437
+ * @section transformer
438
+ */ export type ResolvedFile = {
439
+ /** The absolute path of the resolved file. */ readonly filePath: FilePath;
440
+ /** The named pipeline the resolver chose for the file, if any. */ readonly pipeline: string | null;
441
+ /** The query the resolver gave the file, if any. */ readonly query: string | null;
442
+ /** Corresponds to Asset's <code>sideEffects</code>. */ readonly sideEffects: boolean;
443
+ readonly isExternal?: undefined;
444
+ readonly isExcluded?: undefined;
445
+ } | {
446
+ readonly isExternal: true;
447
+ readonly filePath?: undefined;
448
+ readonly isExcluded?: undefined;
449
+ } | {
450
+ readonly isExcluded: true;
451
+ readonly filePath?: undefined;
452
+ readonly isExternal?: undefined;
453
+ };
454
+ /**
455
+ * Resolves `specifier` from the file `from` with the resolvers configured in .parcelrc, exactly as
456
+ * a dependency of the asset would be. Returns `null` when no resolver resolves it. Rejects with a
457
+ * `Diagnostic` carrying the resolvers' diagnostics when one fails, which reports them unchanged
458
+ * if thrown. Every file the resolvers read invalidates the asset.
459
+ * @section transformer
460
+ */ export type ResolveFn = (from: FilePath, specifier: string, options?: ResolveOptions) => Promise<ResolvedFile | null>;
461
+ /**
462
+ * The methods for a transformer plugin.
463
+ *
464
+ * `config` is the configuration given for the plugin in .parcelrc, if any.
465
+ * @section transformer
466
+ */ export type Transformer<ConfigType> = {
467
+ /** Transform the asset in place. */ transform(args: {
468
+ asset: MutableAsset;
469
+ config: ConfigType;
470
+ resolve: ResolveFn;
471
+ options: PluginOptions;
472
+ }): Async<void>;
473
+ };
474
+ /**
475
+ * @section resolver
476
+ */ export type ResolveResult = {
477
+ /** An absolute path to the resolved file. */ readonly filePath?: FilePath | null;
478
+ /**
479
+ * An optional named pipeline to use to compile the resolved file. Defaults to the
480
+ * dependency's pipeline. `null` removes the pipeline.
481
+ */ readonly pipeline?: string | null;
482
+ /** Query parameters to be used by transformers when compiling the resolved file. */ readonly query?: URLSearchParams | string | null;
483
+ /** Whether the resolved file should be excluded from the build. */ readonly isExcluded?: boolean | null;
484
+ /** Whether the dependency should be left out of the bundle, to be loaded at runtime. */ readonly isExternal?: boolean | null;
485
+ /** Corresponds to Asset's <code>sideEffects</code>. */ readonly sideEffects?: boolean | null;
486
+ /** The code of the resolved asset. If provided, this is used rather than reading the file from disk. */ readonly code?: string | null;
487
+ };
488
+ /**
489
+ * `config` is the configuration given for the plugin in .parcelrc, if any.
490
+ * @section resolver
491
+ */ export type Resolver<ConfigType> = {
492
+ /**
493
+ * Resolve a dependency, or return nullish to leave it to the next resolver plugin. Returning
494
+ * anything else that isn't an object throws.
495
+ */ resolve(args: {
496
+ dependency: Dependency;
497
+ specifier: DependencySpecifier;
498
+ pipeline: string | undefined;
499
+ config: ConfigType;
500
+ options: PluginOptions;
501
+ }): Async<ResolveResult | null | undefined>;
502
+ };
503
+ /**
504
+ * `config` is the configuration given for the plugin in .parcelrc, if any.
505
+ * @section namer
506
+ */ export type Namer<ConfigType> = {
507
+ /**
508
+ * Return a file path for <code>bundle</code>, relative to its target's <code>distDir</code>,
509
+ * or nullish or `""` to leave it to the next namer plugin. A path that leaves the
510
+ * <code>distDir</code>, e.g. an absolute one, fails the build.
511
+ */ name(args: {
512
+ bundle: Bundle;
513
+ bundleGraph: BundleGraph;
514
+ config: ConfigType;
515
+ options: PluginOptions;
516
+ }): Async<FilePath | null | undefined>;
517
+ };
518
+ /**
519
+ * @section optimizer
520
+ */ export type OptimizerResult = {
521
+ readonly contents: string | Uint8Array;
522
+ /** The source map for the optimized contents. */ readonly map?: SourceMapInput | null;
523
+ };
524
+ /**
525
+ * `config` is the configuration given for the plugin in .parcelrc, if any.
526
+ * @section optimizer
527
+ */ export type Optimizer<ConfigType> = {
528
+ optimize(args: {
529
+ bundle: Bundle;
530
+ bundleGraph: BundleGraph;
531
+ contents: Uint8Array;
532
+ /** The source map for the bundle. */ map: SourceMapJSON | null;
533
+ config: ConfigType;
534
+ options: PluginOptions;
535
+ }): Async<OptimizerResult>;
536
+ };
537
+ /**
538
+ * Passed to every reporter method alongside the event's own fields.
539
+ * @section reporter
540
+ */ export type ReporterContext<ConfigType> = {
541
+ readonly config: ConfigType;
542
+ readonly options: PluginOptions;
543
+ };
544
+ /**
545
+ * The build just started.
546
+ * @section reporter
547
+ */ export type BuildStartEvent<ConfigType> = ReporterContext<ConfigType>;
548
+ /**
549
+ * The build was successful.
550
+ * @section reporter
551
+ */ export type BuildSuccessEvent<ConfigType> = ReporterContext<ConfigType> & {
552
+ readonly bundleGraph: BundleGraph;
553
+ /** The duration of the build, in milliseconds. */ readonly buildTime: number;
554
+ /** The assets transformed by this build. On a full build, that is every asset. */ readonly changedAssets: Array<Asset>;
555
+ };
556
+ /**
557
+ * The build failed.
558
+ * @section reporter
559
+ */ export type BuildFailureEvent<ConfigType> = ReporterContext<ConfigType> & {
560
+ readonly diagnostics: Array<DiagnosticOptions>;
561
+ };
562
+ /**
563
+ * A message was logged, either as text or as diagnostics.
564
+ * @section reporter
565
+ */ export type LogEvent<ConfigType> = ReporterContext<ConfigType> & {
566
+ readonly level: Exclude<LogLevel, 'none'>;
567
+ } & ({
568
+ readonly message: string;
569
+ readonly diagnostics?: undefined;
570
+ } | {
571
+ readonly message?: undefined;
572
+ readonly diagnostics: Array<DiagnosticOptions>;
573
+ });
574
+ /**
575
+ * A reporter must implement at least one of these methods.
576
+ *
577
+ * `config` is the configuration given for the plugin in .parcelrc, if any.
578
+ * @section reporter
579
+ */ export type Reporter<ConfigType> = {
580
+ buildStart?: (event: BuildStartEvent<ConfigType>) => Async<void>;
581
+ buildSuccess?: (event: BuildSuccessEvent<ConfigType>) => Async<void>;
582
+ buildFailure?: (event: BuildFailureEvent<ConfigType>) => Async<void>;
583
+ log?: (event: LogEvent<ConfigType>) => Async<void>;
584
+ };
package/lib/types.js ADDED
@@ -0,0 +1,26 @@
1
+ // Plugin API types for Parcel v3. These describe the objects exposed to
2
+ // JavaScript plugins by the QuickJS bindings in crates/plugin-js.
3
+ //
4
+ // Plugins log by calling `console` methods. Passing a `Diagnostic` (exported by
5
+ // `@parcel/plugin`) logs its diagnostics, with a severity matching the method's
6
+ // level unless they set one. Throwing (or rejecting) fails the plugin call. A
7
+ // thrown `Diagnostic` is reported as the diagnostics it was created with. For
8
+ // any other error, the message becomes a diagnostic, with a code frame pointing
9
+ // at `filename`/`fileName`, `line` and `column` if the error has them, or
10
+ // otherwise at the top frame of its stack. Diagnostics are attributed to the
11
+ // plugin unless they set `origin`.
12
+ //
13
+ // A plugin's methods are called with the object passed to its constructor (e.g.
14
+ // `new Transformer({...})`) as `this`, so they can call helper methods on it.
15
+ //
16
+ // Each worker thread runs plugins in its own JavaScript runtime, and calls run
17
+ // concurrently across threads. Module-level state is therefore not shared between
18
+ // calls, not even between a reporter's `log` and `buildSuccess` calls. Timers and
19
+ // I/O callbacks aren't available, so a promise must be settled by other promises
20
+ // or synchronous code.
21
+ /**
22
+ * A reporter must implement at least one of these methods.
23
+ *
24
+ * `config` is the configuration given for the plugin in .parcelrc, if any.
25
+ * @section reporter
26
+ */ export { };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcel/plugin",
3
- "version": "2.16.3",
3
+ "version": "3.0.0-alpha.1",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -13,17 +13,14 @@
13
13
  "type": "git",
14
14
  "url": "https://github.com/parcel-bundler/parcel.git"
15
15
  },
16
+ "type": "module",
16
17
  "main": "lib/PluginAPI.js",
17
- "source": "src/PluginAPI.js",
18
- "types": "src/PluginAPI.d.ts",
18
+ "files": [
19
+ "lib"
20
+ ],
21
+ "source": "src/PluginAPI.ts",
22
+ "types": "lib/PluginAPI.d.ts",
19
23
  "engines": {
20
24
  "node": ">= 16.0.0"
21
- },
22
- "scripts": {
23
- "check-ts": "tsc --noEmit src/PluginAPI.d.ts"
24
- },
25
- "dependencies": {
26
- "@parcel/types": "2.16.3"
27
- },
28
- "gitHead": "73f691d67d22482440babb2d1846b7da2160f7cc"
29
- }
25
+ }
26
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2017-present Devon Govett
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1,52 +0,0 @@
1
- import type {
2
- Transformer as TransformerOpts,
3
- Resolver as ResolverOpts,
4
- Bundler as BundlerOpts,
5
- Namer as NamerOpts,
6
- Runtime as RuntimeOpts,
7
- Packager as PackagerOpts,
8
- Optimizer as OptimizerOpts,
9
- Compressor as CompressorOpts,
10
- Reporter as ReporterOpts,
11
- Validator as ValidatorOpts,
12
- } from '@parcel/types';
13
-
14
- export declare class Transformer<T> {
15
- constructor(opts: TransformerOpts<T>);
16
- }
17
-
18
- export declare class Resolver<T> {
19
- constructor(opts: ResolverOpts<T>);
20
- }
21
-
22
- export declare class Bundler<T> {
23
- constructor(opts: BundlerOpts<T>);
24
- }
25
-
26
- export declare class Namer<T> {
27
- constructor(opts: NamerOpts<T>);
28
- }
29
-
30
- export declare class Runtime<T> {
31
- constructor(opts: RuntimeOpts<T>);
32
- }
33
-
34
- export declare class Validator<T> {
35
- constructor(opts: ValidatorOpts);
36
- }
37
-
38
- export declare class Packager<C, B> {
39
- constructor(opts: PackagerOpts<C, B>);
40
- }
41
-
42
- export declare class Optimizer<C, B> {
43
- constructor(opts: OptimizerOpts<C, B>);
44
- }
45
-
46
- export declare class Compressor {
47
- constructor(opts: CompressorOpts);
48
- }
49
-
50
- export declare class Reporter {
51
- constructor(opts: ReporterOpts);
52
- }
package/src/PluginAPI.js DELETED
@@ -1,86 +0,0 @@
1
- // @flow strict-local
2
-
3
- import type {
4
- Transformer as TransformerOpts,
5
- Resolver as ResolverOpts,
6
- Bundler as BundlerOpts,
7
- Namer as NamerOpts,
8
- Runtime as RuntimeOpts,
9
- Packager as PackagerOpts,
10
- Optimizer as OptimizerOpts,
11
- Compressor as CompressorOpts,
12
- Reporter as ReporterOpts,
13
- Validator as ValidatorOpts,
14
- } from '@parcel/types';
15
-
16
- const CONFIG = Symbol.for('parcel-plugin-config');
17
-
18
- export class Transformer {
19
- constructor<T>(opts: TransformerOpts<T>) {
20
- // $FlowFixMe
21
- this[CONFIG] = opts;
22
- }
23
- }
24
-
25
- export class Resolver {
26
- constructor<T>(opts: ResolverOpts<T>) {
27
- // $FlowFixMe
28
- this[CONFIG] = opts;
29
- }
30
- }
31
-
32
- export class Bundler {
33
- constructor<T>(opts: BundlerOpts<T>) {
34
- // $FlowFixMe
35
- this[CONFIG] = opts;
36
- }
37
- }
38
-
39
- export class Namer {
40
- constructor<T>(opts: NamerOpts<T>) {
41
- // $FlowFixMe
42
- this[CONFIG] = opts;
43
- }
44
- }
45
-
46
- export class Runtime {
47
- constructor<T>(opts: RuntimeOpts<T>) {
48
- // $FlowFixMe
49
- this[CONFIG] = opts;
50
- }
51
- }
52
-
53
- export class Validator {
54
- constructor(opts: ValidatorOpts) {
55
- // $FlowFixMe
56
- this[CONFIG] = opts;
57
- }
58
- }
59
-
60
- export class Packager {
61
- constructor<T, U>(opts: PackagerOpts<T, U>) {
62
- // $FlowFixMe
63
- this[CONFIG] = opts;
64
- }
65
- }
66
-
67
- export class Optimizer {
68
- constructor<T, U>(opts: OptimizerOpts<T, U>) {
69
- // $FlowFixMe
70
- this[CONFIG] = opts;
71
- }
72
- }
73
-
74
- export class Compressor {
75
- constructor(opts: CompressorOpts) {
76
- // $FlowFixMe
77
- this[CONFIG] = opts;
78
- }
79
- }
80
-
81
- export class Reporter {
82
- constructor(opts: ReporterOpts) {
83
- // $FlowFixMe
84
- this[CONFIG] = opts;
85
- }
86
- }