@salty-css/core 0.1.0-alpha.26 → 0.1.0-alpha.28
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/README.md +126 -0
- package/{class-name-generator-BIYysuhW.cjs → class-name-generator-DZcz_NT4.cjs} +1 -1
- package/{class-name-generator-B2LriwKm.js → class-name-generator-zQ8zLbPI.js} +1 -1
- package/compiler/resolve-import.d.ts +17 -0
- package/compiler/salty-compiler.cjs +104 -25
- package/compiler/salty-compiler.d.ts +1 -0
- package/compiler/salty-compiler.js +106 -26
- package/config/index.cjs +2 -0
- package/config/index.js +3 -1
- package/css/dynamic-styles.cjs +1 -1
- package/css/dynamic-styles.js +1 -1
- package/css/keyframes.cjs +1 -1
- package/css/keyframes.js +1 -1
- package/factories/define-import.d.ts +14 -0
- package/factories/index.cjs +16 -0
- package/factories/index.d.ts +1 -0
- package/factories/index.js +16 -0
- package/generators/index.cjs +1 -1
- package/generators/index.js +2 -2
- package/instances/classname-instance.cjs +1 -1
- package/instances/classname-instance.js +1 -1
- package/package.json +1 -1
- package/{parse-styles-jPtMfgXH.cjs → parse-styles-BFoV7HiL.cjs} +187 -6
- package/{parse-styles--vHKY6Mw.js → parse-styles-CtA-RKqt.js} +187 -6
- package/parsers/index.cjs +80 -3
- package/parsers/index.js +81 -4
- package/parsers/parse-templates.d.ts +10 -0
- package/parsers/resolve-template-variants.d.ts +21 -0
- package/runtime/index.cjs +1 -1
- package/runtime/index.js +1 -1
- package/types/config-types.d.ts +32 -1
package/README.md
CHANGED
|
@@ -58,6 +58,7 @@ To get help with problems, [Join Salty CSS Discord server](https://discord.gg/R6
|
|
|
58
58
|
- [defineMediaQuery](#media-queries) - create CSS media queries and use them in any styling function
|
|
59
59
|
- [defineTemplates](#templates) - create reusable templates that can be applied when same styles are used over and over again
|
|
60
60
|
- [defineFont](#custom-fonts) - register custom fonts via `@font-face` (or a remote stylesheet) and expose them as a CSS variable
|
|
61
|
+
- [defineImport](#importing-additional-css) - pull in external CSS files (relative, public, node_modules, or URL)
|
|
61
62
|
- [keyframes](#keyframes-animations) - create CSS keyframes animation that can be used and imported in any styling function
|
|
62
63
|
|
|
63
64
|
### Styling helpers & utility
|
|
@@ -320,6 +321,88 @@ Example usage:
|
|
|
320
321
|
styled('div', { base: { textStyle: 'headline.large', card: '20px' } });
|
|
321
322
|
```
|
|
322
323
|
|
|
324
|
+
### Template variants
|
|
325
|
+
|
|
326
|
+
Static templates can opt into named variants by switching a node from a plain styles object to a "rich" shape with `base` and `variants` keys — the same authoring API as `styled`. Variants declared at a parent node are inherited by every descendant leaf, so one declaration of `weight` on `heading` flows down to `heading.large`, `heading.small`, etc.
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
// /styles/templates.css.ts
|
|
330
|
+
import { defineTemplates } from '@salty-css/core/factories';
|
|
331
|
+
|
|
332
|
+
export default defineTemplates({
|
|
333
|
+
textStyle: {
|
|
334
|
+
heading: {
|
|
335
|
+
// Rich node: variants declared here are available to every child leaf.
|
|
336
|
+
base: {
|
|
337
|
+
fontFamily: '{fontFamily.heading}',
|
|
338
|
+
lineHeight: '1.1em',
|
|
339
|
+
},
|
|
340
|
+
variants: {
|
|
341
|
+
weight: {
|
|
342
|
+
light: { fontWeight: 300 },
|
|
343
|
+
regular: { fontWeight: 500 },
|
|
344
|
+
heavy: { fontWeight: 800 },
|
|
345
|
+
},
|
|
346
|
+
italic: {
|
|
347
|
+
true: { fontStyle: 'italic' },
|
|
348
|
+
},
|
|
349
|
+
},
|
|
350
|
+
defaultVariants: {
|
|
351
|
+
weight: 'regular',
|
|
352
|
+
},
|
|
353
|
+
compoundVariants: [
|
|
354
|
+
// Applied when ALL listed axes match.
|
|
355
|
+
{ weight: 'heavy', italic: true, css: { letterSpacing: '-0.01em' } },
|
|
356
|
+
],
|
|
357
|
+
// Leaves can be plain styles…
|
|
358
|
+
small: { fontSize: '{fontSize.heading.small}' },
|
|
359
|
+
regular: { fontSize: '{fontSize.heading.regular}' },
|
|
360
|
+
// …or rich, with their own additional variants / overrides.
|
|
361
|
+
large: {
|
|
362
|
+
base: { fontSize: '{fontSize.heading.large}' },
|
|
363
|
+
variants: {
|
|
364
|
+
weight: {
|
|
365
|
+
// Override the inherited bundle just for `large`.
|
|
366
|
+
heavy: { fontWeight: 900, letterSpacing: '-0.02em' },
|
|
367
|
+
},
|
|
368
|
+
},
|
|
369
|
+
},
|
|
370
|
+
},
|
|
371
|
+
},
|
|
372
|
+
});
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
Apply variants at the call site in either of two equivalent forms — string query or object:
|
|
376
|
+
|
|
377
|
+
```ts
|
|
378
|
+
styled('h1', {
|
|
379
|
+
base: {
|
|
380
|
+
// String form: `path@axis=value&axis=value&boolFlag`
|
|
381
|
+
textStyle: 'heading.large@weight=heavy&italic',
|
|
382
|
+
},
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
styled('h2', {
|
|
386
|
+
base: {
|
|
387
|
+
// Object form: `name` is the dot-path, the rest are axis values.
|
|
388
|
+
textStyle: { name: 'heading.large', weight: 'heavy', italic: true },
|
|
389
|
+
},
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
// No variants — existing simple usage still works.
|
|
393
|
+
styled('p', { base: { textStyle: 'heading.regular' } });
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
Behaviour worth knowing:
|
|
397
|
+
|
|
398
|
+
- **Inheritance is parent → leaf only.** A leaf sees variants from its ancestors; siblings and children are invisible.
|
|
399
|
+
- **Closest wins.** If the same axis/value bundle is declared at multiple levels, the deepest one replaces (not merges) the ancestor's bundle for that single call.
|
|
400
|
+
- **`defaultVariants` apply when the call site omits an axis.** Walked bottom-up, same closest-wins rule.
|
|
401
|
+
- **`compoundVariants` (AND) and `anyOfVariants` (OR) are accumulated top-down** across the path — every matching rule contributes.
|
|
402
|
+
- **Boolean axes accept a shorthand.** `@italic` is equivalent to `@italic=true`; in object form pass `italic: true`.
|
|
403
|
+
- **Reserved keys** inside a rich node: `base`, `variants`, `defaultVariants`, `compoundVariants`, `anyOfVariants`. Don't use `name` as an axis (reserved for the object call-site form).
|
|
404
|
+
- **Function templates** (e.g. `card: (v) => ({ … })`) don't support variants — keep them as plain functions.
|
|
405
|
+
|
|
323
406
|
## Custom fonts
|
|
324
407
|
|
|
325
408
|
Register custom fonts that will be emitted as `@font-face` declarations and exposed as a CSS variable. Mirrors the developer experience of Next.js / Astro font loaders, but generated at build time alongside the rest of your Salty CSS output.
|
|
@@ -402,6 +485,49 @@ export const Body = styled('p', {
|
|
|
402
485
|
});
|
|
403
486
|
```
|
|
404
487
|
|
|
488
|
+
## Importing additional CSS
|
|
489
|
+
|
|
490
|
+
Use `defineImport` to pull in CSS that lives outside of Salty's authoring API — a reset stylesheet from npm, a Google Fonts URL, an asset in your app's `public/` folder, or a sibling `.css` file. The compiler turns each spec into an `@import` rule in the generated `saltygen/index.css`, so the imported stylesheets travel with the rest of your build.
|
|
491
|
+
|
|
492
|
+
```ts
|
|
493
|
+
// /styles/imports.css.ts
|
|
494
|
+
import { defineImport } from '@salty-css/core/factories';
|
|
495
|
+
|
|
496
|
+
export default defineImport(
|
|
497
|
+
// Relative to this file
|
|
498
|
+
'./reset.css',
|
|
499
|
+
// From node_modules (bare specifier — same as Vite / native CSS @import)
|
|
500
|
+
'modern-normalize/modern-normalize.css',
|
|
501
|
+
// From node_modules (~ prefix — same resolver, webpack-style)
|
|
502
|
+
'~normalize.css/normalize.css',
|
|
503
|
+
// From your app's public/ folder (served at the host root)
|
|
504
|
+
'/fonts/inter.css',
|
|
505
|
+
// External URL
|
|
506
|
+
'https://fonts.googleapis.com/css2?family=Inter&display=swap',
|
|
507
|
+
// Object form — attach media or supports() conditions
|
|
508
|
+
{ url: './print.css', media: 'print' },
|
|
509
|
+
{ url: './p3.css', supports: 'color(display-p3 1 1 1)' }
|
|
510
|
+
);
|
|
511
|
+
```
|
|
512
|
+
|
|
513
|
+
Path resolution:
|
|
514
|
+
|
|
515
|
+
| Pattern | Behaviour |
|
|
516
|
+
| --------------------------- | ---------------------------------------------------------------------------------------- |
|
|
517
|
+
| `http://`, `https://`, `//` | Emitted verbatim |
|
|
518
|
+
| Starts with `/` | Public-folder URL — emitted verbatim, the browser resolves it against your host |
|
|
519
|
+
| Starts with `./` or `../` | Resolved at build time relative to the file that called `defineImport` |
|
|
520
|
+
| `~package/file.css` | Stripped of the leading `~`, then resolved from `node_modules` and copied into the build |
|
|
521
|
+
| `package/file.css` (bare) | Same `node_modules` resolution as the `~` form |
|
|
522
|
+
|
|
523
|
+
All imports are placed inside a new `imports` cascade layer that sits **before** `reset`, `global`, `templates`, and your component styles. This means your own styles always win over third-party CSS you pull in — which is what most teams expect when they drop in something like `modern-normalize`.
|
|
524
|
+
|
|
525
|
+
The full layer order in the generated `index.css` is:
|
|
526
|
+
|
|
527
|
+
```css
|
|
528
|
+
@layer imports, reset, global, templates, l0, l1, l2, l3, l4, l5, l6, l7, l8;
|
|
529
|
+
```
|
|
530
|
+
|
|
405
531
|
## Keyframes animations
|
|
406
532
|
|
|
407
533
|
```ts
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
var __defProp = Object.defineProperty;
|
|
3
3
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
4
4
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
5
|
-
const parseStyles = require("./parse-styles-
|
|
5
|
+
const parseStyles = require("./parse-styles-BFoV7HiL.cjs");
|
|
6
6
|
const dashCase = require("./dash-case-DIwKaYgE.cjs");
|
|
7
7
|
const toHash = require("./to-hash-C05Y906F.cjs");
|
|
8
8
|
class StylesGenerator {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var __defProp = Object.defineProperty;
|
|
2
2
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
3
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
|
-
import { p as parseAndJoinStyles } from "./parse-styles
|
|
4
|
+
import { p as parseAndJoinStyles } from "./parse-styles-CtA-RKqt.js";
|
|
5
5
|
import { d as dashCase } from "./dash-case-DblXvymC.js";
|
|
6
6
|
import { t as toHash } from "./to-hash-DAN2LcHK.js";
|
|
7
7
|
class StylesGenerator {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { ImportSpec } from '../factories/define-import';
|
|
2
|
+
export interface ResolveImportOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Override for node_modules resolution. Receives the bare specifier (with any leading `~` already
|
|
5
|
+
* stripped) and the source file path of the salty file that called `defineImport`. Must return the
|
|
6
|
+
* absolute filesystem path of the resolved CSS file. Defaults to `createRequire(sourceFile).resolve`.
|
|
7
|
+
*/
|
|
8
|
+
resolveModule?: (specifier: string, sourceFile: string) => string;
|
|
9
|
+
/**
|
|
10
|
+
* Override for copying resolved node_modules CSS into `<destDir>/imports/`. Receives the absolute
|
|
11
|
+
* source and destination paths. Defaults to `copyFileSync`.
|
|
12
|
+
*/
|
|
13
|
+
copyAsset?: (from: string, to: string) => void;
|
|
14
|
+
}
|
|
15
|
+
export declare const resolveImport: (spec: ImportSpec, sourceFile: string, destDir: string, options?: ResolveImportOptions) => {
|
|
16
|
+
rule: string;
|
|
17
|
+
};
|
|
@@ -13,12 +13,12 @@ const compiler_helpers = require("./helpers.cjs");
|
|
|
13
13
|
const dashCase = require("../dash-case-DIwKaYgE.cjs");
|
|
14
14
|
const toHash = require("../to-hash-C05Y906F.cjs");
|
|
15
15
|
const defineTemplates = require("../define-templates-Deq1aCbN.cjs");
|
|
16
|
-
const
|
|
16
|
+
const module$1 = require("module");
|
|
17
|
+
const parseStyles = require("../parse-styles-BFoV7HiL.cjs");
|
|
17
18
|
const css_merge = require("../css/merge.cjs");
|
|
18
19
|
const parsers_index = require("../parsers/index.cjs");
|
|
19
|
-
const
|
|
20
|
+
const moduleType = require("../util/module-type");
|
|
20
21
|
const console = require("console");
|
|
21
|
-
var _documentCurrentScript = typeof document !== "undefined" ? document.currentScript : null;
|
|
22
22
|
function _interopNamespaceDefault(e) {
|
|
23
23
|
const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
|
|
24
24
|
if (e) {
|
|
@@ -44,19 +44,53 @@ const logger = winston.createLogger({
|
|
|
44
44
|
const logError = (message) => {
|
|
45
45
|
logger.error(message);
|
|
46
46
|
};
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
if (
|
|
50
|
-
return
|
|
47
|
+
const EXTERNAL_URL = /^(?:[a-z][a-z0-9+.-]*:)?\/\//i;
|
|
48
|
+
const normaliseSpec = (spec) => {
|
|
49
|
+
if (typeof spec === "string") return { url: spec };
|
|
50
|
+
return spec;
|
|
51
51
|
};
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
52
|
+
const ensureRelativePrefix = (path2) => {
|
|
53
|
+
if (path2.startsWith(".") || path2.startsWith("/")) return path2;
|
|
54
|
+
return `./${path2}`;
|
|
55
|
+
};
|
|
56
|
+
const toPosix = (path2) => path2.split("\\").join("/");
|
|
57
|
+
const defaultResolveModule = (specifier, sourceFile) => {
|
|
58
|
+
return module$1.createRequire(sourceFile).resolve(specifier);
|
|
59
|
+
};
|
|
60
|
+
const defaultCopyAsset = (from, to) => {
|
|
61
|
+
const dir = path.dirname(to);
|
|
62
|
+
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
63
|
+
fs.copyFileSync(from, to);
|
|
64
|
+
};
|
|
65
|
+
const buildRule = (url, { media, supports }) => {
|
|
66
|
+
let rule = `@import url('${url}')`;
|
|
67
|
+
if (supports) rule += ` supports(${supports})`;
|
|
68
|
+
if (media) rule += ` ${media}`;
|
|
69
|
+
return `${rule};`;
|
|
70
|
+
};
|
|
71
|
+
const resolveImport = (spec, sourceFile, destDir, options = {}) => {
|
|
72
|
+
const opts = normaliseSpec(spec);
|
|
73
|
+
const { url } = opts;
|
|
74
|
+
const resolveModule = options.resolveModule ?? defaultResolveModule;
|
|
75
|
+
const copyAsset = options.copyAsset ?? defaultCopyAsset;
|
|
76
|
+
if (EXTERNAL_URL.test(url)) {
|
|
77
|
+
return { rule: buildRule(url, opts) };
|
|
78
|
+
}
|
|
79
|
+
if (url.startsWith("/")) {
|
|
80
|
+
return { rule: buildRule(url, opts) };
|
|
81
|
+
}
|
|
82
|
+
if (url.startsWith("./") || url.startsWith("../")) {
|
|
83
|
+
const absolute2 = path.resolve(path.dirname(sourceFile), url);
|
|
84
|
+
const fromImportsFile = path.relative(path.join(destDir, "css"), absolute2);
|
|
85
|
+
return { rule: buildRule(ensureRelativePrefix(toPosix(fromImportsFile)), opts) };
|
|
86
|
+
}
|
|
87
|
+
const specifier = url.startsWith("~") ? url.slice(1) : url;
|
|
88
|
+
const absolute = resolveModule(specifier, sourceFile);
|
|
89
|
+
const hash = toHash.toHash(absolute, 6);
|
|
90
|
+
const fileName = `${hash}-${path.basename(absolute)}`;
|
|
91
|
+
const destPath = path.join(destDir, "imports", fileName);
|
|
92
|
+
copyAsset(absolute, destPath);
|
|
93
|
+
return { rule: buildRule(`../imports/${fileName}`, opts) };
|
|
60
94
|
};
|
|
61
95
|
function dotCase(str) {
|
|
62
96
|
if (!str) return "";
|
|
@@ -173,7 +207,7 @@ class SaltyCompiler {
|
|
|
173
207
|
const destDir = await this.getDestDir();
|
|
174
208
|
const coreConfigPath = path.join(this.projectRootDir, (rcProject == null ? void 0 : rcProject.configDir) || "", "salty.config.ts");
|
|
175
209
|
const coreConfigDest = path.join(destDir, "salty.config.js");
|
|
176
|
-
const moduleType = await detectCurrentModuleType(this.projectRootDir);
|
|
210
|
+
const moduleType$1 = await moduleType.detectCurrentModuleType(this.projectRootDir);
|
|
177
211
|
const externalModules = this.getExternalModules(coreConfigPath);
|
|
178
212
|
await esbuild__namespace.build({
|
|
179
213
|
entryPoints: [coreConfigPath],
|
|
@@ -181,7 +215,7 @@ class SaltyCompiler {
|
|
|
181
215
|
treeShaking: true,
|
|
182
216
|
bundle: true,
|
|
183
217
|
outfile: coreConfigDest,
|
|
184
|
-
format: moduleType,
|
|
218
|
+
format: moduleType$1,
|
|
185
219
|
external: externalModules
|
|
186
220
|
});
|
|
187
221
|
const { config } = await this.importFile(coreConfigDest);
|
|
@@ -233,6 +267,7 @@ ${currentFile}`;
|
|
|
233
267
|
fs.mkdirSync(path.join(destDir, "types"));
|
|
234
268
|
fs.mkdirSync(path.join(destDir, "js"));
|
|
235
269
|
fs.mkdirSync(path.join(destDir, "cache"));
|
|
270
|
+
fs.mkdirSync(path.join(destDir, "imports"));
|
|
236
271
|
};
|
|
237
272
|
if (clean) clearDistDir();
|
|
238
273
|
const files = /* @__PURE__ */ new Set();
|
|
@@ -348,7 +383,7 @@ ${currentFile}`;
|
|
|
348
383
|
});
|
|
349
384
|
}
|
|
350
385
|
const otherGlobalCssFiles = globalCssFiles.map((file) => `@import url('./css/${file}');`).join("\n");
|
|
351
|
-
const globalCssFilenames = ["_variables.css", "_reset.css", "_global.css", "_templates.css", "_fonts.css"];
|
|
386
|
+
const globalCssFilenames = ["_imports.css", "_variables.css", "_reset.css", "_global.css", "_templates.css", "_fonts.css"];
|
|
352
387
|
const importsWithData = globalCssFilenames.filter((file) => {
|
|
353
388
|
try {
|
|
354
389
|
const data = fs.readFileSync(path.join(destDir, "css", file), "utf8");
|
|
@@ -357,9 +392,12 @@ ${currentFile}`;
|
|
|
357
392
|
return false;
|
|
358
393
|
}
|
|
359
394
|
});
|
|
360
|
-
const globalImports = importsWithData.map((file) =>
|
|
395
|
+
const globalImports = importsWithData.map((file) => {
|
|
396
|
+
const layerSuffix = file === "_imports.css" ? " layer(imports)" : "";
|
|
397
|
+
return `@import url('./css/${file}')${layerSuffix};`;
|
|
398
|
+
});
|
|
361
399
|
const generatorText = "/*!\n * Generated with Salty CSS (https://salty-css.dev)\n * Do not edit this file directly\n */\n";
|
|
362
|
-
let cssContent = `${generatorText}@layer reset, global, templates, fonts, l0, l1, l2, l3, l4, l5, l6, l7, l8;
|
|
400
|
+
let cssContent = `${generatorText}@layer imports, reset, global, templates, fonts, l0, l1, l2, l3, l4, l5, l6, l7, l8;
|
|
363
401
|
|
|
364
402
|
${globalImports.join(
|
|
365
403
|
"\n"
|
|
@@ -406,6 +444,7 @@ ${css}
|
|
|
406
444
|
globalStyles: [],
|
|
407
445
|
variables: [],
|
|
408
446
|
templates: [],
|
|
447
|
+
imports: [],
|
|
409
448
|
fonts: []
|
|
410
449
|
};
|
|
411
450
|
await Promise.all(
|
|
@@ -416,6 +455,7 @@ ${css}
|
|
|
416
455
|
else if (value.isGlobalDefine) generationResults.globalStyles.push(value);
|
|
417
456
|
else if (value.isDefineVariables) generationResults.variables.push(value);
|
|
418
457
|
else if (value.isDefineTemplates) generationResults.templates.push(value._setPath(`${name};;${outputFilePath}`));
|
|
458
|
+
else if (value.isDefineImport) generationResults.imports.push(value._setPath(src));
|
|
419
459
|
else if (value.isDefineFont) generationResults.fonts.push(value);
|
|
420
460
|
});
|
|
421
461
|
})
|
|
@@ -513,8 +553,25 @@ ${css}
|
|
|
513
553
|
const templates = css_merge.mergeObjects(config.templates, generationResults.templates);
|
|
514
554
|
const templateStylesString = await parsers_index.parseTemplates(templates);
|
|
515
555
|
const templateTokens = parsers_index.getTemplateTypes(templates);
|
|
556
|
+
const templateVariantMaps = parsers_index.getTemplateVariantMaps(templates);
|
|
516
557
|
fs.writeFileSync(templateStylesPath, `@layer templates { ${templateStylesString} }`);
|
|
517
558
|
configCacheContent.templates = templates;
|
|
559
|
+
const importsPath = path.join(destDir, "css/_imports.css");
|
|
560
|
+
const importRules = [];
|
|
561
|
+
for (const factory of generationResults.imports) {
|
|
562
|
+
const sourceFile = factory._path;
|
|
563
|
+
if (!sourceFile) continue;
|
|
564
|
+
for (const spec of factory._current) {
|
|
565
|
+
try {
|
|
566
|
+
const { rule } = resolveImport(spec, sourceFile, destDir);
|
|
567
|
+
importRules.push(rule);
|
|
568
|
+
} catch (e) {
|
|
569
|
+
const url = typeof spec === "string" ? spec : spec.url;
|
|
570
|
+
logger.error(`Failed to resolve defineImport(${JSON.stringify(url)}) from ${sourceFile}: ${e.message}`);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
fs.writeFileSync(importsPath, importRules.join("\n"));
|
|
518
575
|
const configTemplateFactories = config.templates ? [defineTemplates.defineTemplates(config.templates)._setPath(`config;;${configPath}`)] : [];
|
|
519
576
|
const templateFactories = css_merge.mergeFactories(generationResults.templates, configTemplateFactories);
|
|
520
577
|
configCacheContent.templatePaths = Object.fromEntries(Object.entries(templateFactories).map(([key, faktory]) => [key, faktory._path]));
|
|
@@ -536,16 +593,38 @@ ${css}
|
|
|
536
593
|
}
|
|
537
594
|
const tsTokensPath = path.join(destDir, "types/css-tokens.d.ts");
|
|
538
595
|
const tsVariableTokens = [...variableTokens].join("|");
|
|
596
|
+
const pascal = (str) => str.split(/[.\-_]/).filter(Boolean).map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
|
|
597
|
+
const templateVariantMapEntries = Object.entries(templateVariantMaps);
|
|
598
|
+
const hasVariantMaps = templateVariantMapEntries.some(([, pathMap]) => Object.keys(pathMap).length > 0);
|
|
599
|
+
const tsTemplateVariantMap = hasVariantMaps ? `type TemplateVariantTokens = {
|
|
600
|
+
${templateVariantMapEntries.filter(([, pathMap]) => Object.keys(pathMap).length > 0).map(([templateKey, pathMap]) => {
|
|
601
|
+
const pathEntries = Object.entries(pathMap).map(
|
|
602
|
+
([dotPath, axes]) => `'${dotPath}': { ${Object.entries(axes).map(([axis, valueType]) => `${axis}?: ${valueType}`).join("; ")} }`
|
|
603
|
+
).join(";\n ");
|
|
604
|
+
return `${templateKey}: {
|
|
605
|
+
${pathEntries}
|
|
606
|
+
}`;
|
|
607
|
+
}).join(";\n ")}
|
|
608
|
+
}` : `type TemplateVariantTokens = Record<string, Record<string, Record<string, never>>>;`;
|
|
609
|
+
const tsTemplateVariantAliases = templateVariantMapEntries.flatMap(
|
|
610
|
+
([templateKey, pathMap]) => Object.keys(pathMap).map(
|
|
611
|
+
(dotPath) => `type ${pascal(templateKey)}${pascal(dotPath)}Variants = TemplateVariantTokens['${templateKey}']['${dotPath}'];`
|
|
612
|
+
)
|
|
613
|
+
).join("\n ");
|
|
539
614
|
const tsTokensTypes = `
|
|
540
615
|
// Variable types
|
|
541
|
-
type VariableTokens = ${tsVariableTokens || `''`};
|
|
616
|
+
type VariableTokens = ${tsVariableTokens || `''`};
|
|
542
617
|
type PropertyValueToken = \`{\${VariableTokens}}\`;
|
|
543
|
-
|
|
618
|
+
|
|
544
619
|
// Template types
|
|
545
620
|
type TemplateTokens = {
|
|
546
621
|
${Object.entries(templateTokens).map(([key, value]) => `${key}?: ${value}`).join("\n")}
|
|
547
622
|
}
|
|
548
|
-
|
|
623
|
+
|
|
624
|
+
// Template variant types (per docs/template-variants-spec.md §7)
|
|
625
|
+
${tsTemplateVariantMap}
|
|
626
|
+
${tsTemplateVariantAliases}
|
|
627
|
+
|
|
549
628
|
// Media query types
|
|
550
629
|
type MediaQueryKeys = ${mediaQueryKeys || `''`};
|
|
551
630
|
`;
|
|
@@ -569,7 +648,7 @@ ${css}
|
|
|
569
648
|
const rcProject = await this.getRCProjectConfig(this.projectRootDir);
|
|
570
649
|
const coreConfigPath = path.join(this.projectRootDir, (rcProject == null ? void 0 : rcProject.configDir) || "", "salty.config.ts");
|
|
571
650
|
const externalModules = this.getExternalModules(coreConfigPath);
|
|
572
|
-
const moduleType = await detectCurrentModuleType(this.projectRootDir);
|
|
651
|
+
const moduleType$1 = await moduleType.detectCurrentModuleType(this.projectRootDir);
|
|
573
652
|
await esbuild__namespace.build({
|
|
574
653
|
stdin: {
|
|
575
654
|
contents: currentFile,
|
|
@@ -581,7 +660,7 @@ ${css}
|
|
|
581
660
|
treeShaking: true,
|
|
582
661
|
bundle: true,
|
|
583
662
|
outfile: outputFilePath,
|
|
584
|
-
format: moduleType,
|
|
663
|
+
format: moduleType$1,
|
|
585
664
|
target: ["node20"],
|
|
586
665
|
keepNames: true,
|
|
587
666
|
external: externalModules,
|
|
@@ -2,19 +2,20 @@ var __defProp = Object.defineProperty;
|
|
|
2
2
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
3
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
4
|
import * as esbuild from "esbuild";
|
|
5
|
-
import { join, parse } from "path";
|
|
5
|
+
import { resolve, dirname, relative, join, basename, parse } from "path";
|
|
6
6
|
import { createLogger, transports, format } from "winston";
|
|
7
7
|
import { readFile } from "fs/promises";
|
|
8
|
-
import {
|
|
8
|
+
import { existsSync, mkdirSync, copyFileSync, readFileSync, statSync, readdirSync, writeFileSync } from "fs";
|
|
9
9
|
import { execSync } from "child_process";
|
|
10
10
|
import { isSaltyFile, resolveExportValue, getCorePackageRoot, saltyFileExtensions } from "./helpers.js";
|
|
11
11
|
import { d as dashCase } from "../dash-case-DblXvymC.js";
|
|
12
12
|
import { t as toHash } from "../to-hash-DAN2LcHK.js";
|
|
13
13
|
import { d as defineTemplates } from "../define-templates-CVhhgPnd.js";
|
|
14
|
-
import {
|
|
14
|
+
import { createRequire } from "module";
|
|
15
|
+
import { p as parseAndJoinStyles, b as parseVariableTokens } from "../parse-styles-CtA-RKqt.js";
|
|
15
16
|
import { mergeObjects, mergeFactories } from "../css/merge.js";
|
|
16
|
-
import { parseTemplates, getTemplateTypes } from "../parsers/index.js";
|
|
17
|
-
import {
|
|
17
|
+
import { parseTemplates, getTemplateTypes, getTemplateVariantMaps } from "../parsers/index.js";
|
|
18
|
+
import { detectCurrentModuleType } from "../util/module-type";
|
|
18
19
|
import console from "console";
|
|
19
20
|
const logger = createLogger({
|
|
20
21
|
level: "debug",
|
|
@@ -24,19 +25,53 @@ const logger = createLogger({
|
|
|
24
25
|
const logError = (message) => {
|
|
25
26
|
logger.error(message);
|
|
26
27
|
};
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
if (
|
|
30
|
-
return
|
|
28
|
+
const EXTERNAL_URL = /^(?:[a-z][a-z0-9+.-]*:)?\/\//i;
|
|
29
|
+
const normaliseSpec = (spec) => {
|
|
30
|
+
if (typeof spec === "string") return { url: spec };
|
|
31
|
+
return spec;
|
|
31
32
|
};
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
33
|
+
const ensureRelativePrefix = (path) => {
|
|
34
|
+
if (path.startsWith(".") || path.startsWith("/")) return path;
|
|
35
|
+
return `./${path}`;
|
|
36
|
+
};
|
|
37
|
+
const toPosix = (path) => path.split("\\").join("/");
|
|
38
|
+
const defaultResolveModule = (specifier, sourceFile) => {
|
|
39
|
+
return createRequire(sourceFile).resolve(specifier);
|
|
40
|
+
};
|
|
41
|
+
const defaultCopyAsset = (from, to) => {
|
|
42
|
+
const dir = dirname(to);
|
|
43
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
44
|
+
copyFileSync(from, to);
|
|
45
|
+
};
|
|
46
|
+
const buildRule = (url, { media, supports }) => {
|
|
47
|
+
let rule = `@import url('${url}')`;
|
|
48
|
+
if (supports) rule += ` supports(${supports})`;
|
|
49
|
+
if (media) rule += ` ${media}`;
|
|
50
|
+
return `${rule};`;
|
|
51
|
+
};
|
|
52
|
+
const resolveImport = (spec, sourceFile, destDir, options = {}) => {
|
|
53
|
+
const opts = normaliseSpec(spec);
|
|
54
|
+
const { url } = opts;
|
|
55
|
+
const resolveModule = options.resolveModule ?? defaultResolveModule;
|
|
56
|
+
const copyAsset = options.copyAsset ?? defaultCopyAsset;
|
|
57
|
+
if (EXTERNAL_URL.test(url)) {
|
|
58
|
+
return { rule: buildRule(url, opts) };
|
|
59
|
+
}
|
|
60
|
+
if (url.startsWith("/")) {
|
|
61
|
+
return { rule: buildRule(url, opts) };
|
|
62
|
+
}
|
|
63
|
+
if (url.startsWith("./") || url.startsWith("../")) {
|
|
64
|
+
const absolute2 = resolve(dirname(sourceFile), url);
|
|
65
|
+
const fromImportsFile = relative(join(destDir, "css"), absolute2);
|
|
66
|
+
return { rule: buildRule(ensureRelativePrefix(toPosix(fromImportsFile)), opts) };
|
|
67
|
+
}
|
|
68
|
+
const specifier = url.startsWith("~") ? url.slice(1) : url;
|
|
69
|
+
const absolute = resolveModule(specifier, sourceFile);
|
|
70
|
+
const hash = toHash(absolute, 6);
|
|
71
|
+
const fileName = `${hash}-${basename(absolute)}`;
|
|
72
|
+
const destPath = join(destDir, "imports", fileName);
|
|
73
|
+
copyAsset(absolute, destPath);
|
|
74
|
+
return { rule: buildRule(`../imports/${fileName}`, opts) };
|
|
40
75
|
};
|
|
41
76
|
function dotCase(str) {
|
|
42
77
|
if (!str) return "";
|
|
@@ -121,10 +156,10 @@ class SaltyCompiler {
|
|
|
121
156
|
* Get the project configuration from the .saltyrc.json file based on the current directory.
|
|
122
157
|
* If no specific project configuration is found, it falls back to the default project.
|
|
123
158
|
*/
|
|
124
|
-
__publicField(this, "getRCProjectConfig", async (
|
|
159
|
+
__publicField(this, "getRCProjectConfig", async (dirname2) => {
|
|
125
160
|
var _a, _b;
|
|
126
|
-
const rcFile = await this.readRCFile(
|
|
127
|
-
const projectConfig = (_a = rcFile.projects) == null ? void 0 : _a.find((project) =>
|
|
161
|
+
const rcFile = await this.readRCFile(dirname2);
|
|
162
|
+
const projectConfig = (_a = rcFile.projects) == null ? void 0 : _a.find((project) => dirname2.endsWith(project.dir || ""));
|
|
128
163
|
if (!projectConfig) return (_b = rcFile.projects) == null ? void 0 : _b.find((project) => project.dir === rcFile.defaultProject);
|
|
129
164
|
return projectConfig;
|
|
130
165
|
});
|
|
@@ -213,6 +248,7 @@ ${currentFile}`;
|
|
|
213
248
|
mkdirSync(join(destDir, "types"));
|
|
214
249
|
mkdirSync(join(destDir, "js"));
|
|
215
250
|
mkdirSync(join(destDir, "cache"));
|
|
251
|
+
mkdirSync(join(destDir, "imports"));
|
|
216
252
|
};
|
|
217
253
|
if (clean) clearDistDir();
|
|
218
254
|
const files = /* @__PURE__ */ new Set();
|
|
@@ -328,7 +364,7 @@ ${currentFile}`;
|
|
|
328
364
|
});
|
|
329
365
|
}
|
|
330
366
|
const otherGlobalCssFiles = globalCssFiles.map((file) => `@import url('./css/${file}');`).join("\n");
|
|
331
|
-
const globalCssFilenames = ["_variables.css", "_reset.css", "_global.css", "_templates.css", "_fonts.css"];
|
|
367
|
+
const globalCssFilenames = ["_imports.css", "_variables.css", "_reset.css", "_global.css", "_templates.css", "_fonts.css"];
|
|
332
368
|
const importsWithData = globalCssFilenames.filter((file) => {
|
|
333
369
|
try {
|
|
334
370
|
const data = readFileSync(join(destDir, "css", file), "utf8");
|
|
@@ -337,9 +373,12 @@ ${currentFile}`;
|
|
|
337
373
|
return false;
|
|
338
374
|
}
|
|
339
375
|
});
|
|
340
|
-
const globalImports = importsWithData.map((file) =>
|
|
376
|
+
const globalImports = importsWithData.map((file) => {
|
|
377
|
+
const layerSuffix = file === "_imports.css" ? " layer(imports)" : "";
|
|
378
|
+
return `@import url('./css/${file}')${layerSuffix};`;
|
|
379
|
+
});
|
|
341
380
|
const generatorText = "/*!\n * Generated with Salty CSS (https://salty-css.dev)\n * Do not edit this file directly\n */\n";
|
|
342
|
-
let cssContent = `${generatorText}@layer reset, global, templates, fonts, l0, l1, l2, l3, l4, l5, l6, l7, l8;
|
|
381
|
+
let cssContent = `${generatorText}@layer imports, reset, global, templates, fonts, l0, l1, l2, l3, l4, l5, l6, l7, l8;
|
|
343
382
|
|
|
344
383
|
${globalImports.join(
|
|
345
384
|
"\n"
|
|
@@ -386,6 +425,7 @@ ${css}
|
|
|
386
425
|
globalStyles: [],
|
|
387
426
|
variables: [],
|
|
388
427
|
templates: [],
|
|
428
|
+
imports: [],
|
|
389
429
|
fonts: []
|
|
390
430
|
};
|
|
391
431
|
await Promise.all(
|
|
@@ -396,6 +436,7 @@ ${css}
|
|
|
396
436
|
else if (value.isGlobalDefine) generationResults.globalStyles.push(value);
|
|
397
437
|
else if (value.isDefineVariables) generationResults.variables.push(value);
|
|
398
438
|
else if (value.isDefineTemplates) generationResults.templates.push(value._setPath(`${name};;${outputFilePath}`));
|
|
439
|
+
else if (value.isDefineImport) generationResults.imports.push(value._setPath(src));
|
|
399
440
|
else if (value.isDefineFont) generationResults.fonts.push(value);
|
|
400
441
|
});
|
|
401
442
|
})
|
|
@@ -493,8 +534,25 @@ ${css}
|
|
|
493
534
|
const templates = mergeObjects(config.templates, generationResults.templates);
|
|
494
535
|
const templateStylesString = await parseTemplates(templates);
|
|
495
536
|
const templateTokens = getTemplateTypes(templates);
|
|
537
|
+
const templateVariantMaps = getTemplateVariantMaps(templates);
|
|
496
538
|
writeFileSync(templateStylesPath, `@layer templates { ${templateStylesString} }`);
|
|
497
539
|
configCacheContent.templates = templates;
|
|
540
|
+
const importsPath = join(destDir, "css/_imports.css");
|
|
541
|
+
const importRules = [];
|
|
542
|
+
for (const factory of generationResults.imports) {
|
|
543
|
+
const sourceFile = factory._path;
|
|
544
|
+
if (!sourceFile) continue;
|
|
545
|
+
for (const spec of factory._current) {
|
|
546
|
+
try {
|
|
547
|
+
const { rule } = resolveImport(spec, sourceFile, destDir);
|
|
548
|
+
importRules.push(rule);
|
|
549
|
+
} catch (e) {
|
|
550
|
+
const url = typeof spec === "string" ? spec : spec.url;
|
|
551
|
+
logger.error(`Failed to resolve defineImport(${JSON.stringify(url)}) from ${sourceFile}: ${e.message}`);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
writeFileSync(importsPath, importRules.join("\n"));
|
|
498
556
|
const configTemplateFactories = config.templates ? [defineTemplates(config.templates)._setPath(`config;;${configPath}`)] : [];
|
|
499
557
|
const templateFactories = mergeFactories(generationResults.templates, configTemplateFactories);
|
|
500
558
|
configCacheContent.templatePaths = Object.fromEntries(Object.entries(templateFactories).map(([key, faktory]) => [key, faktory._path]));
|
|
@@ -516,16 +574,38 @@ ${css}
|
|
|
516
574
|
}
|
|
517
575
|
const tsTokensPath = join(destDir, "types/css-tokens.d.ts");
|
|
518
576
|
const tsVariableTokens = [...variableTokens].join("|");
|
|
577
|
+
const pascal = (str) => str.split(/[.\-_]/).filter(Boolean).map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
|
|
578
|
+
const templateVariantMapEntries = Object.entries(templateVariantMaps);
|
|
579
|
+
const hasVariantMaps = templateVariantMapEntries.some(([, pathMap]) => Object.keys(pathMap).length > 0);
|
|
580
|
+
const tsTemplateVariantMap = hasVariantMaps ? `type TemplateVariantTokens = {
|
|
581
|
+
${templateVariantMapEntries.filter(([, pathMap]) => Object.keys(pathMap).length > 0).map(([templateKey, pathMap]) => {
|
|
582
|
+
const pathEntries = Object.entries(pathMap).map(
|
|
583
|
+
([dotPath, axes]) => `'${dotPath}': { ${Object.entries(axes).map(([axis, valueType]) => `${axis}?: ${valueType}`).join("; ")} }`
|
|
584
|
+
).join(";\n ");
|
|
585
|
+
return `${templateKey}: {
|
|
586
|
+
${pathEntries}
|
|
587
|
+
}`;
|
|
588
|
+
}).join(";\n ")}
|
|
589
|
+
}` : `type TemplateVariantTokens = Record<string, Record<string, Record<string, never>>>;`;
|
|
590
|
+
const tsTemplateVariantAliases = templateVariantMapEntries.flatMap(
|
|
591
|
+
([templateKey, pathMap]) => Object.keys(pathMap).map(
|
|
592
|
+
(dotPath) => `type ${pascal(templateKey)}${pascal(dotPath)}Variants = TemplateVariantTokens['${templateKey}']['${dotPath}'];`
|
|
593
|
+
)
|
|
594
|
+
).join("\n ");
|
|
519
595
|
const tsTokensTypes = `
|
|
520
596
|
// Variable types
|
|
521
|
-
type VariableTokens = ${tsVariableTokens || `''`};
|
|
597
|
+
type VariableTokens = ${tsVariableTokens || `''`};
|
|
522
598
|
type PropertyValueToken = \`{\${VariableTokens}}\`;
|
|
523
|
-
|
|
599
|
+
|
|
524
600
|
// Template types
|
|
525
601
|
type TemplateTokens = {
|
|
526
602
|
${Object.entries(templateTokens).map(([key, value]) => `${key}?: ${value}`).join("\n")}
|
|
527
603
|
}
|
|
528
|
-
|
|
604
|
+
|
|
605
|
+
// Template variant types (per docs/template-variants-spec.md §7)
|
|
606
|
+
${tsTemplateVariantMap}
|
|
607
|
+
${tsTemplateVariantAliases}
|
|
608
|
+
|
|
529
609
|
// Media query types
|
|
530
610
|
type MediaQueryKeys = ${mediaQueryKeys || `''`};
|
|
531
611
|
`;
|
package/config/index.cjs
CHANGED
|
@@ -7,9 +7,11 @@ const defineConfig = (config) => {
|
|
|
7
7
|
};
|
|
8
8
|
exports.FontFactory = factories_index.FontFactory;
|
|
9
9
|
exports.GlobalStylesFactory = factories_index.GlobalStylesFactory;
|
|
10
|
+
exports.ImportFactory = factories_index.ImportFactory;
|
|
10
11
|
exports.VariablesFactory = factories_index.VariablesFactory;
|
|
11
12
|
exports.defineFont = factories_index.defineFont;
|
|
12
13
|
exports.defineGlobalStyles = factories_index.defineGlobalStyles;
|
|
14
|
+
exports.defineImport = factories_index.defineImport;
|
|
13
15
|
exports.defineMediaQuery = factories_index.defineMediaQuery;
|
|
14
16
|
exports.defineVariables = factories_index.defineVariables;
|
|
15
17
|
exports.TemplateFactory = defineTemplates.TemplateFactory;
|