@js-template-engine/extension-sass 0.0.0-stage → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Björn Djurnamn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,157 @@
1
- # Temporary Holding Version
1
+ # @js-template-engine/extension-sass
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [Sass](https://sass-lang.com) extension for the
4
+ [JS Template Engine](https://github.com/djurnamn/js-template-engine). It
5
+ writes a component's stylesheet as SCSS, resolves the Sass source in a
6
+ template to plain CSS for every other stylesheet language, and gives
7
+ `@include` style keys their meaning.
8
+
9
+ ## Installation
10
+
11
+ ```sh
12
+ pnpm add @js-template-engine/extension-sass
13
+ ```
14
+
15
+ The package brings Dart Sass (`sass`), which it compiles with when it
16
+ resolves Sass source to CSS.
17
+
18
+ ## Usage
19
+
20
+ Pass the extension to write SCSS:
21
+
22
+ ```ts
23
+ import { process } from '@js-template-engine/core';
24
+ import { react } from '@js-template-engine/extension-react';
25
+ import { sass } from '@js-template-engine/extension-sass';
26
+
27
+ const result = process(template, {
28
+ extensions: [react(), sass({ loadPaths: ['styles'] })],
29
+ styling: { placement: 'separate-file' },
30
+ });
31
+ // result.files: Button.tsx, Button.scss
32
+ ```
33
+
34
+ Passing it selects the `scss` language: each stylesheet is written as nested
35
+ SCSS blocks in a `.scss` file, for your own Sass build to compile.
36
+
37
+ Pass it with `output: false` beside another language. The build writes that
38
+ language, and the extension resolves the Sass source of the template to
39
+ plain CSS first:
40
+
41
+ ```ts
42
+ process(template, {
43
+ extensions: [react(), sass({ loadPaths: ['styles'], output: false })],
44
+ });
45
+ // result.files: Button.tsx, its styles resolved to CSS
46
+ ```
47
+
48
+ ## Options
49
+
50
+ | Option | |
51
+ |---|---|
52
+ | `loadPaths` | Directories `@use`, `@forward`, `@import` and `@include` resolve against, as in Sass's own load-path model. |
53
+ | `importers` | Dart Sass importer objects tried beside the load paths, such as one that resolves a package's `pkg:` URLs. |
54
+ | `output` | `true` (default) writes SCSS. `false` leaves the language to the build and resolves Sass source to CSS for it. |
55
+
56
+ ## What a template can hold
57
+
58
+ - **`@include` keys.** A style key that starts with `@include` is a mixin
59
+ include. `'@include focus-ring': true` is `@include focus-ring;`, and an
60
+ object value is the include's content block. An include is written where
61
+ it stands among the declarations of its rule, so a declaration after it
62
+ overrides it.
63
+ - **A preamble.** The component's `extensions.sass.preamble` is its Sass at
64
+ file scope: `@use` lines, variables and mixins. The component's `style`
65
+ string is written at file scope too, after the preamble.
66
+ - **Sass in values and selectors.** `$variables`, functions and `#{...}`
67
+ interpolation.
68
+
69
+ ```ts
70
+ const template = {
71
+ type: 'component',
72
+ name: 'Button',
73
+ extensions: { sass: { preamble: "@use 'mixins' as *;" } },
74
+ children: [
75
+ {
76
+ type: 'element',
77
+ tag: 'button',
78
+ attributes: {
79
+ class: 'button',
80
+ style: {
81
+ '@include focus-ring': true,
82
+ padding: '$button-padding',
83
+ ':hover': { '@include elevation(2)': true },
84
+ },
85
+ },
86
+ },
87
+ ],
88
+ };
89
+ ```
90
+
91
+ ## SCSS output
92
+
93
+ ```scss
94
+ @use 'mixins' as *;
95
+
96
+ .button {
97
+ @include focus-ring;
98
+ padding: $button-padding;
99
+
100
+ &:hover {
101
+ @include elevation(2);
102
+ }
103
+ }
104
+ ```
105
+
106
+ A pseudo-selector key nests as `&:hover`, a parent selector (`.ancestor &`)
107
+ and an at-rule (`@media`) nest as written, and a modifier of the node's own
108
+ class is written `&--large`. Includes, the preamble and Sass values are
109
+ written as they stand.
110
+
111
+ SCSS needs a compile step. Vue and Svelte compile a `<style lang="scss">`
112
+ block, so they take it under every placement. React and the html output
113
+ take it with the `separate-file` placement.
114
+
115
+ ### The cascade layer order
116
+
117
+ Sass allows nothing ahead of a stylesheet's `@use` lines and writes each
118
+ loaded module's CSS ahead of the stylesheet's own. Under `styling.layer`
119
+ with an `order`, each stylesheet therefore loads a generated module first,
120
+ `_layer-order.scss`, which holds the `@layer` order statement, so the
121
+ statement is first in the compiled CSS. The module is written beside the
122
+ stylesheets that load it. `SASS_LAYER_ORDER_FILE` is its file name.
123
+
124
+ ## Resolving to CSS
125
+
126
+ Under any language other than SCSS, and under the `inline` placement, the
127
+ extension compiles each style with Dart Sass and hands the build plain CSS:
128
+ mixins expanded, functions and variables evaluated, the preamble's own rules
129
+ (`@keyframes`) kept as the component's style. Nothing is compiled for a
130
+ component with no include, no load paths and no `pkg:` load.
131
+
132
+ A mixin, a variable or a function does not come back out as one: what a
133
+ language other than SCSS receives is the CSS they resolve to.
134
+
135
+ A selector that still holds `#{...}` in a build no Sass compile reads is
136
+ written as it stands and matches nothing, and the build warns about it.
137
+
138
+ ## Compiling a Sass source
139
+
140
+ `sassSourceCompilers(options?)` returns the compilers of Sass's two
141
+ syntaxes, `{ scss, sass }`, each a function from
142
+ `{ text, language, filePath?, loadPaths }` to CSS. It is what a reader of
143
+ stylesheet sources takes to read `.scss` and `.sass` files, such as
144
+ `compileStylesheetSource` of `@js-template-engine/stylesheet-loader`, which
145
+ accepts them in its `compilers` option. `options.importers` lists Dart Sass
146
+ importers tried beside the load paths.
147
+
148
+ ## Without the extension
149
+
150
+ `@js-template-engine/core` takes `styling.language: 'scss'`,
151
+ `styling.loadPaths` and `styling.sassImporters` with no extension passed,
152
+ and resolves `@include` keys the same way, by handing them to this package.
153
+ Passing `sass()` is the same thing said in `extensions`.
154
+
155
+ ## License
156
+
157
+ MIT
@@ -0,0 +1,35 @@
1
+ /** A Sass source to compile to CSS. */
2
+ export interface SassSource {
3
+ /** The source text. */
4
+ text: string;
5
+ /** `'sass'` for the indented syntax; anything else is SCSS. */
6
+ language: string;
7
+ /** The source file's absolute path, when the source is a file. */
8
+ filePath?: string;
9
+ /** The absolute directories `@use`, `@forward` and `@import` resolve against. */
10
+ loadPaths: string[];
11
+ }
12
+ /** What {@link sassSourceCompilers} reads. */
13
+ export interface SassSourceCompilerOptions {
14
+ /**
15
+ * Sass importers tried beside the load paths, such as one that resolves a
16
+ * package's own `pkg:` URLs. Each is a Dart Sass importer object.
17
+ */
18
+ importers?: readonly unknown[];
19
+ }
20
+ /**
21
+ * The compilers of Sass's two syntaxes, SCSS and the indented one, each
22
+ * under its language's name and file extension: what a reader of
23
+ * stylesheet sources takes to read `.scss` and `.sass` files.
24
+ *
25
+ * @param options - The importers tried beside the load paths.
26
+ * @returns The compilers, `{ scss, sass }`, each returning CSS.
27
+ *
28
+ * @example
29
+ * sassSourceCompilers().scss({
30
+ * text: '.card { &:hover { color: red; } }',
31
+ * language: 'scss',
32
+ * loadPaths: [],
33
+ * }); // '.card:hover {\n color: red;\n}'
34
+ */
35
+ export declare function sassSourceCompilers(options?: SassSourceCompilerOptions): Record<"scss" | "sass", (source: SassSource) => string>;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sassSourceCompilers = sassSourceCompilers;
4
+ /**
5
+ * The compilers of Sass's two syntaxes, SCSS and the indented one, each
6
+ * under its language's name and file extension: what a reader of
7
+ * stylesheet sources takes to read `.scss` and `.sass` files.
8
+ *
9
+ * @param options - The importers tried beside the load paths.
10
+ * @returns The compilers, `{ scss, sass }`, each returning CSS.
11
+ *
12
+ * @example
13
+ * sassSourceCompilers().scss({
14
+ * text: '.card { &:hover { color: red; } }',
15
+ * language: 'scss',
16
+ * loadPaths: [],
17
+ * }); // '.card:hover {\n color: red;\n}'
18
+ */
19
+ function sassSourceCompilers(options = {}) {
20
+ const compile = (source) => {
21
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
22
+ const compiler = require("sass");
23
+ return compiler.compileString(source.text, {
24
+ syntax: source.language === "sass" ? "indented" : "scss",
25
+ loadPaths: source.loadPaths,
26
+ ...(options.importers === undefined
27
+ ? {}
28
+ : {
29
+ importers: options.importers,
30
+ }),
31
+ style: "expanded",
32
+ ...(source.filePath === undefined
33
+ ? {}
34
+ : { url: new URL(`file://${encodeURI(source.filePath)}`) }),
35
+ }).css;
36
+ };
37
+ return { scss: compile, sass: compile };
38
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Sass extension for the JS Template Engine.
3
+ *
4
+ * Writes a component's stylesheet as SCSS, resolves Sass source to CSS for
5
+ * a build that writes another language, and gives `@include` style keys
6
+ * their meaning:
7
+ * `process(template, { extensions: [react(), sass({ loadPaths })] })`.
8
+ */
9
+ export { sass, SASS_LAYER_ORDER_FILE, type SassExtension, type SassOptions, type SassSourceExtension, } from "./sass-extension";
10
+ export { SCSS_DIALECT, SCSS_SOURCE_SYNTAX, scssWriter } from "./scss-writer";
11
+ export { sassSourceCompilers, type SassSource, type SassSourceCompilerOptions, } from "./compile-source";
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sassSourceCompilers = exports.scssWriter = exports.SCSS_SOURCE_SYNTAX = exports.SCSS_DIALECT = exports.SASS_LAYER_ORDER_FILE = exports.sass = void 0;
4
+ /**
5
+ * Sass extension for the JS Template Engine.
6
+ *
7
+ * Writes a component's stylesheet as SCSS, resolves Sass source to CSS for
8
+ * a build that writes another language, and gives `@include` style keys
9
+ * their meaning:
10
+ * `process(template, { extensions: [react(), sass({ loadPaths })] })`.
11
+ */
12
+ var sass_extension_1 = require("./sass-extension");
13
+ Object.defineProperty(exports, "sass", { enumerable: true, get: function () { return sass_extension_1.sass; } });
14
+ Object.defineProperty(exports, "SASS_LAYER_ORDER_FILE", { enumerable: true, get: function () { return sass_extension_1.SASS_LAYER_ORDER_FILE; } });
15
+ var scss_writer_1 = require("./scss-writer");
16
+ Object.defineProperty(exports, "SCSS_DIALECT", { enumerable: true, get: function () { return scss_writer_1.SCSS_DIALECT; } });
17
+ Object.defineProperty(exports, "SCSS_SOURCE_SYNTAX", { enumerable: true, get: function () { return scss_writer_1.SCSS_SOURCE_SYNTAX; } });
18
+ Object.defineProperty(exports, "scssWriter", { enumerable: true, get: function () { return scss_writer_1.scssWriter; } });
19
+ var compile_source_1 = require("./compile-source");
20
+ Object.defineProperty(exports, "sassSourceCompilers", { enumerable: true, get: function () { return compile_source_1.sassSourceCompilers; } });
@@ -0,0 +1,35 @@
1
+ import type { ClaimedStyles, ResolvedStyles, StylesheetTools } from "@js-template-engine/types";
2
+ /** What every compile of a component's Sass resolves loads against. */
3
+ export interface SassCompiler {
4
+ /** The stylesheet language the resolved styles are written in. */
5
+ language: string;
6
+ /** The directories loads resolve against. */
7
+ loadPaths: readonly string[];
8
+ /** The importers tried beside the load paths. */
9
+ importers: readonly unknown[];
10
+ }
11
+ /**
12
+ * Resolves the Sass source in a component's styles to flat CSS, for a build
13
+ * that writes a language other than SCSS or places its styles inline:
14
+ * mixins, functions and `$variables` expanded against the load paths by
15
+ * Dart Sass. Each style comes back as an ordinary nested-`&` style object.
16
+ *
17
+ * Nothing is resolved when nothing asks for it: no load paths are
18
+ * configured, no style holds an include, and the preamble loads no `pkg:`
19
+ * URL.
20
+ *
21
+ * @param styles - The component's styles.
22
+ * @param options - The load paths and importers.
23
+ * @param tools - The engine's serializers.
24
+ * @returns The styles as CSS, or `undefined` when nothing is resolved.
25
+ * @throws The engine's error when Sass fails to compile a style.
26
+ *
27
+ * @example
28
+ * resolveSassStyles(
29
+ * { language: 'css', componentStyle: "@use 'mixins' as *;", overrides: {}, styles: [{ '@include focus-ring': true }] },
30
+ * { loadPaths: ['styles'], importers: [] },
31
+ * tools
32
+ * );
33
+ * // { componentStyle: undefined, styles: [{ outline: '2px solid' }] }
34
+ */
35
+ export declare function resolveSassStyles(styles: ClaimedStyles, options: Pick<SassCompiler, "loadPaths" | "importers">, tools: StylesheetTools): ResolvedStyles | undefined;
@@ -0,0 +1,315 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveSassStyles = resolveSassStyles;
4
+ const scss_writer_1 = require("./scss-writer");
5
+ /**
6
+ * The placeholder root each style is compiled under. Sass expands `&` (and
7
+ * `#{&}` interpolations) against it; the compiled selectors are then
8
+ * re-relativized back to `&` so the result is selector-agnostic and is a
9
+ * nested-`&` style object again. A class selector survives interpolation
10
+ * cleanly (`#{&}--soft` becomes `....--soft`) and cannot occur in real
11
+ * authored CSS.
12
+ */
13
+ const PLACEHOLDER = ".JTE_SASS_ROOT_PLACEHOLDER";
14
+ /** A `@use`, `@forward` or `@import` of a `pkg:` URL in a preamble. */
15
+ const PACKAGE_URL_LOAD = /@(?:use|forward|import)\s+["']pkg:/;
16
+ /**
17
+ * Resolves the Sass source in a component's styles to flat CSS, for a build
18
+ * that writes a language other than SCSS or places its styles inline:
19
+ * mixins, functions and `$variables` expanded against the load paths by
20
+ * Dart Sass. Each style comes back as an ordinary nested-`&` style object.
21
+ *
22
+ * Nothing is resolved when nothing asks for it: no load paths are
23
+ * configured, no style holds an include, and the preamble loads no `pkg:`
24
+ * URL.
25
+ *
26
+ * @param styles - The component's styles.
27
+ * @param options - The load paths and importers.
28
+ * @param tools - The engine's serializers.
29
+ * @returns The styles as CSS, or `undefined` when nothing is resolved.
30
+ * @throws The engine's error when Sass fails to compile a style.
31
+ *
32
+ * @example
33
+ * resolveSassStyles(
34
+ * { language: 'css', componentStyle: "@use 'mixins' as *;", overrides: {}, styles: [{ '@include focus-ring': true }] },
35
+ * { loadPaths: ['styles'], importers: [] },
36
+ * tools
37
+ * );
38
+ * // { componentStyle: undefined, styles: [{ outline: '2px solid' }] }
39
+ */
40
+ function resolveSassStyles(styles, options, tools) {
41
+ const preamble = (0, scss_writer_1.sassPreamble)(styles.overrides, styles.componentStyle);
42
+ if (options.loadPaths.length === 0 &&
43
+ !styles.styles.some(objectHasInclude) &&
44
+ !PACKAGE_URL_LOAD.test(preamble)) {
45
+ return undefined;
46
+ }
47
+ const compiler = { ...options, language: styles.language };
48
+ return {
49
+ styles: styles.styles.map((style) => resolveStyleObject(style, preamble, compiler, tools)),
50
+ // The preamble's definitions (`@use`, `$variables`, mixins) emit no
51
+ // CSS. Whatever it does emit on its own (`@keyframes`) is the resolved
52
+ // component style.
53
+ componentStyle: emptyToUndefined(compilePreamble(preamble, compiler, tools)),
54
+ };
55
+ }
56
+ /** Whether a value is a runtime `{ $expression }` binding. */
57
+ function isExpressionBinding(value) {
58
+ return (typeof value === "object" &&
59
+ value !== null &&
60
+ !Array.isArray(value) &&
61
+ "$expression" in value);
62
+ }
63
+ /**
64
+ * Resolves one static style object to its flat-CSS nested-`&` form.
65
+ *
66
+ * Splits off `$expression`-valued top-level properties (runtime values, never
67
+ * Sass), compiles the static remainder under {@link PLACEHOLDER} with the
68
+ * preamble in scope, reconstructs the flat CSS into a nested-`&` style object,
69
+ * then merges the dynamic properties back. A style with no static content
70
+ * (only expression properties) is returned unchanged.
71
+ */
72
+ function resolveStyleObject(style, preamble, compiler, tools) {
73
+ const dynamic = {};
74
+ const staticStyle = {};
75
+ for (const [key, value] of Object.entries(style)) {
76
+ if (value === undefined) {
77
+ continue;
78
+ }
79
+ // The whole-object `$expression` (a string) and per-property expression
80
+ // values are runtime values, never Sass - split them off and merge back.
81
+ if (key === "$expression" || isExpressionBinding(value)) {
82
+ dynamic[key] = value;
83
+ }
84
+ else {
85
+ staticStyle[key] = value;
86
+ }
87
+ }
88
+ if (Object.keys(staticStyle).length === 0) {
89
+ return style;
90
+ }
91
+ const block = tools
92
+ .nestedRules({ selector: PLACEHOLDER, style: staticStyle }, scss_writer_1.SCSS_DIALECT)
93
+ .join("\n\n");
94
+ const source = preamble === "" ? block : `${preamble}\n${block}`;
95
+ const css = compile(source, compiler, tools);
96
+ const resolved = reconstruct(parseCss(css));
97
+ return { ...resolved, ...dynamic };
98
+ }
99
+ /** Compiles the preamble alone, returning the CSS its own rules emit. */
100
+ function compilePreamble(preamble, compiler, tools) {
101
+ if (preamble === "") {
102
+ return "";
103
+ }
104
+ return compile(preamble, compiler, tools).trim();
105
+ }
106
+ /** Dart Sass, once a compile has needed it. */
107
+ let compiler;
108
+ /**
109
+ * Dart Sass, loaded when the first compile runs: a build that resolves no
110
+ * Sass source never loads it.
111
+ */
112
+ function loadSass() {
113
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
114
+ compiler ?? (compiler = require("sass"));
115
+ return compiler;
116
+ }
117
+ /** Runs Dart Sass, reporting a compile failure as the engine's error. */
118
+ function compile(source, { language, loadPaths, importers }, tools) {
119
+ try {
120
+ return loadSass().compileString(source, {
121
+ loadPaths: [...loadPaths],
122
+ importers: importers,
123
+ style: "expanded",
124
+ }).css;
125
+ }
126
+ catch (error) {
127
+ const detail = error instanceof Error ? error.message : String(error);
128
+ return tools.fail(`Sass resolution failed (styling.language: '${language}'): ${detail}`);
129
+ }
130
+ }
131
+ /**
132
+ * Reconstructs compiled CSS into a node's nested-`&` style object. The rule
133
+ * matching the placeholder root exactly contributes its declarations as
134
+ * top-level plain properties (so they inline under the `inline` placement);
135
+ * every other placeholder-rooted rule becomes a nested-`&` key (so it routes
136
+ * to a stylesheet). Rules with no placeholder reference (preamble output, e.g.
137
+ * keyframes) are dropped - the preamble is compiled separately.
138
+ */
139
+ function reconstruct(nodes) {
140
+ const style = {};
141
+ for (const node of nodes) {
142
+ if (node.type === "atRule") {
143
+ // Sass emits a separate at-rule block per source branch, so the same
144
+ // `@media ...` appears more than once; merge their inner rules under one
145
+ // key (object keys are unique, and one combined block is equivalent).
146
+ const existing = style[node.name];
147
+ const inner = typeof existing === "object" &&
148
+ existing !== null &&
149
+ !Array.isArray(existing)
150
+ ? existing
151
+ : {};
152
+ for (const rule of node.nodes) {
153
+ if (rule.type === "rule" && referencesPlaceholder(rule.selector)) {
154
+ inner[relativize(rule.selector)] = declarationsToStyle(rule.declarations);
155
+ }
156
+ }
157
+ if (Object.keys(inner).length > 0) {
158
+ style[node.name] = inner;
159
+ }
160
+ continue;
161
+ }
162
+ if (!referencesPlaceholder(node.selector)) {
163
+ continue;
164
+ }
165
+ const declarations = declarationsToStyle(node.declarations);
166
+ if (isPlaceholderRoot(node.selector)) {
167
+ Object.assign(style, declarations);
168
+ }
169
+ else {
170
+ style[relativize(node.selector)] = declarations;
171
+ }
172
+ }
173
+ return style;
174
+ }
175
+ function declarationsToStyle(declarations) {
176
+ const style = {};
177
+ for (const { property, value } of declarations) {
178
+ style[property] = value;
179
+ }
180
+ return style;
181
+ }
182
+ function referencesPlaceholder(selector) {
183
+ return selector.includes(PLACEHOLDER);
184
+ }
185
+ /** True when the selector is the placeholder root alone (the node itself). */
186
+ function isPlaceholderRoot(selector) {
187
+ return selector.trim() === PLACEHOLDER;
188
+ }
189
+ /** Re-relativizes a compiled selector: the placeholder root becomes `&`. */
190
+ function relativize(selector) {
191
+ return selector.split(PLACEHOLDER).join("&").trim();
192
+ }
193
+ function emptyToUndefined(value) {
194
+ return value === "" ? undefined : value;
195
+ }
196
+ /**
197
+ * A minimal parser for the regular, expanded CSS Dart Sass emits: style rules
198
+ * (`selector { prop: value; ... }`) and nested at-rules (`@media ... { ... }`).
199
+ * Declarations split on top-level semicolons (paren-aware, so `rgb(a, b)` and
200
+ * `calc(... )` values stay intact). Sufficient for compiled Sass output; not a
201
+ * general CSS parser.
202
+ */
203
+ function parseCss(css) {
204
+ const nodes = [];
205
+ let index = 0;
206
+ const parseBlock = () => {
207
+ const result = [];
208
+ let prelude = "";
209
+ while (index < css.length) {
210
+ const char = css[index];
211
+ if (char === "}") {
212
+ index += 1;
213
+ break;
214
+ }
215
+ if (char === "{") {
216
+ index += 1;
217
+ const head = prelude.trim();
218
+ prelude = "";
219
+ if (head.startsWith("@")) {
220
+ result.push({ type: "atRule", name: head, nodes: parseBlock() });
221
+ }
222
+ else {
223
+ result.push({
224
+ type: "rule",
225
+ selector: head,
226
+ declarations: parseDeclarations(),
227
+ });
228
+ }
229
+ continue;
230
+ }
231
+ prelude += char;
232
+ index += 1;
233
+ }
234
+ return result;
235
+ };
236
+ // Parse declarations of a style rule, stopping at the closing brace. A
237
+ // nested block would mean an at-rule inside a style rule (not emitted for
238
+ // these inputs); declarations are split on paren-aware top-level `;`.
239
+ const parseDeclarations = () => {
240
+ let body = "";
241
+ while (index < css.length && css[index] !== "}") {
242
+ body += css[index];
243
+ index += 1;
244
+ }
245
+ index += 1; // consume '}'
246
+ return splitDeclarations(body);
247
+ };
248
+ while (index < css.length) {
249
+ const before = index;
250
+ nodes.push(...parseBlock());
251
+ if (index === before) {
252
+ index += 1;
253
+ }
254
+ }
255
+ return nodes;
256
+ }
257
+ function splitDeclarations(body) {
258
+ const declarations = [];
259
+ let depth = 0;
260
+ let current = "";
261
+ const flush = () => {
262
+ const trimmed = current.trim();
263
+ current = "";
264
+ if (trimmed === "") {
265
+ return;
266
+ }
267
+ // A statement at-rule Sass passed through (`@apply px-4 hover:m-0`).
268
+ if (trimmed.startsWith("@")) {
269
+ declarations.push({ property: trimmed, value: true });
270
+ return;
271
+ }
272
+ const colon = trimmed.indexOf(":");
273
+ if (colon === -1) {
274
+ return;
275
+ }
276
+ declarations.push({
277
+ property: trimmed.slice(0, colon).trim(),
278
+ value: trimmed.slice(colon + 1).trim(),
279
+ });
280
+ };
281
+ for (const char of body) {
282
+ if (char === "(") {
283
+ depth += 1;
284
+ }
285
+ else if (char === ")") {
286
+ depth -= 1;
287
+ }
288
+ if (char === ";" && depth === 0) {
289
+ flush();
290
+ continue;
291
+ }
292
+ current += char;
293
+ }
294
+ flush();
295
+ return declarations;
296
+ }
297
+ /**
298
+ * Whether a style object holds a Sass include at any depth: the `$include`
299
+ * key or an `@include ...` at-rule key.
300
+ */
301
+ function objectHasInclude(style) {
302
+ for (const [key, value] of Object.entries(style)) {
303
+ if (key === "$include" || key.startsWith("@include")) {
304
+ return true;
305
+ }
306
+ if (typeof value === "object" &&
307
+ value !== null &&
308
+ !Array.isArray(value) &&
309
+ !isExpressionBinding(value) &&
310
+ objectHasInclude(value)) {
311
+ return true;
312
+ }
313
+ }
314
+ return false;
315
+ }
@@ -0,0 +1,70 @@
1
+ import type { AtRuleClaim, Extension, StylesheetLanguageExtension } from "@js-template-engine/types";
2
+ export { SASS_LAYER_ORDER_FILE } from "./scss-writer";
3
+ /** The options of {@link sass}. */
4
+ export interface SassOptions {
5
+ /**
6
+ * Directories Sass resolves `@use`, `@forward`, `@import` and `@include`
7
+ * against, matching Sass's own load-path model. Under SCSS output they
8
+ * are the consumer's own Sass build's to set; they are read here when
9
+ * Sass source is resolved to CSS.
10
+ */
11
+ loadPaths?: readonly string[];
12
+ /**
13
+ * Sass importers tried beside the load paths on every compile, such as
14
+ * one that resolves a package's `pkg:` URLs. Each is a Dart Sass importer
15
+ * object (an `Importer` or a `FileImporter`).
16
+ */
17
+ importers?: readonly unknown[];
18
+ /**
19
+ * Whether the build's stylesheets are written as SCSS. `true` (default)
20
+ * selects the `scss` language. `false` leaves the language to the build,
21
+ * and resolves the Sass source in a template to CSS for it.
22
+ */
23
+ output?: boolean;
24
+ }
25
+ /** The Sass extension that writes SCSS: a stylesheet language extension. */
26
+ export type SassExtension = StylesheetLanguageExtension;
27
+ /**
28
+ * The Sass extension that writes no stylesheet of its own: it resolves the
29
+ * Sass source in a template to CSS for the language the build writes.
30
+ */
31
+ export type SassSourceExtension = Extension & {
32
+ readonly atRules: AtRuleClaim;
33
+ };
34
+ /**
35
+ * Creates the Sass extension.
36
+ *
37
+ * With no options it selects the `scss` stylesheet language: each
38
+ * component's stylesheet is written as nested SCSS blocks in a `.scss`
39
+ * file, for the consumer's own Sass build, with `@include` keys and the
40
+ * component's Sass preamble written as they stand.
41
+ *
42
+ * With `output: false` it writes no stylesheet. The build writes its own
43
+ * language, and the extension resolves `@include` keys, Sass functions and
44
+ * `$variables` to plain CSS first, against `loadPaths` and `importers`.
45
+ *
46
+ * Either way the extension claims the `@include` at-rule key of a style
47
+ * object, and reads a component's `extensions.sass.preamble` as its Sass
48
+ * preamble: `@use` lines, variables and mixins at file scope.
49
+ *
50
+ * @param options - The load paths, the importers and whether SCSS is
51
+ * written.
52
+ * @returns The extension.
53
+ *
54
+ * @example
55
+ * process(template, {
56
+ * extensions: [react(), sass({ loadPaths: ['styles'] })],
57
+ * styling: { placement: 'separate-file' },
58
+ * });
59
+ * // files: Button.tsx, Button.scss
60
+ *
61
+ * @example
62
+ * process(template, {
63
+ * extensions: [react(), sass({ loadPaths: ['styles'], output: false })],
64
+ * });
65
+ * // files: Button.tsx, its styles resolved to CSS
66
+ */
67
+ export declare function sass(options: SassOptions & {
68
+ output: false;
69
+ }): SassSourceExtension;
70
+ export declare function sass(options?: SassOptions): SassExtension;
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SASS_LAYER_ORDER_FILE = void 0;
4
+ exports.sass = sass;
5
+ const resolve_sass_1 = require("./resolve-sass");
6
+ const scss_writer_1 = require("./scss-writer");
7
+ var scss_writer_2 = require("./scss-writer");
8
+ Object.defineProperty(exports, "SASS_LAYER_ORDER_FILE", { enumerable: true, get: function () { return scss_writer_2.SASS_LAYER_ORDER_FILE; } });
9
+ /**
10
+ * The warning for a selector key still holding Sass interpolation
11
+ * (`#{&}--dense`) in a build no Sass compile reads: it reaches the
12
+ * stylesheet as written and matches nothing.
13
+ */
14
+ function unresolvedKeyWarning(key, { hasClass }) {
15
+ if (!key.includes("#{")) {
16
+ return undefined;
17
+ }
18
+ return (`The selector '${key}' holds Sass interpolation, and these styles are not compiled through Sass, ` +
19
+ `so it is written to the stylesheet as it stands and matches nothing. ` +
20
+ (hasClass
21
+ ? `Set the styling language to 'scss', or write the selector without #{...}`
22
+ : `The element has no class for Sass to build on, so the 'scss' language would not help: ` +
23
+ `give the element a class, or write the selector without #{...}`));
24
+ }
25
+ /**
26
+ * Checks the value of an `@include ...` key: `true`, a statement with no
27
+ * content, or an object, the include's content block.
28
+ */
29
+ function validateValue(_key, value) {
30
+ return value === true ||
31
+ (typeof value === "object" &&
32
+ value !== null &&
33
+ !Array.isArray(value) &&
34
+ !("$expression" in value))
35
+ ? undefined
36
+ : "An '@include' value must be `true` (a no-content statement) or an object (a content block)";
37
+ }
38
+ /** Whether a value is a plain object. */
39
+ function isRecord(value) {
40
+ return typeof value === "object" && value !== null && !Array.isArray(value);
41
+ }
42
+ /**
43
+ * Checks a template's `extensions.sass` blocks: the component's holds a
44
+ * `preamble` that is a string, and no node below it holds one, since the
45
+ * preamble is the component's.
46
+ */
47
+ function validateOverrides(template) {
48
+ const violations = [];
49
+ const visit = (value, path, root) => {
50
+ if (Array.isArray(value)) {
51
+ value.forEach((entry, index) => visit(entry, `${path}[${index}]`, root));
52
+ return;
53
+ }
54
+ if (!isRecord(value)) {
55
+ return;
56
+ }
57
+ const block = isRecord(value.extensions)
58
+ ? value.extensions.sass
59
+ : undefined;
60
+ const blockPath = `${path === "" ? "" : `${path}.`}extensions.sass`;
61
+ if (block !== undefined && typeof value.type === "string") {
62
+ if (!root) {
63
+ violations.push({
64
+ message: "'extensions.sass' is read on the component alone, where its 'preamble' is the component's Sass preamble; a node takes none",
65
+ nodePath: blockPath,
66
+ });
67
+ }
68
+ else if (!isRecord(block)) {
69
+ violations.push({
70
+ message: "'extensions.sass' must be an object, such as { preamble: \"@use 'tokens';\" }",
71
+ nodePath: blockPath,
72
+ });
73
+ }
74
+ else if (block.preamble !== undefined &&
75
+ typeof block.preamble !== "string") {
76
+ violations.push({
77
+ message: "'extensions.sass.preamble' must be a string of Sass: the @use lines, variables and mixins the component's styles resolve against",
78
+ nodePath: `${blockPath}.preamble`,
79
+ });
80
+ }
81
+ }
82
+ for (const [key, entry] of Object.entries(value)) {
83
+ if (key !== "extensions" && (Array.isArray(entry) || isRecord(entry))) {
84
+ visit(entry, path === "" ? key : `${path}.${key}`, false);
85
+ }
86
+ }
87
+ };
88
+ if (Array.isArray(template)) {
89
+ template.forEach((node, index) => visit(node, `[${index}]`, false));
90
+ }
91
+ else {
92
+ visit(template, "", true);
93
+ }
94
+ return violations;
95
+ }
96
+ function sass(options = {}) {
97
+ const compiler = {
98
+ loadPaths: options.loadPaths ?? [],
99
+ importers: options.importers ?? [],
100
+ };
101
+ const source = {
102
+ key: "sass",
103
+ overrideKeys: { component: ["preamble"] },
104
+ validateOverrides,
105
+ atRules: {
106
+ names: ["include"],
107
+ resolve: (styles, tools) => (0, resolve_sass_1.resolveSassStyles)(styles, compiler, tools),
108
+ unresolvedKeyWarning,
109
+ validateValue,
110
+ },
111
+ };
112
+ return options.output === false
113
+ ? source
114
+ : { ...source, kind: "stylesheet-language", writer: (0, scss_writer_1.scssWriter)() };
115
+ }
@@ -0,0 +1,50 @@
1
+ import type { NestingDialect, StylesheetSourceSyntax, StylesheetWriter } from "@js-template-engine/types";
2
+ /**
3
+ * The generated Sass module stating the cascade layer order, written beside
4
+ * each SCSS stylesheet that loads it: a partial, so no component's file
5
+ * name can meet it.
6
+ */
7
+ export declare const SASS_LAYER_ORDER_FILE = "_layer-order.scss";
8
+ /**
9
+ * What SCSS makes of a style object: every nested key a nested block, and a
10
+ * selector that extends `&` joined to it.
11
+ */
12
+ export declare const SCSS_DIALECT: NestingDialect;
13
+ /**
14
+ * What SCSS adds to CSS where the names a stylesheet defines are read: its
15
+ * comments, interpolation and variables, the statements and blocks that
16
+ * write nothing where they stand, and the blocks written only where a
17
+ * mixin is included or a condition holds.
18
+ */
19
+ export declare const SCSS_SOURCE_SYNTAX: StylesheetSourceSyntax;
20
+ /**
21
+ * The Sass preamble of a component: the `preamble` of its `extensions.sass`
22
+ * block, ahead of its component-level style, which is written at file scope
23
+ * too. Sass takes its loads before anything else, so where both are
24
+ * present the `@use` and `@forward` statements that lead each of them lead
25
+ * the result, the preamble's first, and the rest of each follows in the
26
+ * same order. One of them alone is written as it stands.
27
+ *
28
+ * @param overrides - The component's `extensions` blocks.
29
+ * @param componentStyle - The component-level style, trimmed.
30
+ * @returns The preamble; empty when there is neither.
31
+ *
32
+ * @example
33
+ * sassPreamble({ sass: { preamble: '$gap: 4px;' } }, "@use 'tokens';\n.x {}");
34
+ * // "@use 'tokens';\n\n$gap: 4px;\n\n.x {}"
35
+ */
36
+ export declare function sassPreamble(overrides: Readonly<Record<string, unknown>>, componentStyle: string | undefined): string;
37
+ /**
38
+ * Creates the SCSS stylesheet writer: nested style objects written as
39
+ * nested SCSS blocks, for the consumer's own Sass build, with `@include`
40
+ * keys and the preamble written as they stand. Pseudo-selector keys become
41
+ * `&:hover`, and parent-modifier keys (`.ancestor &`) and at-rule keys
42
+ * (`@media ...`) nest verbatim. The cascade layer order is stated by
43
+ * loading {@link SASS_LAYER_ORDER_FILE} first.
44
+ *
45
+ * @returns The writer.
46
+ *
47
+ * @example
48
+ * scssWriter().fileExtension; // 'scss'
49
+ */
50
+ export declare function scssWriter(): StylesheetWriter;
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SCSS_SOURCE_SYNTAX = exports.SCSS_DIALECT = exports.SASS_LAYER_ORDER_FILE = void 0;
4
+ exports.sassPreamble = sassPreamble;
5
+ exports.scssWriter = scssWriter;
6
+ /** Sass load at-rules, which must precede everything else in a `.scss` file. */
7
+ const SASS_LOAD_PATTERN = /^@(?:use|forward)\b/;
8
+ /**
9
+ * The generated Sass module stating the cascade layer order, written beside
10
+ * each SCSS stylesheet that loads it: a partial, so no component's file
11
+ * name can meet it.
12
+ */
13
+ exports.SASS_LAYER_ORDER_FILE = "_layer-order.scss";
14
+ /**
15
+ * The load each SCSS stylesheet starts with under a layer order, a separate
16
+ * one or a component file's style block. Loaded without a namespace
17
+ * (`as *`): the module has no members, and a stylesheet whose preamble
18
+ * loads a module of the kit's own named `layer-order` would otherwise meet
19
+ * its namespace twice.
20
+ */
21
+ const LAYER_ORDER_LOAD = "@use './layer-order' as *;";
22
+ /**
23
+ * What SCSS makes of a style object: every nested key a nested block, and a
24
+ * selector that extends `&` joined to it.
25
+ */
26
+ exports.SCSS_DIALECT = {
27
+ unspellable: "suffix",
28
+ nestsUnderComplexParent: true,
29
+ };
30
+ /**
31
+ * What SCSS adds to CSS where the names a stylesheet defines are read: its
32
+ * comments, interpolation and variables, the statements and blocks that
33
+ * write nothing where they stand, and the blocks written only where a
34
+ * mixin is included or a condition holds.
35
+ */
36
+ exports.SCSS_SOURCE_SYNTAX = {
37
+ lineComments: true,
38
+ interpolation: {
39
+ open: "#{",
40
+ close: "}",
41
+ description: "a selector with Sass interpolation, whose class names the engine cannot read ahead of the Sass build",
42
+ },
43
+ variableDeclaration: /^\$/,
44
+ silentStatements: /^@(?:use|forward|debug|warn|error|extend|return)\b/,
45
+ rulelessAtRules: /^@function\b/,
46
+ expandedAtRules: /^@include\b/,
47
+ conditionalAtRules: {
48
+ pattern: /^@(?:mixin|if|else|each|for|while|include|at-root)\b/,
49
+ description: "a selector inside a @mixin, a control rule or an include's content block, which the engine cannot tell is built",
50
+ },
51
+ };
52
+ /**
53
+ * Splits the leading run of Sass loads off a preamble: its `@use` and
54
+ * `@forward` statements, each to its closing `;`, with the blank lines and
55
+ * comments between them. Anything else ends the run.
56
+ */
57
+ function splitLoads(text) {
58
+ const lines = text.split("\n");
59
+ let index = 0;
60
+ let lastLoad = -1;
61
+ while (index < lines.length) {
62
+ const line = lines[index].trim();
63
+ if (line === "" || line.startsWith("//") || line.startsWith("/*")) {
64
+ index += 1;
65
+ continue;
66
+ }
67
+ if (!SASS_LOAD_PATTERN.test(line)) {
68
+ break;
69
+ }
70
+ while (index < lines.length && !lines[index].trimEnd().endsWith(";")) {
71
+ index += 1;
72
+ }
73
+ lastLoad = index;
74
+ index += 1;
75
+ }
76
+ return {
77
+ loads: lines
78
+ .slice(0, lastLoad + 1)
79
+ .join("\n")
80
+ .trim(),
81
+ rest: lines
82
+ .slice(lastLoad + 1)
83
+ .join("\n")
84
+ .trim(),
85
+ };
86
+ }
87
+ /**
88
+ * The Sass preamble of a component: the `preamble` of its `extensions.sass`
89
+ * block, ahead of its component-level style, which is written at file scope
90
+ * too. Sass takes its loads before anything else, so where both are
91
+ * present the `@use` and `@forward` statements that lead each of them lead
92
+ * the result, the preamble's first, and the rest of each follows in the
93
+ * same order. One of them alone is written as it stands.
94
+ *
95
+ * @param overrides - The component's `extensions` blocks.
96
+ * @param componentStyle - The component-level style, trimmed.
97
+ * @returns The preamble; empty when there is neither.
98
+ *
99
+ * @example
100
+ * sassPreamble({ sass: { preamble: '$gap: 4px;' } }, "@use 'tokens';\n.x {}");
101
+ * // "@use 'tokens';\n\n$gap: 4px;\n\n.x {}"
102
+ */
103
+ function sassPreamble(overrides, componentStyle) {
104
+ const authored = overrides.sass
105
+ ?.preamble;
106
+ const preamble = typeof authored === "string" ? authored.trim() : "";
107
+ const style = componentStyle ?? "";
108
+ if (preamble === "" || style === "") {
109
+ return preamble === "" ? style : preamble;
110
+ }
111
+ const first = splitLoads(preamble);
112
+ const second = splitLoads(style);
113
+ return [
114
+ [first.loads, second.loads].filter((part) => part !== "").join("\n"),
115
+ first.rest,
116
+ second.rest,
117
+ ]
118
+ .filter((part) => part !== "")
119
+ .join("\n\n");
120
+ }
121
+ /**
122
+ * Creates the SCSS stylesheet writer: nested style objects written as
123
+ * nested SCSS blocks, for the consumer's own Sass build, with `@include`
124
+ * keys and the preamble written as they stand. Pseudo-selector keys become
125
+ * `&:hover`, and parent-modifier keys (`.ancestor &`) and at-rule keys
126
+ * (`@media ...`) nest verbatim. The cascade layer order is stated by
127
+ * loading {@link SASS_LAYER_ORDER_FILE} first.
128
+ *
129
+ * @returns The writer.
130
+ *
131
+ * @example
132
+ * scssWriter().fileExtension; // 'scss'
133
+ */
134
+ function scssWriter() {
135
+ return {
136
+ language: "scss",
137
+ fileExtension: "scss",
138
+ styleBlockLanguage: "scss",
139
+ needsCompilation: true,
140
+ carriesStatements: true,
141
+ passesThrough: ["include"],
142
+ unresolvedSource: exports.SCSS_SOURCE_SYNTAX,
143
+ // Sass allows nothing before a stylesheet's loads and writes each
144
+ // loaded module's CSS ahead of the stylesheet's own, so the layer order
145
+ // is stated in a module of its own, loaded first.
146
+ companionFiles: (css, { layer }) => layer?.order !== undefined &&
147
+ layer.order.length > 0 &&
148
+ css.startsWith(LAYER_ORDER_LOAD)
149
+ ? [
150
+ {
151
+ path: exports.SASS_LAYER_ORDER_FILE,
152
+ content: `@layer ${layer.order.join(", ")};\n`,
153
+ },
154
+ ]
155
+ : [],
156
+ write: (stylesheet, tools) => {
157
+ const preamble = sassPreamble(stylesheet.overrides, stylesheet.componentStyle);
158
+ const source = {
159
+ ...stylesheet,
160
+ componentStyle: preamble === "" ? undefined : preamble,
161
+ classNames: () => stylesheet.classNames(),
162
+ carriedTogether: (first, second) => stylesheet.carriedTogether(first, second),
163
+ };
164
+ return tools.textStylesheet(source, {
165
+ rule: (rule) => tools.nestedRules(rule, exports.SCSS_DIALECT),
166
+ leadingStatements: SASS_LOAD_PATTERN,
167
+ layerOrderLoad: LAYER_ORDER_LOAD,
168
+ });
169
+ },
170
+ };
171
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@js-template-engine/extension-sass",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2.4.0",
4
+ "description": "Sass extension for the JS Template Engine: writes a component's stylesheet as SCSS, resolves Sass source to CSS for every other stylesheet language, and gives @include style keys their meaning",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js",
11
+ "require": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md"
17
+ ],
18
+ "dependencies": {
19
+ "sass": "^1.101.0",
20
+ "@js-template-engine/types": "^2.4.0"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/djurnamn/js-template-engine.git",
25
+ "directory": "packages/extension-sass"
26
+ },
27
+ "keywords": [
28
+ "js-template-engine",
29
+ "sass",
30
+ "scss",
31
+ "stylesheet",
32
+ "extension"
33
+ ],
34
+ "author": "Björn Djurnamn <bjorn@djurnamn.co>",
35
+ "license": "MIT",
36
+ "bugs": {
37
+ "url": "https://github.com/djurnamn/js-template-engine/issues"
38
+ },
39
+ "homepage": "https://github.com/djurnamn/js-template-engine/tree/main/packages/extension-sass",
40
+ "devDependencies": {
41
+ "@types/node": "^20.0.0",
42
+ "rimraf": "^5.0.5",
43
+ "typescript": "^5.3.3",
44
+ "vitest": "^1.6.1"
45
+ },
46
+ "scripts": {
47
+ "build": "tsc",
48
+ "build:watch": "tsc --watch",
49
+ "clean": "rimraf dist",
50
+ "test": "vitest run",
51
+ "test:watch": "vitest",
52
+ "typecheck": "tsc --noEmit -p tsconfig.type-check.json",
53
+ "lint": "eslint --max-warnings 0 ."
54
+ }
6
55
  }