@sanity/pkg-utils 10.5.8 → 10.7.0

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.
@@ -2,10 +2,10 @@ import path from "node:path";
2
2
  import { up } from "empathic/package";
3
3
  import { rimraf } from "rimraf";
4
4
  import { loadConfig } from "./defaults.js";
5
+ import { buildTaskHandlers, writeBundleCssExports, resolveVanillaExtract, resolveVanillaExtractCssName } from "./index.js";
5
6
  import { getTargetPaths, loadPkgWithReporting, resolveBuildContext } from "./resolveBuildContext.js";
6
7
  import { createLogger, handleError } from "./handleError.js";
7
8
  import { createSpinner } from "./spinner.js";
8
- import { buildTaskHandlers } from "./index.js";
9
9
  function resolveBuildTasks(ctx) {
10
10
  const { config, pkg, target } = ctx, bundles = config?.bundles || [], tasks = [], exports = Object.entries(ctx.exports || {}).map(
11
11
  ([_path, exp]) => Object.assign({}, exp, { _path })
@@ -164,6 +164,16 @@ async function build(options) {
164
164
  handler.error(ctx, task, err), process.exit(1);
165
165
  }
166
166
  }
167
+ const vanillaExtract = resolveVanillaExtract(config);
168
+ vanillaExtract.compatMode && await writeBundleCssExports({
169
+ cwd,
170
+ distPath: ctx.distPath,
171
+ cssName: resolveVanillaExtractCssName(vanillaExtract.options, {
172
+ compatMode: !0,
173
+ runtime: "*"
174
+ }),
175
+ logger
176
+ });
167
177
  }
168
178
  async function buildAction(options) {
169
179
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"buildAction.js","sources":["../../src/node/resolveBuildTasks.ts","../../src/node/build.ts","../../src/cli/buildAction.ts"],"sourcesContent":["import path from 'node:path'\nimport type {PkgExport, PkgFormat, PkgRuntime} from './core/config/types.ts'\nimport type {BuildContext} from './core/contexts/buildContext.ts'\nimport {getTargetPaths} from './tasks/dts/getTargetPaths.ts'\nimport type {DtsTask} from './tasks/dts/types.ts'\nimport type {BuildTask, RolldownDtsTask, RollupTask, RollupTaskEntry} from './tasks/types.ts'\n\n/** @internal */\nexport function resolveBuildTasks(ctx: BuildContext): BuildTask[] {\n const {config, pkg, target} = ctx\n\n const bundles = config?.bundles || []\n\n const tasks: BuildTask[] = []\n\n const exports = Object.entries(ctx.exports || {}).map(\n ([_path, exp]) => Object.assign({}, exp, {_path}) as PkgExport & {_path: string},\n )\n\n const dtsTask: DtsTask = {\n type: 'build:dts',\n entries: [],\n }\n\n const rolldownDtsTask: Record<string, RolldownDtsTask> = {}\n const rollupTasks: Record<string, RollupTask> = {}\n\n function addRollupTaskEntry(format: PkgFormat, runtime: PkgRuntime, entry: RollupTaskEntry) {\n const buildId = `${format}:${runtime}`\n\n if (ctx.dts === 'rolldown') {\n if (rolldownDtsTask[buildId]) {\n rolldownDtsTask[buildId].entries.push(entry)\n } else {\n rolldownDtsTask[buildId] = {\n type: 'rolldown:dts',\n buildId,\n entries: [entry],\n runtime,\n format,\n target: target[runtime],\n }\n }\n }\n\n if (!ctx.emitDeclarationOnly) {\n if (rollupTasks[buildId]) {\n rollupTasks[buildId].entries.push(entry)\n } else {\n rollupTasks[buildId] = {\n type: 'build:js',\n buildId,\n entries: [entry],\n runtime,\n format,\n target: target[runtime],\n }\n }\n }\n }\n\n if (ctx.dts === 'api-extractor') {\n // Parse `dts` tasks\n for (const exp of exports) {\n const importId = path.join(pkg.name, exp._path)\n\n if (exp.source?.endsWith('.ts')) {\n dtsTask.entries.push({\n importId,\n exportPath: exp._path,\n sourcePath: exp.source,\n targetPaths: getTargetPaths(pkg.type, exp),\n })\n }\n\n if (exp.browser?.source?.endsWith('.ts')) {\n dtsTask.entries.push({\n importId,\n exportPath: exp._path,\n sourcePath: exp.browser.source,\n targetPaths: getTargetPaths(pkg.type, exp.browser),\n })\n }\n\n if (exp.node?.source?.endsWith('.ts')) {\n dtsTask.entries.push({\n importId,\n exportPath: exp._path,\n sourcePath: exp.node.source,\n targetPaths: getTargetPaths(pkg.type, exp.node),\n })\n }\n }\n\n // Handle dts tasks for bundles\n for (const bundle of bundles) {\n if (bundle.source?.endsWith('.ts')) {\n // importId needs to be how the bundle is used, like `@sanity/pkg-utils/dist/cli`\n // exportPath needs to be the path to the bundle, like `./dist/cli`\n // targetPaths is then: [./dist/cli.d.ts, ./dist/cli.d.cts]\n const exportPath = (bundle.import || bundle.require)!.replace(/\\.[mc]?js$/, '')\n const importId = path.join(pkg.name, exportPath)\n\n dtsTask.entries.push({\n importId,\n exportPath,\n sourcePath: bundle.source,\n targetPaths: getTargetPaths(pkg.type, bundle),\n })\n }\n }\n\n // Add dts task\n if (dtsTask.entries.length) {\n tasks.push(dtsTask)\n }\n }\n\n // Parse rollup:commonjs:* tasks\n for (const exp of exports) {\n const output = exp.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', ctx.runtime, {\n path: exp._path,\n source: exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:* tasks\n for (const exp of exports) {\n const output = exp.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', ctx.runtime, {\n path: exp._path,\n source: exp.source,\n output,\n })\n }\n\n // Parse rollup:commonjs:browser tasks\n for (const exp of exports) {\n const output = exp.browser?.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', 'browser', {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:browser tasks\n for (const exp of exports) {\n const output = exp.browser?.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', 'browser', {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output,\n })\n }\n\n // Parse rollup:commonjs:node tasks\n for (const exp of exports) {\n const output = exp.node?.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', 'node', {\n path: exp._path,\n source: exp.node?.source || exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:node tasks\n for (const exp of exports) {\n const output = exp.node?.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', 'node', {\n path: exp._path,\n source: exp.node?.source || exp.source,\n output,\n })\n }\n\n for (const bundle of bundles) {\n const idx = bundles.indexOf(bundle)\n\n if (bundle.require) {\n addRollupTaskEntry('commonjs', bundle.runtime || ctx.runtime, {\n path: `__$$bundle_cjs_${idx}$$__`,\n source: bundle.source,\n output: bundle.require,\n })\n }\n\n if (bundle.import) {\n addRollupTaskEntry('esm', bundle.runtime || ctx.runtime, {\n path: `__$$bundle_esm_${idx}$$__`,\n source: bundle.source,\n output: bundle.import,\n })\n }\n }\n\n // Perform rolldown dts tasks first, as they have special logic for removing non .d.ts chunks\n tasks.push(...Object.values(rolldownDtsTask))\n // Then run api-extractor tsdoc release tag checking (if rolldown is used for dts bundling, otherwise api-extractor performs both in the build:dts task)\n // @TODO\n // Then run rollup tasks\n tasks.push(...Object.values(rollupTasks))\n\n return tasks\n}\n","import path from 'node:path'\nimport {up as findPkgPath} from 'empathic/package'\nimport {rimraf} from 'rimraf'\nimport {loadConfig} from './core/config/loadConfig.ts'\nimport {loadPkgWithReporting} from './core/pkg/loadPkgWithReporting.ts'\nimport {createLogger} from './logger.ts'\nimport {resolveBuildContext} from './resolveBuildContext.ts'\nimport {resolveBuildTasks} from './resolveBuildTasks.ts'\nimport {createSpinner} from './spinner.ts'\nimport {buildTaskHandlers} from './tasks/index.ts'\nimport {type BuildTask, type TaskHandler} from './tasks/types.ts'\n\n/**\n * Build the distribution files of a npm package.\n *\n * @example\n * ```ts\n * import {build} from '@sanity/pkg-utils'\n *\n * build({\n * cwd: process.cwd(),\n * tsconfig: 'tsconfig.dist.json,\n * }).then(() => {\n * console.log('successfully built')\n * }).catch((err) => {\n * console.log(`build error: ${err.message}`)\n * })\n * ```\n *\n * @public\n */\nexport async function build(options: {\n cwd: string\n emitDeclarationOnly?: boolean\n strict?: boolean\n tsconfig?: string\n clean?: boolean\n quiet?: boolean\n}): Promise<void> {\n const {\n cwd,\n emitDeclarationOnly,\n strict = false,\n tsconfig: tsconfigOption,\n clean = false,\n quiet = false,\n } = options\n const logger = createLogger(quiet)\n\n const pkgPath = findPkgPath({cwd})\n if (!pkgPath) {\n throw new Error('no package.json found', {cause: {cwd}})\n }\n const config = await loadConfig({cwd, pkgPath})\n\n const {parseStrictOptions} = await import('./strict.ts')\n const strictOptions = parseStrictOptions(config?.strictOptions ?? {})\n const pkg = await loadPkgWithReporting({pkgPath, logger, strict, strictOptions})\n\n const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'\n\n const ctx = await resolveBuildContext({\n config,\n cwd,\n emitDeclarationOnly,\n logger,\n pkg,\n strict,\n tsconfig,\n })\n\n if (clean) {\n if (!quiet) {\n logger.log(\n `Deleting the \\`dist\\` folder: './${path.relative(cwd, ctx.distPath)}' before building...`,\n )\n }\n await rimraf(ctx.distPath)\n }\n\n const buildTasks = resolveBuildTasks(ctx)\n\n for (const task of buildTasks) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- TypeScript can't infer the correct handler type from discriminated union\n const handler = buildTaskHandlers[task.type] as TaskHandler<BuildTask>\n const taskName = handler.name(ctx, task)\n\n const spinner = createSpinner(taskName, quiet)\n\n try {\n const result = await handler.exec(ctx, task).toPromise()\n\n spinner.complete()\n ctx.logger.log()\n\n handler.complete(ctx, task, result)\n } catch (err) {\n spinner.error()\n\n if (err instanceof Error) {\n const RE_CWD = new RegExp(cwd, 'g')\n\n ctx.logger.error(err.message.replace(RE_CWD, '.'))\n ctx.logger.log()\n }\n\n handler.error(ctx, task, err)\n\n process.exit(1)\n }\n }\n}\n","import {build} from '../node/build.ts'\nimport {handleError} from './handleError.ts'\n\nexport async function buildAction(options: {\n emitDeclarationOnly?: boolean\n strict?: boolean\n tsconfig?: string\n clean?: boolean\n quiet?: boolean\n}): Promise<void> {\n try {\n await build({\n cwd: process.cwd(),\n emitDeclarationOnly: options.emitDeclarationOnly,\n strict: options.strict,\n tsconfig: options.tsconfig,\n clean: options.clean,\n quiet: options.quiet,\n })\n } catch (err) {\n handleError(err)\n }\n}\n"],"names":["findPkgPath"],"mappings":";;;;;;;;AAQO,SAAS,kBAAkB,KAAgC;AAChE,QAAM,EAAC,QAAQ,KAAK,OAAA,IAAU,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A,cAAQ,MAAM,KAAK,MAAM,GAAG,GAE5B,QAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF;AC5GA,eAAsB,YAAY,SAMhB;AAChB,MAAI;AACF,UAAM,MAAM;AAAA,MACV,KAAK,QAAQ,IAAA;AAAA,MACb,qBAAqB,QAAQ;AAAA,MAC7B,QAAQ,QAAQ;AAAA,MAChB,UAAU,QAAQ;AAAA,MAClB,OAAO,QAAQ;AAAA,MACf,OAAO,QAAQ;AAAA,IAAA,CAChB;AAAA,EACH,SAAS,KAAK;AACZ,gBAAY,GAAG;AAAA,EACjB;AACF;"}
1
+ {"version":3,"file":"buildAction.js","sources":["../../src/node/resolveBuildTasks.ts","../../src/node/build.ts","../../src/cli/buildAction.ts"],"sourcesContent":["import path from 'node:path'\nimport type {PkgExport, PkgFormat, PkgRuntime} from './core/config/types.ts'\nimport type {BuildContext} from './core/contexts/buildContext.ts'\nimport {getTargetPaths} from './tasks/dts/getTargetPaths.ts'\nimport type {DtsTask} from './tasks/dts/types.ts'\nimport type {BuildTask, RolldownDtsTask, RollupTask, RollupTaskEntry} from './tasks/types.ts'\n\n/** @internal */\nexport function resolveBuildTasks(ctx: BuildContext): BuildTask[] {\n const {config, pkg, target} = ctx\n\n const bundles = config?.bundles || []\n\n const tasks: BuildTask[] = []\n\n const exports = Object.entries(ctx.exports || {}).map(\n ([_path, exp]) => Object.assign({}, exp, {_path}) as PkgExport & {_path: string},\n )\n\n const dtsTask: DtsTask = {\n type: 'build:dts',\n entries: [],\n }\n\n const rolldownDtsTask: Record<string, RolldownDtsTask> = {}\n const rollupTasks: Record<string, RollupTask> = {}\n\n function addRollupTaskEntry(format: PkgFormat, runtime: PkgRuntime, entry: RollupTaskEntry) {\n const buildId = `${format}:${runtime}`\n\n if (ctx.dts === 'rolldown') {\n if (rolldownDtsTask[buildId]) {\n rolldownDtsTask[buildId].entries.push(entry)\n } else {\n rolldownDtsTask[buildId] = {\n type: 'rolldown:dts',\n buildId,\n entries: [entry],\n runtime,\n format,\n target: target[runtime],\n }\n }\n }\n\n if (!ctx.emitDeclarationOnly) {\n if (rollupTasks[buildId]) {\n rollupTasks[buildId].entries.push(entry)\n } else {\n rollupTasks[buildId] = {\n type: 'build:js',\n buildId,\n entries: [entry],\n runtime,\n format,\n target: target[runtime],\n }\n }\n }\n }\n\n if (ctx.dts === 'api-extractor') {\n // Parse `dts` tasks\n for (const exp of exports) {\n const importId = path.join(pkg.name, exp._path)\n\n if (exp.source?.endsWith('.ts')) {\n dtsTask.entries.push({\n importId,\n exportPath: exp._path,\n sourcePath: exp.source,\n targetPaths: getTargetPaths(pkg.type, exp),\n })\n }\n\n if (exp.browser?.source?.endsWith('.ts')) {\n dtsTask.entries.push({\n importId,\n exportPath: exp._path,\n sourcePath: exp.browser.source,\n targetPaths: getTargetPaths(pkg.type, exp.browser),\n })\n }\n\n if (exp.node?.source?.endsWith('.ts')) {\n dtsTask.entries.push({\n importId,\n exportPath: exp._path,\n sourcePath: exp.node.source,\n targetPaths: getTargetPaths(pkg.type, exp.node),\n })\n }\n }\n\n // Handle dts tasks for bundles\n for (const bundle of bundles) {\n if (bundle.source?.endsWith('.ts')) {\n // importId needs to be how the bundle is used, like `@sanity/pkg-utils/dist/cli`\n // exportPath needs to be the path to the bundle, like `./dist/cli`\n // targetPaths is then: [./dist/cli.d.ts, ./dist/cli.d.cts]\n const exportPath = (bundle.import || bundle.require)!.replace(/\\.[mc]?js$/, '')\n const importId = path.join(pkg.name, exportPath)\n\n dtsTask.entries.push({\n importId,\n exportPath,\n sourcePath: bundle.source,\n targetPaths: getTargetPaths(pkg.type, bundle),\n })\n }\n }\n\n // Add dts task\n if (dtsTask.entries.length) {\n tasks.push(dtsTask)\n }\n }\n\n // Parse rollup:commonjs:* tasks\n for (const exp of exports) {\n const output = exp.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', ctx.runtime, {\n path: exp._path,\n source: exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:* tasks\n for (const exp of exports) {\n const output = exp.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', ctx.runtime, {\n path: exp._path,\n source: exp.source,\n output,\n })\n }\n\n // Parse rollup:commonjs:browser tasks\n for (const exp of exports) {\n const output = exp.browser?.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', 'browser', {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:browser tasks\n for (const exp of exports) {\n const output = exp.browser?.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', 'browser', {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output,\n })\n }\n\n // Parse rollup:commonjs:node tasks\n for (const exp of exports) {\n const output = exp.node?.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', 'node', {\n path: exp._path,\n source: exp.node?.source || exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:node tasks\n for (const exp of exports) {\n const output = exp.node?.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', 'node', {\n path: exp._path,\n source: exp.node?.source || exp.source,\n output,\n })\n }\n\n for (const bundle of bundles) {\n const idx = bundles.indexOf(bundle)\n\n if (bundle.require) {\n addRollupTaskEntry('commonjs', bundle.runtime || ctx.runtime, {\n path: `__$$bundle_cjs_${idx}$$__`,\n source: bundle.source,\n output: bundle.require,\n })\n }\n\n if (bundle.import) {\n addRollupTaskEntry('esm', bundle.runtime || ctx.runtime, {\n path: `__$$bundle_esm_${idx}$$__`,\n source: bundle.source,\n output: bundle.import,\n })\n }\n }\n\n // Perform rolldown dts tasks first, as they have special logic for removing non .d.ts chunks\n tasks.push(...Object.values(rolldownDtsTask))\n // Then run api-extractor tsdoc release tag checking (if rolldown is used for dts bundling, otherwise api-extractor performs both in the build:dts task)\n // @TODO\n // Then run rollup tasks\n tasks.push(...Object.values(rollupTasks))\n\n return tasks\n}\n","import path from 'node:path'\nimport {up as findPkgPath} from 'empathic/package'\nimport {rimraf} from 'rimraf'\nimport {loadConfig} from './core/config/loadConfig.ts'\nimport {resolveVanillaExtract, resolveVanillaExtractCssName} from './core/config/vanillaExtract.ts'\nimport {loadPkgWithReporting} from './core/pkg/loadPkgWithReporting.ts'\nimport {writeBundleCssExports} from './core/pkg/writeBundleCssExports.ts'\nimport {createLogger} from './logger.ts'\nimport {resolveBuildContext} from './resolveBuildContext.ts'\nimport {resolveBuildTasks} from './resolveBuildTasks.ts'\nimport {createSpinner} from './spinner.ts'\nimport {buildTaskHandlers} from './tasks/index.ts'\nimport {type BuildTask, type TaskHandler} from './tasks/types.ts'\n\n/**\n * Build the distribution files of a npm package.\n *\n * @example\n * ```ts\n * import {build} from '@sanity/pkg-utils'\n *\n * build({\n * cwd: process.cwd(),\n * tsconfig: 'tsconfig.dist.json,\n * }).then(() => {\n * console.log('successfully built')\n * }).catch((err) => {\n * console.log(`build error: ${err.message}`)\n * })\n * ```\n *\n * @public\n */\nexport async function build(options: {\n cwd: string\n emitDeclarationOnly?: boolean\n strict?: boolean\n tsconfig?: string\n clean?: boolean\n quiet?: boolean\n}): Promise<void> {\n const {\n cwd,\n emitDeclarationOnly,\n strict = false,\n tsconfig: tsconfigOption,\n clean = false,\n quiet = false,\n } = options\n const logger = createLogger(quiet)\n\n const pkgPath = findPkgPath({cwd})\n if (!pkgPath) {\n throw new Error('no package.json found', {cause: {cwd}})\n }\n const config = await loadConfig({cwd, pkgPath})\n\n const {parseStrictOptions} = await import('./strict.ts')\n const strictOptions = parseStrictOptions(config?.strictOptions ?? {})\n const pkg = await loadPkgWithReporting({pkgPath, logger, strict, strictOptions})\n\n const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'\n\n const ctx = await resolveBuildContext({\n config,\n cwd,\n emitDeclarationOnly,\n logger,\n pkg,\n strict,\n tsconfig,\n })\n\n if (clean) {\n if (!quiet) {\n logger.log(\n `Deleting the \\`dist\\` folder: './${path.relative(cwd, ctx.distPath)}' before building...`,\n )\n }\n await rimraf(ctx.distPath)\n }\n\n const buildTasks = resolveBuildTasks(ctx)\n\n for (const task of buildTasks) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- TypeScript can't infer the correct handler type from discriminated union\n const handler = buildTaskHandlers[task.type] as TaskHandler<BuildTask>\n const taskName = handler.name(ctx, task)\n\n const spinner = createSpinner(taskName, quiet)\n\n try {\n const result = await handler.exec(ctx, task).toPromise()\n\n spinner.complete()\n ctx.logger.log()\n\n handler.complete(ctx, task, result)\n } catch (err) {\n spinner.error()\n\n if (err instanceof Error) {\n const RE_CWD = new RegExp(cwd, 'g')\n\n ctx.logger.error(err.message.replace(RE_CWD, '.'))\n ctx.logger.log()\n }\n\n handler.error(ctx, task, err)\n\n process.exit(1)\n }\n }\n\n // In vanilla-extract compat mode, make sure package.json declares the conditional `./<css>`\n // export that the injected `import \"<pkg>/<css>\"` resolves through.\n const vanillaExtract = resolveVanillaExtract(config)\n if (vanillaExtract.compatMode) {\n await writeBundleCssExports({\n cwd,\n distPath: ctx.distPath,\n cssName: resolveVanillaExtractCssName(vanillaExtract.options, {\n compatMode: true,\n runtime: '*',\n }),\n logger,\n })\n }\n}\n","import {build} from '../node/build.ts'\nimport {handleError} from './handleError.ts'\n\nexport async function buildAction(options: {\n emitDeclarationOnly?: boolean\n strict?: boolean\n tsconfig?: string\n clean?: boolean\n quiet?: boolean\n}): Promise<void> {\n try {\n await build({\n cwd: process.cwd(),\n emitDeclarationOnly: options.emitDeclarationOnly,\n strict: options.strict,\n tsconfig: options.tsconfig,\n clean: options.clean,\n quiet: options.quiet,\n })\n } catch (err) {\n handleError(err)\n }\n}\n"],"names":["findPkgPath"],"mappings":";;;;;;;;AAQO,SAAS,kBAAkB,KAAgC;AAChE,QAAM,EAAC,QAAQ,KAAK,OAAA,IAAU,KAExB,UAAU,QAAQ,WAAW,CAAA,GAE7B,QAAqB,CAAA,GAErB,UAAU,OAAO,QAAQ,IAAI,WAAW,CAAA,CAAE,EAAE;AAAA,IAChD,CAAC,CAAC,OAAO,GAAG,MAAM,OAAO,OAAO,CAA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;AAAA,IACA,UAAU,IAAI;AAAA,IACd,SAAS,6BAA6B,eAAe,SAAS;AAAA,MAC5D,YAAY;AAAA,MACZ,SAAS;AAAA,IAAA,CACV;AAAA,IACD;AAAA,EAAA,CACD;AAEL;AC7HA,eAAsB,YAAY,SAMhB;AAChB,MAAI;AACF,UAAM,MAAM;AAAA,MACV,KAAK,QAAQ,IAAA;AAAA,MACb,qBAAqB,QAAQ;AAAA,MAC7B,QAAQ,QAAQ;AAAA,MAChB,UAAU,QAAQ;AAAA,MAClB,OAAO,QAAQ;AAAA,MACf,OAAO,QAAQ;AAAA,IAAA,CAChB;AAAA,EACH,SAAS,KAAK;AACZ,gBAAY,GAAG;AAAA,EACjB;AACF;"}
@@ -1,12 +1,12 @@
1
+ import fs, { readFile, writeFile } from "node:fs/promises";
2
+ import path, { basename } from "node:path";
1
3
  import chalk from "chalk";
2
4
  import { from, Observable } from "rxjs";
3
5
  import { printExtractMessages } from "./printExtractMessages.js";
4
- import path, { basename } from "node:path";
5
6
  import { ExtractorConfig, Extractor, ExtractorLogLevel } from "@microsoft/api-extractor";
6
7
  import * as rimraf from "rimraf";
7
8
  import { rimraf as rimraf$1 } from "rimraf";
8
9
  import ts from "typescript";
9
- import fs from "node:fs/promises";
10
10
  import { mkdirp } from "mkdirp";
11
11
  import * as prettier from "prettier";
12
12
  import { createApiExtractorConfig } from "./createApiExtractorConfig.js";
@@ -27,6 +27,41 @@ import esbuild from "rollup-plugin-esbuild";
27
27
  import { DEFAULT_BROWSERSLIST_QUERY } from "./defaults.js";
28
28
  import browserslist from "browserslist";
29
29
  import { browserslistToTargets, transform } from "lightningcss";
30
+ const DEFAULT_VANILLA_EXTRACT_CSS_NAME = "bundle.css";
31
+ function resolveVanillaExtract(config) {
32
+ const value = config?.rollup?.vanillaExtract, enabled = !!value, options = value === !0 || !value ? {} : value, compatMode = enabled ? options.extract?.compatMode ?? !0 : !1;
33
+ return { enabled, options, compatMode };
34
+ }
35
+ function resolveVanillaExtractCssName(options, context) {
36
+ return options.extract?.name ? options.extract.name : context.compatMode ? DEFAULT_VANILLA_EXTRACT_CSS_NAME : context.runtime === "node" ? "bundle.node.css" : context.runtime === "browser" ? "bundle.browser.css" : DEFAULT_VANILLA_EXTRACT_CSS_NAME;
37
+ }
38
+ function createConditionalCssExport(cssFile, shimFile) {
39
+ return { browser: cssFile, style: cssFile, node: shimFile, default: shimFile };
40
+ }
41
+ function hasMatchingExport(value, expected) {
42
+ if (typeof value != "object" || value === null) return !1;
43
+ const actual = Object.fromEntries(Object.entries(value)), keys = Object.keys(expected);
44
+ return keys.length === Object.keys(actual).length && keys.every((key) => actual[key] === expected[key]);
45
+ }
46
+ function detectIndent(source) {
47
+ const match = source.match(/\n([ \t]+)\S/);
48
+ if (!match) return 2;
49
+ const indent = match[1];
50
+ return indent.includes(" ") ? " " : indent.length;
51
+ }
52
+ async function writeBundleCssExports(options) {
53
+ const { cwd, distPath, cssName, logger } = options, pkgPath = path.resolve(cwd, "package.json"), source = await readFile(pkgPath, "utf8"), pkg = JSON.parse(source), distRel = (path.relative(cwd, distPath) || "dist").split(path.sep).join("/"), exportKey = `./${cssName}`, cssFile = `./${path.posix.join(distRel, cssName)}`, shimFile = `./${path.posix.join(distRel, `${cssName}.js`)}`, conditionalExport = createConditionalCssExport(cssFile, shimFile);
54
+ if (hasMatchingExport(pkg.exports?.[exportKey], conditionalExport))
55
+ return;
56
+ const nextExports = {};
57
+ let inserted = !1;
58
+ for (const [key, value] of Object.entries(pkg.exports ?? {}))
59
+ key !== exportKey && (key === "./package.json" && !inserted && (nextExports[exportKey] = conditionalExport, inserted = !0), nextExports[key] = value);
60
+ inserted || (nextExports[exportKey] = conditionalExport), pkg.exports = nextExports, await writeFile(pkgPath, `${JSON.stringify(pkg, null, detectIndent(source))}
61
+ `), logger.log(
62
+ `Updated package.json: added \`exports["${exportKey}"]\` for vanilla-extract compat mode`
63
+ );
64
+ }
30
65
  function printDiagnostic(options) {
31
66
  const { cwd, logger, diagnostic } = options;
32
67
  if (diagnostic.file && diagnostic.start) {
@@ -379,6 +414,21 @@ function replaceFileEnding(filePath) {
379
414
  return filePath.replace(/\.js$/, ".d.ts");
380
415
  }
381
416
  }
417
+ function bundleCssShim(options) {
418
+ const cssName = options.fileName.replace(/\.js$/, "");
419
+ return {
420
+ name: "pkg-utils:bundle-css-shim",
421
+ generateBundle() {
422
+ this.emitFile({
423
+ type: "asset",
424
+ fileName: options.fileName,
425
+ source: `// No-op shim for \`${cssName}\` in runtimes that cannot import \`.css\` files directly.
426
+ export default ""
427
+ `
428
+ });
429
+ }
430
+ };
431
+ }
382
432
  function optimizeCss(options) {
383
433
  return {
384
434
  name: "optimize-css",
@@ -391,18 +441,19 @@ function optimizeCss(options) {
391
441
  await transformCss(
392
442
  asset,
393
443
  bundle[sourceMapFileName]?.type === "asset" ? bundle[sourceMapFileName] : void 0,
394
- options.browserslist
444
+ options.browserslist,
445
+ options.minify ?? !0
395
446
  );
396
447
  }
397
448
  }
398
449
  }
399
450
  };
400
451
  }
401
- async function transformCss(asset, sourceMapAsset, browserslistConfig) {
452
+ async function transformCss(asset, sourceMapAsset, browserslistConfig, minify) {
402
453
  const css = asset.source.toString(), file = asset.fileName, targets = browserslistToTargets(browserslist(browserslistConfig)), lightningCssResult = transform({
403
454
  filename: file,
404
455
  code: Buffer.from(css),
405
- minify: !0,
456
+ minify,
406
457
  cssModules: !1,
407
458
  targets,
408
459
  sourceMap: !!sourceMapAsset,
@@ -438,7 +489,10 @@ function resolveRollupConfig(ctx, buildTask) {
438
489
  name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, "")
439
490
  }), {}), exportIds = _exports && Object.keys(_exports).map((exportPath) => path.join(pkg.name, exportPath)), sourcePaths = _exports && Object.values(_exports).map((e) => path.resolve(cwd, e.source)), replacements = Object.fromEntries(
440
491
  Object.entries(config?.define || {}).map(([key, val]) => [key, JSON.stringify(val)])
441
- ), { optimizeLodash: enableOptimizeLodash = hasDependency(pkg, "lodash") } = config?.rollup || {}, enableStyledComponents = shouldEnableStyledComponents(config, pkg, logger), defaultPlugins = [
492
+ ), { optimizeLodash: enableOptimizeLodash = hasDependency(pkg, "lodash") } = config?.rollup || {}, enableStyledComponents = shouldEnableStyledComponents(config, pkg, logger), vanillaExtract = resolveVanillaExtract(config), vanillaExtractCssName = resolveVanillaExtractCssName(vanillaExtract.options, {
493
+ compatMode: vanillaExtract.compatMode,
494
+ runtime
495
+ }), defaultPlugins = [
442
496
  replace({
443
497
  preventAssignment: !0,
444
498
  values: pkg.name === "@sanity/pkg-utils" ? { ...replacements } : {
@@ -464,27 +518,30 @@ function resolveRollupConfig(ctx, buildTask) {
464
518
  }),
465
519
  commonjs(),
466
520
  json(),
467
- config?.rollup?.vanillaExtract && vanillaExtractPlugin(
468
- config?.rollup?.vanillaExtract === !0 ? {
469
- extract: {
470
- name: runtime === "node" ? "bundle.node.css" : runtime === "browser" ? "bundle.browser.css" : "bundle.css",
471
- sourcemap: !0
472
- },
473
- identifiers: "short"
474
- } : config?.rollup?.vanillaExtract
475
- ),
476
- config?.rollup?.vanillaExtract && optimizeCss(
477
- config?.rollup?.vanillaExtract === !0 ? {
478
- extractFileName: runtime === "node" ? "bundle.node.css" : runtime === "browser" ? "bundle.browser.css" : "bundle.css",
479
- browserslist: DEFAULT_BROWSERSLIST_QUERY
480
- } : {
481
- extractFileName: typeof config.rollup.vanillaExtract.extract == "object" && config.rollup.vanillaExtract.extract.name ? config.rollup.vanillaExtract.extract.name : runtime === "node" ? "bundle.node.css" : runtime === "browser" ? "bundle.browser.css" : "bundle.css",
482
- browserslist: config.rollup.vanillaExtract.browserslist || DEFAULT_BROWSERSLIST_QUERY
521
+ vanillaExtract.enabled && vanillaExtractPlugin({
522
+ identifiers: vanillaExtract.options.identifiers ?? "short",
523
+ cwd: vanillaExtract.options.cwd,
524
+ esbuildOptions: vanillaExtract.options.esbuildOptions,
525
+ unstable_injectFilescopes: vanillaExtract.options.unstable_injectFilescopes,
526
+ extract: {
527
+ name: vanillaExtractCssName,
528
+ sourcemap: vanillaExtract.options.extract?.sourcemap ?? !0
483
529
  }
484
- ),
530
+ }),
531
+ vanillaExtract.enabled && optimizeCss({
532
+ extractFileName: vanillaExtractCssName,
533
+ browserslist: vanillaExtract.options.browserslist || DEFAULT_BROWSERSLIST_QUERY,
534
+ minify: vanillaExtract.options.minify ?? !0
535
+ }),
536
+ // In compat mode, emit the no-op JS shim that the `node`/`default` conditions of the
537
+ // `./<css>` export resolve to.
538
+ vanillaExtract.compatMode && bundleCssShim({ fileName: `${vanillaExtractCssName}.js` }),
485
539
  (config?.babel?.reactCompiler || enableStyledComponents) && babel({
486
540
  babelrc: !1,
487
541
  presets: ["@babel/preset-typescript"],
542
+ parserOpts: {
543
+ plugins: ["jsx"]
544
+ },
488
545
  babelHelpers: "bundled",
489
546
  parallel: !0,
490
547
  extensions: [".ts", ".tsx", ".js", ".jsx"],
@@ -596,10 +653,26 @@ function resolveRollupConfig(ctx, buildTask) {
596
653
  hoistTransitiveImports: !1,
597
654
  minifyInternalExports: minify,
598
655
  assetFileNames: "[name][extname]",
599
- ...config?.rollup?.output
656
+ ...config?.rollup?.output,
657
+ // In compat mode, inject the self-referential bundle.css import into entry chunks so userland
658
+ // does not need to set `rollup.output.intro` themselves. Use `require()` for CommonJS output
659
+ // (a top-level `import` would be invalid in a `.cjs` bundle).
660
+ ...vanillaExtract.compatMode ? {
661
+ intro: composeIntro(
662
+ format === "commonjs" ? `require(${JSON.stringify(`${pkg.name}/${vanillaExtractCssName}`)})` : `import ${JSON.stringify(`${pkg.name}/${vanillaExtractCssName}`)}`,
663
+ config?.rollup?.output?.intro
664
+ )
665
+ } : {}
600
666
  }
601
667
  };
602
668
  }
669
+ function composeIntro(autoImport, userIntro) {
670
+ return async (chunkInfo) => {
671
+ const auto = chunkInfo.isEntry ? `${autoImport}
672
+ ` : "", user = typeof userIntro == "function" ? await userIntro(chunkInfo) : typeof userIntro == "string" ? userIntro : "";
673
+ return `${auto}${user}`;
674
+ };
675
+ }
603
676
  function hasDependency(pkg, packageName) {
604
677
  return pkg.dependencies ? packageName in pkg.dependencies : pkg.peerDependencies ? packageName in pkg.peerDependencies : !1;
605
678
  }
@@ -719,6 +792,9 @@ const rollupWatchTask = {
719
792
  };
720
793
  export {
721
794
  buildTaskHandlers,
722
- watchTaskHandlers
795
+ resolveVanillaExtract,
796
+ resolveVanillaExtractCssName,
797
+ watchTaskHandlers,
798
+ writeBundleCssExports
723
799
  };
724
800
  //# sourceMappingURL=index.js.map