@pikacss/integration 0.0.32 → 0.0.34

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.
package/dist/index.cjs CHANGED
@@ -28,20 +28,19 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  let node_fs = require("node:fs");
29
29
  let node_fs_promises = require("node:fs/promises");
30
30
  let __pikacss_core = require("@pikacss/core");
31
- let jiti = require("jiti");
31
+ let alien_signals = require("alien-signals");
32
+ let globby = require("globby");
32
33
  let klona = require("klona");
33
34
  let local_pkg = require("local-pkg");
34
35
  let magic_string = require("magic-string");
35
36
  magic_string = __toESM(magic_string);
36
- let micromatch = require("micromatch");
37
- micromatch = __toESM(micromatch);
38
37
  let pathe = require("pathe");
39
- let perfect_debounce = require("perfect-debounce");
40
38
 
41
39
  //#region src/eventHook.ts
42
40
  function createEventHook() {
43
41
  const listeners = /* @__PURE__ */ new Set();
44
42
  function trigger(payload) {
43
+ if (listeners.size === 0) return;
45
44
  listeners.forEach((listener) => listener(payload));
46
45
  }
47
46
  function off(listener) {
@@ -130,9 +129,11 @@ function generateVueDeclaration(ctx) {
130
129
  ];
131
130
  }
132
131
  async function generateOverloadContent(ctx) {
132
+ __pikacss_core.log.debug("Generating TypeScript overload content");
133
133
  const paramsLines = [];
134
134
  const fnsLines = [];
135
135
  const usages = [...ctx.usages.values()].flat();
136
+ __pikacss_core.log.debug(`Processing ${usages.length} style usages for overload generation`);
136
137
  for (let i = 0; i < usages.length; i++) {
137
138
  const usage = usages[i];
138
139
  try {
@@ -166,6 +167,7 @@ async function generateOverloadContent(ctx) {
166
167
  ];
167
168
  }
168
169
  async function generateTsCodegenContent(ctx) {
170
+ __pikacss_core.log.debug("Generating TypeScript code generation content");
169
171
  const lines = [
170
172
  `// Auto-generated by ${ctx.currentPackageName}`,
171
173
  `import type { CSSProperty, CSSSelectors, DefineAutocomplete, Properties, StyleDefinition, StyleItem } from \'${ctx.currentPackageName}\'`,
@@ -187,257 +189,370 @@ async function generateTsCodegenContent(ctx) {
187
189
  lines.push(...generateGlobalDeclaration(ctx));
188
190
  lines.push(...generateVueDeclaration(ctx));
189
191
  lines.push(...await generateOverloadContent(ctx));
192
+ __pikacss_core.log.debug("TypeScript code generation content completed");
190
193
  return lines.join("\n");
191
194
  }
192
195
 
193
196
  //#endregion
194
197
  //#region src/ctx.ts
195
- function findFunctionCalls(code, RE) {
196
- const result = [];
197
- let matched = RE.exec(code);
198
- while (matched != null) {
199
- const fnName = matched[1];
200
- const start = matched.index;
201
- let end = start + fnName.length;
202
- let depth = 1;
203
- let inString = false;
204
- while (depth > 0) {
205
- end++;
206
- if (inString === false && code[end] === "(") depth++;
207
- else if (inString === false && code[end] === ")") depth--;
208
- else if (inString === false && (code[end] === "'" || code[end] === "\"")) inString = code[end];
209
- else if (inString === code[end]) inString = false;
210
- }
211
- const snippet = code.slice(start, end + 1);
212
- result.push({
213
- fnName,
214
- start,
215
- end,
216
- snippet
217
- });
218
- matched = RE.exec(code);
219
- }
220
- return result;
221
- }
222
- const ESCAPE_REPLACE_RE = /[.*+?^${}()|[\]\\/]/g;
223
- function createFnUtils(fnName) {
224
- const available = {
225
- normal: new Set([fnName]),
226
- forceString: new Set([
227
- `${fnName}.str`,
228
- `${fnName}['str']`,
229
- `${fnName}["str"]`,
230
- `${fnName}[\`str\`]`
231
- ]),
232
- forceArray: new Set([
233
- `${fnName}.arr`,
234
- `${fnName}['arr']`,
235
- `${fnName}["arr"]`,
236
- `${fnName}[\`arr\`]`
237
- ]),
238
- forceInline: new Set([
239
- `${fnName}.inl`,
240
- `${fnName}['inl']`,
241
- `${fnName}["inl"]`,
242
- `${fnName}[\`inl\`]`
243
- ]),
244
- normalPreview: new Set([`${fnName}p`]),
245
- forceStringPreview: new Set([
246
- `${fnName}p.str`,
247
- `${fnName}p['str']`,
248
- `${fnName}p["str"]`,
249
- `${fnName}p[\`str\`]`
250
- ]),
251
- forceArrayPreview: new Set([
252
- `${fnName}p.arr`,
253
- `${fnName}p['arr']`,
254
- `${fnName}p["arr"]`,
255
- `${fnName}p[\`arr\`]`
256
- ]),
257
- forceInlinePreview: new Set([
258
- `${fnName}p.inl`,
259
- `${fnName}p['inl']`,
260
- `${fnName}p["inl"]`,
261
- `${fnName}p[\`inl\`]`
262
- ])
263
- };
198
+ function usePaths({ cwd: _cwd, cssCodegen, tsCodegen }) {
199
+ const cwd = (0, alien_signals.signal)(_cwd);
264
200
  return {
265
- isNormal: (fnName$1) => available.normal.has(fnName$1) || available.normalPreview.has(fnName$1),
266
- isForceString: (fnName$1) => available.forceString.has(fnName$1) || available.forceStringPreview.has(fnName$1),
267
- isForceArray: (fnName$1) => available.forceArray.has(fnName$1) || available.forceArrayPreview.has(fnName$1),
268
- isForceInline: (fnName$1) => available.forceInline.has(fnName$1) || available.forceInlinePreview.has(fnName$1),
269
- isPreview: (fnName$1) => available.normalPreview.has(fnName$1) || available.forceStringPreview.has(fnName$1) || available.forceArrayPreview.has(fnName$1) || available.forceInlinePreview.has(fnName$1),
270
- RE: new RegExp(`\\b(${Object.values(available).flatMap((s) => [...s].map((f) => `(${f.replace(ESCAPE_REPLACE_RE, "\\$&")})`)).join("|")})\\(`, "g")
201
+ cwd,
202
+ cssCodegenFilepath: (0, alien_signals.computed)(() => (0, pathe.isAbsolute)(cssCodegen) ? (0, pathe.resolve)(cssCodegen) : (0, pathe.join)(cwd(), cssCodegen)),
203
+ tsCodegenFilepath: (0, alien_signals.computed)(() => tsCodegen === false ? null : (0, pathe.isAbsolute)(tsCodegen) ? (0, pathe.resolve)(tsCodegen) : (0, pathe.join)(cwd(), tsCodegen))
271
204
  };
272
205
  }
273
- async function createCtx(options) {
274
- const { cwd, currentPackageName, target, configOrPath, fnName, transformedFormat, tsCodegen, devCss, autoCreateConfig } = options;
275
- (0, __pikacss_core.setWarnFn)((...args) => {
276
- console.warn(`[${currentPackageName}]`, ...args);
206
+ function useConfig({ cwd, tsCodegenFilepath, currentPackageName, autoCreateConfig, configOrPath, scan }) {
207
+ const RE_VALID_CONFIG_EXT = /\.(?:js|cjs|mjs|ts|cts|mts)$/;
208
+ const specificConfigPath = (0, alien_signals.computed)(() => {
209
+ if (typeof configOrPath === "string" && RE_VALID_CONFIG_EXT.test(configOrPath)) return (0, pathe.isAbsolute)(configOrPath) ? configOrPath : (0, pathe.join)(cwd(), configOrPath);
210
+ return null;
277
211
  });
278
- const devCssFilepath = (0, pathe.isAbsolute)(devCss) ? (0, pathe.resolve)(devCss) : (0, pathe.join)(cwd, devCss);
279
- const tsCodegenFilepath = tsCodegen === false ? null : (0, pathe.isAbsolute)(tsCodegen) ? (0, pathe.resolve)(tsCodegen) : (0, pathe.join)(cwd, tsCodegen);
212
+ async function findFirstExistingConfigPath() {
213
+ const _cwd = cwd();
214
+ const _specificConfigPath = specificConfigPath();
215
+ if (_specificConfigPath != null && (0, node_fs.statSync)(_specificConfigPath, { throwIfNoEntry: false })?.isFile()) return _specificConfigPath;
216
+ const stream = (0, globby.globbyStream)("**/{pika,pikacss}.config.{js,cjs,mjs,ts,cts,mts}", { ignore: scan.exclude });
217
+ for await (const entry of stream) return (0, pathe.join)(_cwd, entry);
218
+ return null;
219
+ }
280
220
  const inlineConfig = typeof configOrPath === "object" ? configOrPath : null;
281
- const specificConfigPath = typeof configOrPath === "string" ? (0, pathe.isAbsolute)(configOrPath) ? configOrPath : (0, pathe.join)(cwd, configOrPath) : null;
282
- const configSources = [...specificConfigPath == null ? [] : [specificConfigPath], ...["pika", "pikacss"].flatMap((name) => [
283
- "js",
284
- "ts",
285
- "cjs",
286
- "cts",
287
- "mjs",
288
- "mts"
289
- ].map((ext) => `${name}.config.${ext}`)).map((name) => (0, pathe.join)(cwd, name))];
290
- const targetREs = target.map((t) => micromatch.default.makeRe(t));
291
- const needToTransform = (id) => targetREs.some((re) => re.test(id));
292
- const ctx = {
293
- cwd,
294
- currentPackageName,
295
- fnName,
296
- fnUtils: createFnUtils(fnName),
297
- transformedFormat,
298
- devCssFilepath,
299
- tsCodegenFilepath,
300
- hasVue: (0, local_pkg.isPackageExists)("vue", { paths: [cwd] }),
301
- usages: /* @__PURE__ */ new Map(),
302
- hooks: {
303
- styleUpdated: createEventHook(),
304
- tsCodegenUpdated: createEventHook()
305
- },
306
- loadConfig: async () => {
307
- if (inlineConfig != null) return {
308
- config: (0, klona.klona)(inlineConfig),
309
- file: null
310
- };
311
- let resolvedConfigPath = configSources.find((path) => {
312
- const stat = (0, node_fs.statSync)(path, { throwIfNoEntry: false });
313
- return stat != null && stat.isFile();
314
- });
315
- if (resolvedConfigPath == null) {
316
- if (autoCreateConfig === false) return {
317
- config: null,
221
+ async function _loadConfig() {
222
+ try {
223
+ __pikacss_core.log.debug("Loading engine config");
224
+ if (inlineConfig != null) {
225
+ __pikacss_core.log.debug("Using inline config");
226
+ return {
227
+ config: (0, klona.klona)(inlineConfig),
318
228
  file: null
319
229
  };
320
- resolvedConfigPath = configSources[0];
321
- await (0, node_fs_promises.mkdir)((0, pathe.dirname)(resolvedConfigPath), { recursive: true }).catch(() => {});
322
- const relativeTsCodegenFilepath = tsCodegenFilepath == null ? null : `./${(0, pathe.relative)((0, pathe.dirname)(resolvedConfigPath), tsCodegenFilepath)}`;
323
- await (0, node_fs_promises.writeFile)(resolvedConfigPath, [
230
+ }
231
+ let resolvedConfigPath$1 = await findFirstExistingConfigPath();
232
+ const _cwd = cwd();
233
+ if (resolvedConfigPath$1 == null) {
234
+ if (autoCreateConfig === false) {
235
+ __pikacss_core.log.warn("Config file not found and autoCreateConfig is false");
236
+ return {
237
+ config: null,
238
+ file: null
239
+ };
240
+ }
241
+ resolvedConfigPath$1 = (0, pathe.join)(_cwd, specificConfigPath() ?? "pika.config.js");
242
+ await (0, node_fs_promises.mkdir)((0, pathe.dirname)(resolvedConfigPath$1), { recursive: true }).catch(() => {});
243
+ const _tsCodegenFilepath = tsCodegenFilepath();
244
+ const relativeTsCodegenFilepath = _tsCodegenFilepath == null ? null : `./${(0, pathe.relative)((0, pathe.dirname)(resolvedConfigPath$1), _tsCodegenFilepath)}`;
245
+ await (0, node_fs_promises.writeFile)(resolvedConfigPath$1, [
246
+ ...relativeTsCodegenFilepath == null ? [] : [`/// <reference path="${relativeTsCodegenFilepath}" />`],
324
247
  `import { defineEngineConfig } from '${currentPackageName}'`,
325
- ...relativeTsCodegenFilepath == null ? [] : [`/** @type {import('${relativeTsCodegenFilepath}')} */`],
326
248
  "",
327
249
  "export default defineEngineConfig({",
328
250
  " // Add your PikaCSS engine config here",
329
251
  "})"
330
252
  ].join("\n"));
331
253
  }
332
- const config = (await (0, jiti.createJiti)(cwd, {
333
- fsCache: false,
334
- moduleCache: false
335
- }).import(resolvedConfigPath)).default;
254
+ __pikacss_core.log.info(`Using config file: ${resolvedConfigPath$1}`);
255
+ const { createJiti } = await import("jiti");
256
+ const jiti = createJiti(require("url").pathToFileURL(__filename).href, { interopDefault: true });
257
+ const content = await (0, node_fs_promises.readFile)(resolvedConfigPath$1, "utf-8");
258
+ const config = (await jiti.evalModule(content, {
259
+ id: resolvedConfigPath$1,
260
+ forceTranspile: true
261
+ })).default;
336
262
  return {
337
263
  config: (0, klona.klona)(config),
338
- file: resolvedConfigPath
264
+ file: resolvedConfigPath$1
339
265
  };
340
- },
341
- init: (0, perfect_debounce.debounce)(async () => {
342
- ctx.isReady = false;
343
- ctx.usages.clear();
344
- const { config, file } = await ctx.loadConfig().catch((error) => {
345
- (0, __pikacss_core.warn)(`Failed to load config file: ${error.message}`, error);
346
- return {
347
- config: null,
348
- file: null
349
- };
350
- });
351
- ctx.resolvedConfigPath = file;
352
- const devPlugin = (0, __pikacss_core.defineEnginePlugin)({
353
- name: "@pikacss/integration:dev",
354
- preflightUpdated: () => ctx.hooks.styleUpdated.trigger(),
355
- atomicStyleAdded: () => ctx.hooks.styleUpdated.trigger(),
356
- autocompleteConfigUpdated: () => ctx.hooks.tsCodegenUpdated.trigger()
357
- });
358
- try {
359
- const _config = config ?? {};
360
- _config.plugins = _config.plugins ?? [];
361
- _config.plugins.unshift(devPlugin);
362
- ctx.engine = await (0, __pikacss_core.createEngine)(_config);
363
- } catch (error) {
364
- (0, __pikacss_core.warn)(`Failed to create engine: ${error.message}. Maybe the config file is invalid, falling back to default config.`, error);
365
- ctx.engine = await (0, __pikacss_core.createEngine)({ plugins: [devPlugin] });
366
- }
367
- await (0, node_fs_promises.mkdir)((0, pathe.dirname)(devCssFilepath), { recursive: true }).catch(() => {});
368
- await (0, node_fs_promises.writeFile)(devCssFilepath, "");
369
- if (tsCodegenFilepath != null) {
370
- await (0, node_fs_promises.mkdir)((0, pathe.dirname)(tsCodegenFilepath), { recursive: true }).catch(() => {});
371
- await (0, node_fs_promises.writeFile)(tsCodegenFilepath, await generateTsCodegenContent(ctx));
266
+ } catch (error) {
267
+ __pikacss_core.log.error(`Failed to load config file: ${error.message}`, error);
268
+ return {
269
+ config: null,
270
+ file: null
271
+ };
272
+ }
273
+ }
274
+ const resolvedConfig = (0, alien_signals.signal)(inlineConfig);
275
+ const resolvedConfigPath = (0, alien_signals.signal)(null);
276
+ async function loadConfig() {
277
+ const result = await _loadConfig();
278
+ resolvedConfig(result.config);
279
+ resolvedConfigPath(result.file);
280
+ return result;
281
+ }
282
+ return {
283
+ resolvedConfig,
284
+ resolvedConfigPath,
285
+ loadConfig
286
+ };
287
+ }
288
+ function useTransform({ cwd, scan, fnName, usages, engine, transformedFormat, triggerStyleUpdated, triggerTsCodegenUpdated }) {
289
+ const ESCAPE_REPLACE_RE = /[.*+?^${}()|[\]\\/]/g;
290
+ function createFnUtils(fnName$1) {
291
+ const available = {
292
+ normal: new Set([fnName$1]),
293
+ forceString: new Set([
294
+ `${fnName$1}.str`,
295
+ `${fnName$1}['str']`,
296
+ `${fnName$1}["str"]`,
297
+ `${fnName$1}[\`str\`]`
298
+ ]),
299
+ forceArray: new Set([
300
+ `${fnName$1}.arr`,
301
+ `${fnName$1}['arr']`,
302
+ `${fnName$1}["arr"]`,
303
+ `${fnName$1}[\`arr\`]`
304
+ ]),
305
+ forceInline: new Set([
306
+ `${fnName$1}.inl`,
307
+ `${fnName$1}['inl']`,
308
+ `${fnName$1}["inl"]`,
309
+ `${fnName$1}[\`inl\`]`
310
+ ]),
311
+ normalPreview: new Set([`${fnName$1}p`]),
312
+ forceStringPreview: new Set([
313
+ `${fnName$1}p.str`,
314
+ `${fnName$1}p['str']`,
315
+ `${fnName$1}p["str"]`,
316
+ `${fnName$1}p[\`str\`]`
317
+ ]),
318
+ forceArrayPreview: new Set([
319
+ `${fnName$1}p.arr`,
320
+ `${fnName$1}p['arr']`,
321
+ `${fnName$1}p["arr"]`,
322
+ `${fnName$1}p[\`arr\`]`
323
+ ]),
324
+ forceInlinePreview: new Set([
325
+ `${fnName$1}p.inl`,
326
+ `${fnName$1}p['inl']`,
327
+ `${fnName$1}p["inl"]`,
328
+ `${fnName$1}p[\`inl\`]`
329
+ ])
330
+ };
331
+ return {
332
+ isNormal: (fnName$2) => available.normal.has(fnName$2) || available.normalPreview.has(fnName$2),
333
+ isForceString: (fnName$2) => available.forceString.has(fnName$2) || available.forceStringPreview.has(fnName$2),
334
+ isForceArray: (fnName$2) => available.forceArray.has(fnName$2) || available.forceArrayPreview.has(fnName$2),
335
+ isForceInline: (fnName$2) => available.forceInline.has(fnName$2) || available.forceInlinePreview.has(fnName$2),
336
+ isPreview: (fnName$2) => available.normalPreview.has(fnName$2) || available.forceStringPreview.has(fnName$2) || available.forceArrayPreview.has(fnName$2) || available.forceInlinePreview.has(fnName$2),
337
+ RE: new RegExp(`\\b(${Object.values(available).flatMap((s) => [...s].map((f) => `(${f.replace(ESCAPE_REPLACE_RE, "\\$&")})`)).join("|")})\\(`, "g")
338
+ };
339
+ }
340
+ const fnUtils = createFnUtils(fnName);
341
+ function findFunctionCalls(code) {
342
+ const RE = fnUtils.RE;
343
+ const result = [];
344
+ let matched = RE.exec(code);
345
+ while (matched != null) {
346
+ const fnName$1 = matched[1];
347
+ const start = matched.index;
348
+ let end = start + fnName$1.length;
349
+ let depth = 1;
350
+ let inString = false;
351
+ while (depth > 0) {
352
+ end++;
353
+ if (inString === false && code[end] === "(") depth++;
354
+ else if (inString === false && code[end] === ")") depth--;
355
+ else if (inString === false && (code[end] === "'" || code[end] === "\"")) inString = code[end];
356
+ else if (inString === code[end]) inString = false;
372
357
  }
373
- ctx.isReady = true;
374
- }, 300),
375
- isReady: false,
376
- configSources,
377
- resolvedConfigPath: null,
378
- engine: null,
379
- transform: async (code, id) => {
380
- try {
381
- if (ctx.isReady === false || !needToTransform(id)) return;
382
- ctx.usages.delete(id);
383
- const functionCalls = findFunctionCalls(code, ctx.fnUtils.RE);
384
- if (functionCalls.length === 0) return;
385
- const usages = [];
386
- const transformed = new magic_string.default(code);
387
- for (const fnCall of functionCalls) {
388
- const argsStr = `[${fnCall.snippet.slice(fnCall.fnName.length + 1, -1)}]`;
389
- const args = new Function(`return ${argsStr}`)();
390
- const names = await ctx.engine.use(...args);
391
- const usage = {
392
- atomicStyleIds: names,
393
- params: args
394
- };
395
- usages.push(usage);
396
- let transformedContent;
397
- if (ctx.fnUtils.isNormal(fnCall.fnName)) transformedContent = ctx.transformedFormat === "array" ? `[${names.map((n) => `'${n}'`).join(", ")}]` : ctx.transformedFormat === "string" ? `'${names.join(" ")}'` : names.join(" ");
398
- else if (ctx.fnUtils.isForceString(fnCall.fnName)) transformedContent = `'${names.join(" ")}'`;
399
- else if (ctx.fnUtils.isForceArray(fnCall.fnName)) transformedContent = `[${names.map((n) => `'${n}'`).join(", ")}]`;
400
- else if (ctx.fnUtils.isForceInline(fnCall.fnName)) transformedContent = names.join(" ");
401
- else throw new Error(`Unexpected function name: ${fnCall.fnName}`);
402
- transformed.update(fnCall.start, fnCall.end + 1, transformedContent);
403
- }
404
- ctx.usages.set(id, usages);
405
- ctx.hooks.styleUpdated.trigger();
406
- ctx.hooks.tsCodegenUpdated.trigger();
407
- return {
408
- code: transformed.toString(),
409
- map: transformed.generateMap({ hires: true })
358
+ const snippet = code.slice(start, end + 1);
359
+ result.push({
360
+ fnName: fnName$1,
361
+ start,
362
+ end,
363
+ snippet
364
+ });
365
+ matched = RE.exec(code);
366
+ }
367
+ return result;
368
+ }
369
+ async function transform(code, id) {
370
+ const _engine = engine();
371
+ if (_engine == null) return null;
372
+ try {
373
+ __pikacss_core.log.debug(`Transforming file: ${id}`);
374
+ usages.delete(id);
375
+ const functionCalls = findFunctionCalls(code);
376
+ if (functionCalls.length === 0) return;
377
+ __pikacss_core.log.debug(`Found ${functionCalls.length} style function calls in ${id}`);
378
+ const usageList = [];
379
+ const transformed = new magic_string.default(code);
380
+ for (const fnCall of functionCalls) {
381
+ const argsStr = `[${fnCall.snippet.slice(fnCall.fnName.length + 1, -1)}]`;
382
+ const args = new Function(`return ${argsStr}`)();
383
+ const names = await _engine.use(...args);
384
+ const usage = {
385
+ atomicStyleIds: names,
386
+ params: args
410
387
  };
411
- } catch (error) {
412
- (0, __pikacss_core.warn)(`Failed to transform code: ${error.message}`, error);
413
- return;
388
+ usageList.push(usage);
389
+ let transformedContent;
390
+ if (fnUtils.isNormal(fnCall.fnName)) transformedContent = transformedFormat === "array" ? `[${names.map((n) => `'${n}'`).join(", ")}]` : transformedFormat === "string" ? `'${names.join(" ")}'` : names.join(" ");
391
+ else if (fnUtils.isForceString(fnCall.fnName)) transformedContent = `'${names.join(" ")}'`;
392
+ else if (fnUtils.isForceArray(fnCall.fnName)) transformedContent = `[${names.map((n) => `'${n}'`).join(", ")}]`;
393
+ else if (fnUtils.isForceInline(fnCall.fnName)) transformedContent = names.join(" ");
394
+ else throw new Error(`Unexpected function name: ${fnCall.fnName}`);
395
+ transformed.update(fnCall.start, fnCall.end + 1, transformedContent);
414
396
  }
397
+ usages.set(id, usageList);
398
+ triggerStyleUpdated();
399
+ triggerTsCodegenUpdated();
400
+ __pikacss_core.log.debug(`Transformed ${usageList.length} style usages in ${id}`);
401
+ return {
402
+ code: transformed.toString(),
403
+ map: transformed.generateMap({ hires: true })
404
+ };
405
+ } catch (error) {
406
+ __pikacss_core.log.error(`Failed to transform code (${(0, pathe.join)(cwd(), id)}): ${error.message}`, error);
407
+ return;
408
+ }
409
+ }
410
+ return {
411
+ transformFilter: scan,
412
+ transform
413
+ };
414
+ }
415
+ function createCtx(options) {
416
+ const { cwd, cssCodegenFilepath, tsCodegenFilepath } = usePaths(options);
417
+ const { resolvedConfig, resolvedConfigPath, loadConfig } = useConfig({
418
+ ...options,
419
+ cwd,
420
+ tsCodegenFilepath
421
+ });
422
+ const usages = /* @__PURE__ */ new Map();
423
+ const engine = (0, alien_signals.signal)(null);
424
+ const hooks = {
425
+ styleUpdated: createEventHook(),
426
+ tsCodegenUpdated: createEventHook()
427
+ };
428
+ const { transformFilter, transform } = useTransform({
429
+ ...options,
430
+ cwd,
431
+ usages,
432
+ engine,
433
+ triggerStyleUpdated: () => hooks.styleUpdated.trigger(),
434
+ triggerTsCodegenUpdated: () => hooks.tsCodegenUpdated.trigger()
435
+ });
436
+ const ctx = {
437
+ currentPackageName: options.currentPackageName,
438
+ fnName: options.fnName,
439
+ transformedFormat: options.transformedFormat,
440
+ get cwd() {
441
+ return cwd();
442
+ },
443
+ set cwd(v) {
444
+ cwd(v);
415
445
  },
416
- getCssContent: async (isDev) => {
417
- if (ctx.isReady === false) return null;
446
+ get cssCodegenFilepath() {
447
+ return cssCodegenFilepath();
448
+ },
449
+ get tsCodegenFilepath() {
450
+ return tsCodegenFilepath();
451
+ },
452
+ get hasVue() {
453
+ return (0, local_pkg.isPackageExists)("vue", { paths: [cwd()] });
454
+ },
455
+ get resolvedConfig() {
456
+ return resolvedConfig();
457
+ },
458
+ get resolvedConfigPath() {
459
+ return resolvedConfigPath();
460
+ },
461
+ loadConfig,
462
+ usages,
463
+ hooks,
464
+ get engine() {
465
+ const _engine = engine();
466
+ if (_engine == null) throw new Error("Engine is not initialized yet");
467
+ return _engine;
468
+ },
469
+ transformFilter,
470
+ transform: async (code, id) => {
471
+ await ctx.setupPromise;
472
+ return transform(code, id);
473
+ },
474
+ getCssCodegenContent: async () => {
475
+ await ctx.setupPromise;
476
+ __pikacss_core.log.debug("Generating CSS code");
418
477
  const atomicStyleIds = [...new Set([...ctx.usages.values()].flatMap((i) => [...new Set(i.flatMap((i$1) => i$1.atomicStyleIds))]))];
478
+ __pikacss_core.log.debug(`Collecting ${atomicStyleIds.length} atomic style IDs`);
419
479
  return [
420
480
  `/* Auto-generated by ${ctx.currentPackageName} */`,
421
- await ctx.engine.renderPreflights(isDev),
422
- await ctx.engine.renderAtomicStyles(isDev, { atomicStyleIds })
481
+ await ctx.engine.renderPreflights(true),
482
+ await ctx.engine.renderAtomicStyles(true, { atomicStyleIds })
423
483
  ].join("\n").trim();
424
484
  },
425
485
  getTsCodegenContent: async () => {
426
- if (ctx.isReady === false || ctx.tsCodegenFilepath == null) return null;
486
+ await ctx.setupPromise;
487
+ if (ctx.tsCodegenFilepath == null) return null;
427
488
  return await generateTsCodegenContent(ctx);
428
489
  },
429
- writeDevCssFile: (0, perfect_debounce.debounce)(async () => {
430
- const content = await ctx.getCssContent(true);
490
+ writeCssCodegenFile: async () => {
491
+ await ctx.setupPromise;
492
+ const content = await ctx.getCssCodegenContent();
431
493
  if (content == null) return;
432
- await (0, node_fs_promises.writeFile)(ctx.devCssFilepath, content);
433
- }, 300),
434
- writeTsCodegenFile: (0, perfect_debounce.debounce)(async () => {
494
+ await (0, node_fs_promises.mkdir)((0, pathe.dirname)(ctx.cssCodegenFilepath), { recursive: true }).catch(() => {});
495
+ __pikacss_core.log.debug(`Writing CSS code generation file: ${ctx.cssCodegenFilepath}`);
496
+ await (0, node_fs_promises.writeFile)(ctx.cssCodegenFilepath, content);
497
+ },
498
+ writeTsCodegenFile: async () => {
499
+ await ctx.setupPromise;
500
+ if (ctx.tsCodegenFilepath == null) return;
435
501
  const content = await ctx.getTsCodegenContent();
436
- if (ctx.tsCodegenFilepath == null || content == null) return;
502
+ if (content == null) return;
503
+ await (0, node_fs_promises.mkdir)((0, pathe.dirname)(ctx.tsCodegenFilepath), { recursive: true }).catch(() => {});
504
+ __pikacss_core.log.debug(`Writing TypeScript code generation file: ${ctx.tsCodegenFilepath}`);
437
505
  await (0, node_fs_promises.writeFile)(ctx.tsCodegenFilepath, content);
438
- }, 300)
506
+ },
507
+ fullyCssCodegen: async () => {
508
+ await ctx.setupPromise;
509
+ __pikacss_core.log.debug("Starting full CSS code generation scan");
510
+ const stream = (0, globby.globbyStream)(options.scan.include, { ignore: options.scan.exclude });
511
+ let fileCount = 0;
512
+ const _cwd = cwd();
513
+ for await (const entry of stream) {
514
+ const code = await (0, node_fs_promises.readFile)((0, pathe.join)(_cwd, entry), "utf-8");
515
+ await ctx.transform(code, entry);
516
+ fileCount++;
517
+ }
518
+ __pikacss_core.log.debug(`Scanned ${fileCount} files for style collection`);
519
+ await ctx.writeCssCodegenFile();
520
+ },
521
+ setupPromise: null,
522
+ setup: () => {
523
+ ctx.setupPromise = setup().catch((error) => {
524
+ __pikacss_core.log.error(`Failed to setup integration context: ${error.message}`, error);
525
+ }).then(() => {
526
+ ctx.setupPromise = null;
527
+ });
528
+ return ctx.setupPromise;
529
+ }
439
530
  };
440
- await ctx.init();
531
+ async function setup() {
532
+ __pikacss_core.log.debug("Setting up integration context");
533
+ usages.clear();
534
+ hooks.styleUpdated.listeners.clear();
535
+ hooks.tsCodegenUpdated.listeners.clear();
536
+ engine(null);
537
+ await loadConfig();
538
+ const devPlugin = (0, __pikacss_core.defineEnginePlugin)({
539
+ name: "@pikacss/integration:dev",
540
+ preflightUpdated: () => hooks.styleUpdated.trigger(),
541
+ atomicStyleAdded: () => hooks.styleUpdated.trigger(),
542
+ autocompleteConfigUpdated: () => hooks.tsCodegenUpdated.trigger()
543
+ });
544
+ try {
545
+ const config = resolvedConfig() ?? {};
546
+ config.plugins = config.plugins ?? [];
547
+ config.plugins.unshift(devPlugin);
548
+ __pikacss_core.log.debug("Creating engine with loaded/default config");
549
+ engine(await (0, __pikacss_core.createEngine)(config));
550
+ } catch (error) {
551
+ __pikacss_core.log.error(`Failed to create engine: ${error.message}. Falling back to default config.`, error);
552
+ engine(await (0, __pikacss_core.createEngine)({ plugins: [devPlugin] }));
553
+ }
554
+ __pikacss_core.log.debug("Integration context setup successfully");
555
+ }
441
556
  return ctx;
442
557
  }
443
558