@pikacss/integration 0.0.30 → 0.0.32

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
@@ -1,430 +1,451 @@
1
- 'use strict';
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
2
26
 
3
- const node_fs = require('node:fs');
4
- const promises = require('node:fs/promises');
5
- const core = require('@pikacss/core');
6
- const jiti = require('jiti');
7
- const klona = require('klona');
8
- const localPkg = require('local-pkg');
9
- const MagicString = require('magic-string');
10
- const micromatch = require('micromatch');
11
- const pathe = require('pathe');
12
- const perfectDebounce = require('perfect-debounce');
13
-
14
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
15
-
16
- const MagicString__default = /*#__PURE__*/_interopDefaultCompat(MagicString);
17
- const micromatch__default = /*#__PURE__*/_interopDefaultCompat(micromatch);
27
+ //#endregion
28
+ let node_fs = require("node:fs");
29
+ let node_fs_promises = require("node:fs/promises");
30
+ let __pikacss_core = require("@pikacss/core");
31
+ let jiti = require("jiti");
32
+ let klona = require("klona");
33
+ let local_pkg = require("local-pkg");
34
+ let magic_string = require("magic-string");
35
+ magic_string = __toESM(magic_string);
36
+ let micromatch = require("micromatch");
37
+ micromatch = __toESM(micromatch);
38
+ let pathe = require("pathe");
39
+ let perfect_debounce = require("perfect-debounce");
18
40
 
41
+ //#region src/eventHook.ts
19
42
  function createEventHook() {
20
- const listeners = /* @__PURE__ */ new Set();
21
- function trigger(payload) {
22
- listeners.forEach((listener) => listener(payload));
23
- }
24
- function off(listener) {
25
- listeners.delete(listener);
26
- }
27
- function on(listener) {
28
- listeners.add(listener);
29
- const offListener = () => off(listener);
30
- return offListener;
31
- }
32
- return {
33
- listeners,
34
- trigger,
35
- on,
36
- off
37
- };
43
+ const listeners = /* @__PURE__ */ new Set();
44
+ function trigger(payload) {
45
+ listeners.forEach((listener) => listener(payload));
46
+ }
47
+ function off(listener) {
48
+ listeners.delete(listener);
49
+ }
50
+ function on(listener) {
51
+ listeners.add(listener);
52
+ const offListener = () => off(listener);
53
+ return offListener;
54
+ }
55
+ return {
56
+ listeners,
57
+ trigger,
58
+ on,
59
+ off
60
+ };
38
61
  }
39
62
 
63
+ //#endregion
64
+ //#region src/tsCodegen.ts
40
65
  function formatUnionStringType(list) {
41
- return list.length > 0 ? list.map((i) => typeof i === "number" ? i : `'${i}'`).join(" | ") : "never";
66
+ return list.length > 0 ? list.map((i) => typeof i === "number" ? i : `'${i}'`).join(" | ") : "never";
42
67
  }
43
68
  function generateAutocomplete(ctx) {
44
- const autocomplete = ctx.engine.config.autocomplete;
45
- return [
46
- "export type Autocomplete = DefineAutocomplete<{",
47
- ` Selector: ${formatUnionStringType([...autocomplete.selectors])}`,
48
- ` StyleItemString: ${formatUnionStringType([...autocomplete.styleItemStrings])}`,
49
- ` ExtraProperty: ${formatUnionStringType([...autocomplete.extraProperties])}`,
50
- ` ExtraCssProperty: ${formatUnionStringType([...autocomplete.extraCssProperties])}`,
51
- ` PropertiesValue: { ${Array.from(autocomplete.properties.entries(), ([k, v]) => `'${k}': ${v.join(" | ")}`).join(",")} }`,
52
- ` CssPropertiesValue: { ${Array.from(autocomplete.cssProperties.entries(), ([k, v]) => `'${k}': ${formatUnionStringType(v)}`).join(",")} }`,
53
- "}>",
54
- ""
55
- ];
69
+ const autocomplete = ctx.engine.config.autocomplete;
70
+ return [
71
+ "export type Autocomplete = DefineAutocomplete<{",
72
+ ` Selector: ${formatUnionStringType([...autocomplete.selectors])}`,
73
+ ` StyleItemString: ${formatUnionStringType([...autocomplete.styleItemStrings])}`,
74
+ ` ExtraProperty: ${formatUnionStringType([...autocomplete.extraProperties])}`,
75
+ ` ExtraCssProperty: ${formatUnionStringType([...autocomplete.extraCssProperties])}`,
76
+ ` PropertiesValue: { ${Array.from(autocomplete.properties.entries(), ([k, v]) => `'${k}': ${v.join(" | ")}`).join(",")} }`,
77
+ ` CssPropertiesValue: { ${Array.from(autocomplete.cssProperties.entries(), ([k, v]) => `'${k}': ${formatUnionStringType(v)}`).join(",")} }`,
78
+ "}>",
79
+ ""
80
+ ];
56
81
  }
57
82
  function generateStyleFn(ctx) {
58
- const { transformedFormat } = ctx;
59
- const lines = [
60
- "type StyleFn_Array = (...params: StyleItem[]) => string[]",
61
- "type StyleFn_String = (...params: StyleItem[]) => string",
62
- "type StyleFn_Inline = (...params: StyleItem[]) => void"
63
- ];
64
- if (transformedFormat === "array")
65
- lines.push("type StyleFn_Normal = StyleFn_Array");
66
- else if (transformedFormat === "string")
67
- lines.push("type StyleFn_Normal = StyleFn_String");
68
- else if (transformedFormat === "inline")
69
- lines.push("type StyleFn_Normal = StyleFn_Inline");
70
- lines.push(
71
- "type StyleFn = StyleFn_Normal & {",
72
- " str: StyleFn_String",
73
- " arr: StyleFn_Array",
74
- " inl: StyleFn_Inline",
75
- "}",
76
- `type StyleFnWithPreview = PreviewOverloads<StyleFn_Normal>['fn'] & {`,
77
- ` str: PreviewOverloads<StyleFn_String>['fn']`,
78
- ` arr: PreviewOverloads<StyleFn_Array>['fn']`,
79
- ` inl: PreviewOverloads<StyleFn_Inline>['fn']`,
80
- "}",
81
- ""
82
- );
83
- return lines;
83
+ const { transformedFormat } = ctx;
84
+ const lines = [
85
+ "type StyleFn_Array = (...params: StyleItem[]) => string[]",
86
+ "type StyleFn_String = (...params: StyleItem[]) => string",
87
+ "type StyleFn_Inline = (...params: StyleItem[]) => void"
88
+ ];
89
+ if (transformedFormat === "array") lines.push("type StyleFn_Normal = StyleFn_Array");
90
+ else if (transformedFormat === "string") lines.push("type StyleFn_Normal = StyleFn_String");
91
+ else if (transformedFormat === "inline") lines.push("type StyleFn_Normal = StyleFn_Inline");
92
+ lines.push("type StyleFn = StyleFn_Normal & {", " str: StyleFn_String", " arr: StyleFn_Array", " inl: StyleFn_Inline", "}", `type StyleFnWithPreview = PreviewOverloads<StyleFn_Normal>[\'fn\'] & {`, ` str: PreviewOverloads<StyleFn_String>[\'fn\']`, ` arr: PreviewOverloads<StyleFn_Array>[\'fn\']`, ` inl: PreviewOverloads<StyleFn_Inline>[\'fn\']`, "}", "");
93
+ return lines;
84
94
  }
85
95
  function generateGlobalDeclaration(ctx) {
86
- const { fnName } = ctx;
87
- return [
88
- "declare global {",
89
- " /**",
90
- " * PikaCSS",
91
- " */",
92
- ` const ${fnName}: StyleFn`,
93
- "",
94
- " /**",
95
- " * PikaCSS Preview",
96
- " */",
97
- ` const ${fnName}p: StyleFnWithPreview`,
98
- "}",
99
- ""
100
- ];
96
+ const { fnName } = ctx;
97
+ return [
98
+ "declare global {",
99
+ " /**",
100
+ " * PikaCSS",
101
+ " */",
102
+ ` const ${fnName}: StyleFn`,
103
+ "",
104
+ " /**",
105
+ " * PikaCSS Preview",
106
+ " */",
107
+ ` const ${fnName}p: StyleFnWithPreview`,
108
+ "}",
109
+ ""
110
+ ];
101
111
  }
102
112
  function generateVueDeclaration(ctx) {
103
- const { hasVue, fnName } = ctx;
104
- if (!hasVue)
105
- return [];
106
- return [
107
- "declare module 'vue' {",
108
- " interface ComponentCustomProperties {",
109
- " /**",
110
- " * PikaCSS",
111
- " */",
112
- ` ${fnName}: StyleFn`,
113
- "",
114
- " /**",
115
- " * PikaCSS Preview",
116
- " */",
117
- ` ${fnName}p: StyleFnWithPreview`,
118
- " }",
119
- "}",
120
- ""
121
- ];
113
+ const { hasVue, fnName } = ctx;
114
+ if (!hasVue) return [];
115
+ return [
116
+ "declare module 'vue' {",
117
+ " interface ComponentCustomProperties {",
118
+ " /**",
119
+ " * PikaCSS",
120
+ " */",
121
+ ` ${fnName}: StyleFn`,
122
+ "",
123
+ " /**",
124
+ " * PikaCSS Preview",
125
+ " */",
126
+ ` ${fnName}p: StyleFnWithPreview`,
127
+ " }",
128
+ "}",
129
+ ""
130
+ ];
122
131
  }
123
132
  async function generateOverloadContent(ctx) {
124
- const paramsLines = [];
125
- const fnsLines = [];
126
- const usages = [...ctx.usages.values()].flat();
127
- for (let i = 0; i < usages.length; i++) {
128
- const usage = usages[i];
129
- try {
130
- const addedParamsLines = usage.params.map((param, index) => `type P${i}_${index} = ${JSON.stringify(param)}`);
131
- const addedFnLines = [
132
- " /**",
133
- " * ### PikaCSS Preview",
134
- " * ```css",
135
- // CSS Lines
136
- ...(await ctx.engine.renderAtomicStyles(true, { atomicStyleIds: usage.atomicStyleIds, isPreview: true })).trim().split("\n").map((line) => ` * \u200E${line.replace(/^(\s*)/, "$1\u200E")}`),
137
- " * ```",
138
- " */",
139
- ` fn(...params: [${usage.params.map((_, index) => `p${index}: P${i}_${index}`).join(", ")}]): ReturnType<StyleFn>`
140
- ];
141
- paramsLines.push(...addedParamsLines);
142
- fnsLines.push(...addedFnLines);
143
- } catch {
144
- }
145
- }
146
- return [
147
- "interface PreviewOverloads<StyleFn extends (StyleFn_Array | StyleFn_String | StyleFn_Inline)> {",
148
- ...fnsLines,
149
- " /**",
150
- " * PikaCSS Preview",
151
- " * Save the current file to see the preview.",
152
- " */",
153
- ` fn(...params: Parameters<StyleFn>): ReturnType<StyleFn>`,
154
- "}",
155
- ...paramsLines
156
- ];
133
+ const paramsLines = [];
134
+ const fnsLines = [];
135
+ const usages = [...ctx.usages.values()].flat();
136
+ for (let i = 0; i < usages.length; i++) {
137
+ const usage = usages[i];
138
+ try {
139
+ const addedParamsLines = usage.params.map((param, index) => `type P${i}_${index} = ${JSON.stringify(param)}`);
140
+ const addedFnLines = [
141
+ " /**",
142
+ " * ### PikaCSS Preview",
143
+ " * ```css",
144
+ ...(await ctx.engine.renderAtomicStyles(true, {
145
+ atomicStyleIds: usage.atomicStyleIds,
146
+ isPreview: true
147
+ })).trim().split("\n").map((line) => ` * ‎${line.replace(/^(\s*)/, "$1‎")}`),
148
+ " * ```",
149
+ " */",
150
+ ` fn(...params: [${usage.params.map((_, index) => `p${index}: P${i}_${index}`).join(", ")}]): ReturnType<StyleFn>`
151
+ ];
152
+ paramsLines.push(...addedParamsLines);
153
+ fnsLines.push(...addedFnLines);
154
+ } catch {}
155
+ }
156
+ return [
157
+ "interface PreviewOverloads<StyleFn extends (StyleFn_Array | StyleFn_String | StyleFn_Inline)> {",
158
+ ...fnsLines,
159
+ " /**",
160
+ " * PikaCSS Preview",
161
+ " * Save the current file to see the preview.",
162
+ " */",
163
+ ` fn(...params: Parameters<StyleFn>): ReturnType<StyleFn>`,
164
+ "}",
165
+ ...paramsLines
166
+ ];
157
167
  }
158
168
  async function generateTsCodegenContent(ctx) {
159
- const lines = [
160
- `// Auto-generated by ${ctx.currentPackageName}`,
161
- `import type { CSSProperty, CSSSelectors, DefineAutocomplete, Properties, StyleDefinition, StyleItem } from '${ctx.currentPackageName}'`,
162
- "",
163
- `declare module '${ctx.currentPackageName}' {`,
164
- " interface PikaAugment {",
165
- " Autocomplete: Autocomplete",
166
- " Selector: Autocomplete['Selector'] | CSSSelectors",
167
- " CSSProperty: Autocomplete['ExtraCssProperty'] | CSSProperty",
168
- " Properties: Properties",
169
- " StyleDefinition: StyleDefinition",
170
- " StyleItem: StyleItem",
171
- " }",
172
- "}",
173
- ""
174
- ];
175
- lines.push(...generateAutocomplete(ctx));
176
- lines.push(...generateStyleFn(ctx));
177
- lines.push(...generateGlobalDeclaration(ctx));
178
- lines.push(...generateVueDeclaration(ctx));
179
- lines.push(...await generateOverloadContent(ctx));
180
- return lines.join("\n");
169
+ const lines = [
170
+ `// Auto-generated by ${ctx.currentPackageName}`,
171
+ `import type { CSSProperty, CSSSelectors, DefineAutocomplete, Properties, StyleDefinition, StyleItem } from \'${ctx.currentPackageName}\'`,
172
+ "",
173
+ `declare module \'${ctx.currentPackageName}\' {`,
174
+ " interface PikaAugment {",
175
+ " Autocomplete: Autocomplete",
176
+ " Selector: Autocomplete['Selector'] | CSSSelectors",
177
+ " CSSProperty: Autocomplete['ExtraCssProperty'] | CSSProperty",
178
+ " Properties: Properties",
179
+ " StyleDefinition: StyleDefinition",
180
+ " StyleItem: StyleItem",
181
+ " }",
182
+ "}",
183
+ ""
184
+ ];
185
+ lines.push(...generateAutocomplete(ctx));
186
+ lines.push(...generateStyleFn(ctx));
187
+ lines.push(...generateGlobalDeclaration(ctx));
188
+ lines.push(...generateVueDeclaration(ctx));
189
+ lines.push(...await generateOverloadContent(ctx));
190
+ return lines.join("\n");
181
191
  }
182
192
 
193
+ //#endregion
194
+ //#region src/ctx.ts
183
195
  function findFunctionCalls(code, RE) {
184
- const result = [];
185
- let matched = RE.exec(code);
186
- while (matched != null) {
187
- const fnName = matched[1];
188
- const start = matched.index;
189
- let end = start + fnName.length;
190
- let depth = 1;
191
- let inString = false;
192
- while (depth > 0) {
193
- end++;
194
- if (inString === false && code[end] === "(")
195
- depth++;
196
- else if (inString === false && code[end] === ")")
197
- depth--;
198
- else if (inString === false && (code[end] === "'" || code[end] === '"'))
199
- inString = code[end];
200
- else if (inString === code[end])
201
- inString = false;
202
- }
203
- const snippet = code.slice(start, end + 1);
204
- result.push({ fnName, start, end, snippet });
205
- matched = RE.exec(code);
206
- }
207
- return result;
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;
208
221
  }
209
222
  const ESCAPE_REPLACE_RE = /[.*+?^${}()|[\]\\/]/g;
210
223
  function createFnUtils(fnName) {
211
- const available = {
212
- normal: /* @__PURE__ */ new Set([fnName]),
213
- forceString: /* @__PURE__ */ new Set([`${fnName}.str`, `${fnName}['str']`, `${fnName}["str"]`, `${fnName}[\`str\`]`]),
214
- forceArray: /* @__PURE__ */ new Set([`${fnName}.arr`, `${fnName}['arr']`, `${fnName}["arr"]`, `${fnName}[\`arr\`]`]),
215
- forceInline: /* @__PURE__ */ new Set([`${fnName}.inl`, `${fnName}['inl']`, `${fnName}["inl"]`, `${fnName}[\`inl\`]`]),
216
- // preview
217
- normalPreview: /* @__PURE__ */ new Set([`${fnName}p`]),
218
- forceStringPreview: /* @__PURE__ */ new Set([`${fnName}p.str`, `${fnName}p['str']`, `${fnName}p["str"]`, `${fnName}p[\`str\`]`]),
219
- forceArrayPreview: /* @__PURE__ */ new Set([`${fnName}p.arr`, `${fnName}p['arr']`, `${fnName}p["arr"]`, `${fnName}p[\`arr\`]`]),
220
- forceInlinePreview: /* @__PURE__ */ new Set([`${fnName}p.inl`, `${fnName}p['inl']`, `${fnName}p["inl"]`, `${fnName}p[\`inl\`]`])
221
- };
222
- const RE = new RegExp(`\\b(${Object.values(available).flatMap((s) => [...s].map((f) => `(${f.replace(ESCAPE_REPLACE_RE, "\\$&")})`)).join("|")})\\(`, "g");
223
- return {
224
- isNormal: (fnName2) => available.normal.has(fnName2) || available.normalPreview.has(fnName2),
225
- isForceString: (fnName2) => available.forceString.has(fnName2) || available.forceStringPreview.has(fnName2),
226
- isForceArray: (fnName2) => available.forceArray.has(fnName2) || available.forceArrayPreview.has(fnName2),
227
- isForceInline: (fnName2) => available.forceInline.has(fnName2) || available.forceInlinePreview.has(fnName2),
228
- isPreview: (fnName2) => available.normalPreview.has(fnName2) || available.forceStringPreview.has(fnName2) || available.forceArrayPreview.has(fnName2) || available.forceInlinePreview.has(fnName2),
229
- RE
230
- };
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
+ };
264
+ 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")
271
+ };
231
272
  }
232
273
  async function createCtx(options) {
233
- const {
234
- cwd,
235
- currentPackageName,
236
- target,
237
- configOrPath,
238
- fnName,
239
- transformedFormat,
240
- tsCodegen,
241
- devCss,
242
- autoCreateConfig
243
- } = options;
244
- core.setWarnFn((...args) => {
245
- console.warn(`[${currentPackageName}]`, ...args);
246
- });
247
- const devCssFilepath = pathe.isAbsolute(devCss) ? pathe.resolve(devCss) : pathe.join(cwd, devCss);
248
- const tsCodegenFilepath = tsCodegen === false ? null : pathe.isAbsolute(tsCodegen) ? pathe.resolve(tsCodegen) : pathe.join(cwd, tsCodegen);
249
- const inlineConfig = typeof configOrPath === "object" ? configOrPath : null;
250
- const specificConfigPath = typeof configOrPath === "string" ? pathe.isAbsolute(configOrPath) ? configOrPath : pathe.join(cwd, configOrPath) : null;
251
- const configSources = [
252
- ...specificConfigPath == null ? [] : [specificConfigPath],
253
- ...["pika", "pikacss"].flatMap((name) => ["js", "ts", "cjs", "cts", "mjs", "mts"].map((ext) => `${name}.config.${ext}`)).map((name) => pathe.join(cwd, name))
254
- ];
255
- const targetREs = target.map((t) => micromatch__default.makeRe(t));
256
- const needToTransform = (id) => targetREs.some((re) => re.test(id));
257
- const ctx = {
258
- cwd,
259
- currentPackageName,
260
- fnName,
261
- fnUtils: createFnUtils(fnName),
262
- transformedFormat,
263
- devCssFilepath,
264
- tsCodegenFilepath,
265
- hasVue: localPkg.isPackageExists("vue", { paths: [cwd] }),
266
- usages: /* @__PURE__ */ new Map(),
267
- hooks: {
268
- styleUpdated: createEventHook(),
269
- tsCodegenUpdated: createEventHook()
270
- },
271
- loadConfig: async () => {
272
- if (inlineConfig != null)
273
- return { config: klona.klona(inlineConfig), file: null };
274
- let resolvedConfigPath = configSources.find((path) => {
275
- const stat = node_fs.statSync(path, { throwIfNoEntry: false });
276
- return stat != null && stat.isFile();
277
- });
278
- if (resolvedConfigPath == null) {
279
- if (autoCreateConfig === false)
280
- return { config: null, file: null };
281
- resolvedConfigPath = configSources[0];
282
- await promises.mkdir(pathe.dirname(resolvedConfigPath), { recursive: true }).catch(() => {
283
- });
284
- const relativeTsCodegenFilepath = tsCodegenFilepath == null ? null : `./${pathe.relative(pathe.dirname(resolvedConfigPath), tsCodegenFilepath)}`;
285
- await promises.writeFile(resolvedConfigPath, [
286
- `import { defineEngineConfig } from '${currentPackageName}'`,
287
- ...relativeTsCodegenFilepath == null ? [] : [`/** @type {import('${relativeTsCodegenFilepath}')} */`],
288
- "",
289
- "export default defineEngineConfig({",
290
- " // Add your PikaCSS engine config here",
291
- "})"
292
- ].join("\n"));
293
- }
294
- const jiti$1 = jiti.createJiti(cwd, {
295
- fsCache: false,
296
- moduleCache: false
297
- });
298
- const config = jiti$1.evalModule(await promises.readFile(resolvedConfigPath, { encoding: "utf-8" }), { filename: resolvedConfigPath }).default;
299
- return { config: klona.klona(config), file: resolvedConfigPath };
300
- },
301
- init: perfectDebounce.debounce(async () => {
302
- ctx.isReady = false;
303
- ctx.usages.clear();
304
- const { config, file } = await ctx.loadConfig().catch((error) => {
305
- core.warn(`Failed to load config file: ${error.message}`, error);
306
- return { config: null, file: null };
307
- });
308
- ctx.resolvedConfigPath = file;
309
- const devPlugin = core.defineEnginePlugin({
310
- name: "@pikacss/integration:dev",
311
- preflightUpdated: () => ctx.hooks.styleUpdated.trigger(),
312
- atomicStyleAdded: () => ctx.hooks.styleUpdated.trigger(),
313
- autocompleteConfigUpdated: () => ctx.hooks.tsCodegenUpdated.trigger()
314
- });
315
- try {
316
- const _config = config ?? {};
317
- _config.plugins = _config.plugins ?? [];
318
- _config.plugins.unshift(devPlugin);
319
- ctx.engine = await core.createEngine(_config);
320
- } catch (error) {
321
- core.warn(`Failed to create engine: ${error.message}. Maybe the config file is invalid, falling back to default config.`, error);
322
- ctx.engine = await core.createEngine({ plugins: [devPlugin] });
323
- }
324
- await promises.mkdir(pathe.dirname(devCssFilepath), { recursive: true }).catch(() => {
325
- });
326
- await promises.writeFile(devCssFilepath, "");
327
- if (tsCodegenFilepath != null) {
328
- await promises.mkdir(pathe.dirname(tsCodegenFilepath), { recursive: true }).catch(() => {
329
- });
330
- const content = await generateTsCodegenContent(ctx);
331
- await promises.writeFile(tsCodegenFilepath, content);
332
- }
333
- ctx.isReady = true;
334
- }, 300),
335
- isReady: false,
336
- configSources,
337
- resolvedConfigPath: null,
338
- engine: null,
339
- transform: async (code, id) => {
340
- try {
341
- if (ctx.isReady === false || !needToTransform(id)) {
342
- return;
343
- }
344
- ctx.usages.delete(id);
345
- const functionCalls = findFunctionCalls(code, ctx.fnUtils.RE);
346
- if (functionCalls.length === 0)
347
- return;
348
- const usages = [];
349
- const transformed = new MagicString__default(code);
350
- for (const fnCall of functionCalls) {
351
- const functionCallStr = fnCall.snippet;
352
- const argsStr = `[${functionCallStr.slice(fnCall.fnName.length + 1, -1)}]`;
353
- const args = new Function(`return ${argsStr}`)();
354
- const names = await ctx.engine.use(...args);
355
- const usage = {
356
- atomicStyleIds: names,
357
- params: args
358
- };
359
- usages.push(usage);
360
- let transformedContent;
361
- if (ctx.fnUtils.isNormal(fnCall.fnName)) {
362
- transformedContent = ctx.transformedFormat === "array" ? `[${names.map((n) => `'${n}'`).join(", ")}]` : ctx.transformedFormat === "string" ? `'${names.join(" ")}'` : names.join(" ");
363
- } else if (ctx.fnUtils.isForceString(fnCall.fnName)) {
364
- transformedContent = `'${names.join(" ")}'`;
365
- } else if (ctx.fnUtils.isForceArray(fnCall.fnName)) {
366
- transformedContent = `[${names.map((n) => `'${n}'`).join(", ")}]`;
367
- } else if (ctx.fnUtils.isForceInline(fnCall.fnName)) {
368
- transformedContent = names.join(" ");
369
- } else {
370
- throw new Error(`Unexpected function name: ${fnCall.fnName}`);
371
- }
372
- transformed.update(fnCall.start, fnCall.end + 1, transformedContent);
373
- }
374
- ctx.usages.set(id, usages);
375
- ctx.hooks.styleUpdated.trigger();
376
- ctx.hooks.tsCodegenUpdated.trigger();
377
- return {
378
- code: transformed.toString(),
379
- map: transformed.generateMap({ hires: true })
380
- };
381
- } catch (error) {
382
- core.warn(`Failed to transform code: ${error.message}`, error);
383
- return void 0;
384
- }
385
- },
386
- getCssContent: async (isDev) => {
387
- if (ctx.isReady === false)
388
- return null;
389
- const atomicStyleIds = [...new Set([...ctx.usages.values()].flatMap((i) => [...new Set(i.flatMap((i2) => i2.atomicStyleIds))]))];
390
- const css = [
391
- `/* Auto-generated by ${ctx.currentPackageName} */`,
392
- await ctx.engine.renderPreflights(isDev),
393
- await ctx.engine.renderAtomicStyles(isDev, { atomicStyleIds })
394
- ].join("\n").trim();
395
- return css;
396
- },
397
- getTsCodegenContent: async () => {
398
- if (ctx.isReady === false || ctx.tsCodegenFilepath == null)
399
- return null;
400
- const content = await generateTsCodegenContent(ctx);
401
- return content;
402
- },
403
- writeDevCssFile: perfectDebounce.debounce(async () => {
404
- const content = await ctx.getCssContent(true);
405
- if (content == null)
406
- return;
407
- await promises.writeFile(ctx.devCssFilepath, content);
408
- }, 300),
409
- writeTsCodegenFile: perfectDebounce.debounce(async () => {
410
- const content = await ctx.getTsCodegenContent();
411
- if (ctx.tsCodegenFilepath == null || content == null)
412
- return;
413
- await promises.writeFile(ctx.tsCodegenFilepath, content);
414
- }, 300)
415
- };
416
- await ctx.init();
417
- return ctx;
274
+ const { cwd, currentPackageName, target, configOrPath, fnName, transformedFormat, tsCodegen, devCss, autoCreateConfig } = options;
275
+ (0, __pikacss_core.setWarnFn)((...args) => {
276
+ console.warn(`[${currentPackageName}]`, ...args);
277
+ });
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);
280
+ 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,
318
+ file: null
319
+ };
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, [
324
+ `import { defineEngineConfig } from '${currentPackageName}'`,
325
+ ...relativeTsCodegenFilepath == null ? [] : [`/** @type {import('${relativeTsCodegenFilepath}')} */`],
326
+ "",
327
+ "export default defineEngineConfig({",
328
+ " // Add your PikaCSS engine config here",
329
+ "})"
330
+ ].join("\n"));
331
+ }
332
+ const config = (await (0, jiti.createJiti)(cwd, {
333
+ fsCache: false,
334
+ moduleCache: false
335
+ }).import(resolvedConfigPath)).default;
336
+ return {
337
+ config: (0, klona.klona)(config),
338
+ file: resolvedConfigPath
339
+ };
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));
372
+ }
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 })
410
+ };
411
+ } catch (error) {
412
+ (0, __pikacss_core.warn)(`Failed to transform code: ${error.message}`, error);
413
+ return;
414
+ }
415
+ },
416
+ getCssContent: async (isDev) => {
417
+ if (ctx.isReady === false) return null;
418
+ const atomicStyleIds = [...new Set([...ctx.usages.values()].flatMap((i) => [...new Set(i.flatMap((i$1) => i$1.atomicStyleIds))]))];
419
+ return [
420
+ `/* Auto-generated by ${ctx.currentPackageName} */`,
421
+ await ctx.engine.renderPreflights(isDev),
422
+ await ctx.engine.renderAtomicStyles(isDev, { atomicStyleIds })
423
+ ].join("\n").trim();
424
+ },
425
+ getTsCodegenContent: async () => {
426
+ if (ctx.isReady === false || ctx.tsCodegenFilepath == null) return null;
427
+ return await generateTsCodegenContent(ctx);
428
+ },
429
+ writeDevCssFile: (0, perfect_debounce.debounce)(async () => {
430
+ const content = await ctx.getCssContent(true);
431
+ if (content == null) return;
432
+ await (0, node_fs_promises.writeFile)(ctx.devCssFilepath, content);
433
+ }, 300),
434
+ writeTsCodegenFile: (0, perfect_debounce.debounce)(async () => {
435
+ const content = await ctx.getTsCodegenContent();
436
+ if (ctx.tsCodegenFilepath == null || content == null) return;
437
+ await (0, node_fs_promises.writeFile)(ctx.tsCodegenFilepath, content);
438
+ }, 300)
439
+ };
440
+ await ctx.init();
441
+ return ctx;
418
442
  }
419
443
 
444
+ //#endregion
420
445
  exports.createCtx = createCtx;
421
- Object.prototype.hasOwnProperty.call(core, '__proto__') &&
422
- !Object.prototype.hasOwnProperty.call(exports, '__proto__') &&
423
- Object.defineProperty(exports, '__proto__', {
424
- enumerable: true,
425
- value: core['__proto__']
426
- });
427
-
428
- Object.keys(core).forEach(function (k) {
429
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) exports[k] = core[k];
446
+ Object.keys(__pikacss_core).forEach(function (k) {
447
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
448
+ enumerable: true,
449
+ get: function () { return __pikacss_core[k]; }
450
+ });
430
451
  });