@octane-xplat/bamboo 0.19.0 → 0.20.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/README.md CHANGED
@@ -1,98 +1,5 @@
1
1
  # `@octane-xplat/bamboo`
2
2
 
3
- Shared [Bamboo](https://github.com/aleclarson/bamboo) CSS defaults for
4
- Octane xplat apps. `xplatBambooConfig` scopes generation to the CSS subset
5
- both NativeScript and browsers support (`xplatPortablePreset` and the
6
- `vx-*` utility classes on framework token variables) and orders layers so
7
- utilities sit under the app's own CSS. A Vite plugin emits the stylesheet.
3
+ [Documentation](https://octane-xplat.goddardai.org/package-bamboo).
8
4
 
9
- ```sh
10
- bun add -D @octane-xplat/bamboo
11
- ```
12
-
13
- Two entry points:
14
-
15
- ```ts
16
- // bamboo.config.ts
17
- import { defineConfig } from '@bamboocss/dev'
18
- import { xplatBambooConfig } from '@octane-xplat/bamboo'
19
-
20
- export default defineConfig({
21
- ...xplatBambooConfig,
22
- include: ['src/**/*.ts'],
23
- outdir: 'src/styled',
24
- })
25
- ```
26
-
27
- Token names mirror the UI theme variables: every `--color-*`, `--radius-*`,
28
- and `--space-*` the default theme in `@octane-xplat/ui/theme/chrome.css`
29
- declares is a valid token, compiled to its variable (`warning` →
30
- `var(--color-warning)`). A token only resolves when that stylesheet is
31
- imported or the app defines the variable itself.
32
-
33
- ```ts
34
- css({ color: 'warning' }) // -> var(--color-warning)
35
- ```
36
-
37
- Preflight is off by default and tokens land on `:root, .ns-root`. The
38
- xplat NativeScript CSS transform unwraps the emitted `@layer` blocks for
39
- native builds (the NS parser drops unknown at-rules); browsers keep the
40
- layers, which is what lets app CSS stay unlayered on top.
41
-
42
- ```ts
43
- // Add this plugin alongside your app's existing renderer plugins.
44
- import { xplatBamboo } from '@octane-xplat/bamboo/vite'
45
-
46
- const webPlugins = xplatBamboo()
47
- const nativePlugins = xplatBamboo({ native: true })
48
- ```
49
-
50
- `native: true` covers NativeScript (iOS/Android), the AppKit renderer, and
51
- the GTK renderer — both desktop presets consume the same finalized
52
- `virtual:bamboo.css` asset through `xplatInlineStylesheets`.
53
-
54
- Platform conditions use the same build-time compiler as ordinary CSS. Add
55
- `xplatCss('web')` from `@octane-xplat/cli/vite` to web plugins; native presets
56
- include it. Keep the portable utility subset unless you explicitly extend it.
57
- SSR generation with platform conditions is currently unsupported.
58
-
59
- ```ts
60
- import { css } from './styled-system/css'
61
-
62
- const card = css({
63
- padding: '4',
64
- _web: { color: 'primary' },
65
- _mobile: { color: 'text' },
66
- })
67
- ```
68
-
69
- Guide: [Styling screens](https://octane-xplat.goddardai.org/styling).
70
-
71
- ## Custom builders with unused environments
72
-
73
- A Vite environment is a named build target. Some Cloudflare setups configure
74
- `ssr` but only build a Worker and a browser client. With Bamboo 1.56.2, pass
75
- `buildEnvironments` containing every target your builder actually runs to avoid
76
- an incorrect incomplete-run warning. Use your Worker's environment name:
77
-
78
- ```ts
79
- import { xplatBamboo } from '@octane-xplat/bamboo/vite'
80
-
81
- const plugins = xplatBamboo({
82
- buildEnvironments: ['api', 'client'],
83
- })
84
- ```
85
-
86
- Keep real server-rendering targets in the list, even when they emit no CSS
87
- asset: their reachable styles must remain in the browser stylesheet. An
88
- excluded target that starts building causes an error; a listed target that
89
- never completes still triggers Bamboo's warning. Omit the option for builders
90
- that build all configured environments. Pruning stays enabled.
91
-
92
- ```ts
93
- const plugins = xplatBamboo({ buildEnvironments: ['client', 'ssr'] })
94
- ```
95
-
96
- This option declares participation; it does not schedule builds. It adapts
97
- Bamboo 1.56.2's environment accounting and requires Vite's environment builder.
98
- Platform conditions with real SSR remain unsupported, as described above.
5
+ [API reference](https://octane-xplat.goddardai.org/api-bamboo).
@@ -63,7 +63,7 @@ export function platformOutput() {
63
63
  const mapKey = `${asset.fileName}.map`;
64
64
  const mapAsset = bundle[mapKey];
65
65
  const previousMap = mapAsset?.type === 'asset' ? String(mapAsset.source) : undefined;
66
- if (!source.includes('@platform')) {
66
+ if (!compiler.hasPlatformConditions(source)) {
67
67
  continue;
68
68
  }
69
69
  const projected = compiler.project(source, asset.fileName, previousMap);
package/dist/vite.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { bamboocss } from '@bamboocss/vite';
2
- import { buildEnvironments as adaptBuildEnvironments } from "./build-environments.js";
3
- import { platformOutput } from "./platform-output.js";
2
+ import { buildEnvironments as adaptBuildEnvironments } from './build-environments.js';
3
+ import { platformOutput } from './platform-output.js';
4
4
  function runBeforeNativeCss(plugin, anchor) {
5
5
  const hook = plugin?.generateBundle;
6
6
  if (plugin && typeof hook === 'function') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@octane-xplat/bamboo",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "Bamboo CSS integration defaults for Octane xplat apps",
5
5
  "keywords": [
6
6
  "bamboo",
@@ -44,7 +44,7 @@
44
44
  "scripts": {
45
45
  "prepack": "bun run typegen",
46
46
  "test:packed": "node tests/packed-consumer.mjs",
47
- "typegen": "tsc -p tsconfig.build.json",
47
+ "typegen": "tsc --runExternalCode -p tsconfig.build.json",
48
48
  "test": "node --test tests/*.test.mjs"
49
49
  },
50
50
  "dependencies": {
@@ -56,8 +56,9 @@
56
56
  },
57
57
  "devDependencies": {
58
58
  "@bamboocss/dev": "1.60.1",
59
- "@octane-xplat/cli": "0.19.0",
60
- "typescript": "5.9.3"
59
+ "@octane-xplat/cli": "0.20.0",
60
+ "typescript": "7.1.0-beta",
61
+ "@tsrx/content-mapper": "0.1.2"
61
62
  },
62
63
  "peerDependencies": {
63
64
  "vite": ">=5"
@@ -2,63 +2,69 @@ import type { Plugin } from 'vite'
2
2
 
3
3
  /** Adapt Bamboo 1.56.2's configured-environment accounting to an explicit build plan. */
4
4
  export function buildEnvironments(plugins: Plugin[], names: readonly string[]) {
5
- const participating = new Set(names)
6
- if (!participating.size || names.some((name) => !name)) {
7
- throw new Error('@octane-xplat/bamboo: buildEnvironments must contain environment names')
8
- }
5
+ const participating = new Set(names)
9
6
 
10
- const css = plugins.find((plugin) => plugin.name === 'bamboocss:css')
11
- const resolvedHook = css?.configResolved
12
- const appHook = css?.buildApp
13
- const resolved = typeof resolvedHook === 'function' ? resolvedHook : resolvedHook?.handler
14
- const app = typeof appHook === 'function' ? appHook : appHook?.handler
15
- if (!css || !resolved || !app) {
16
- throw new Error(
17
- '@octane-xplat/bamboo: buildEnvironments requires Bamboo CSS configResolved and buildApp hooks',
18
- )
19
- }
7
+ if (!participating.size || names.some((name) => !name)) {
8
+ throw new Error('@octane-xplat/bamboo: buildEnvironments must contain environment names')
9
+ }
20
10
 
21
- function select<T>(environments: Record<string, T>): Record<string, T> {
22
- for (const name of participating) {
23
- if (!Object.hasOwn(environments, name)) {
24
- throw new Error(`@octane-xplat/bamboo: unknown buildEnvironments entry "${name}"`)
25
- }
26
- }
27
- return Object.fromEntries([...participating].map((name) => [name, environments[name]]))
28
- }
11
+ const css = plugins.find((plugin) => plugin.name === 'bamboocss:css')
12
+ const resolvedHook = css?.configResolved
13
+ const appHook = css?.buildApp
14
+ const resolved = typeof resolvedHook === 'function' ? resolvedHook : resolvedHook?.handler
15
+ const app = typeof appHook === 'function' ? appHook : appHook?.handler
29
16
 
30
- // Only Bamboo receives this view. Vite and other plugins retain the full registry.
31
- css.configResolved = {
32
- ...(typeof resolvedHook === 'object' ? resolvedHook : {}),
33
- handler(config) {
34
- return resolved.call(
35
- this,
36
- config.command === 'build'
37
- ? { ...config, environments: select(config.environments) }
38
- : config,
39
- )
40
- },
41
- }
42
- css.buildApp = {
43
- ...(typeof appHook === 'object' ? appHook : {}),
44
- handler(builder) {
45
- return app.call(this, { ...builder, environments: select(builder.environments) })
46
- },
47
- }
48
- plugins.unshift({
49
- name: 'xplat-bamboo:build-environments',
50
- apply: 'build',
51
- buildStart: {
52
- order: 'pre',
53
- sequential: true,
54
- handler() {
55
- const name = this.environment?.name
56
- if (!name || !participating.has(name)) {
57
- this.error(
58
- `@octane-xplat/bamboo: building environment "${name ?? 'unknown'}" is missing from buildEnvironments; include every environment the builder runs`,
59
- )
60
- }
61
- },
62
- },
63
- })
17
+ if (!css || !resolved || !app) {
18
+ throw new Error(
19
+ '@octane-xplat/bamboo: buildEnvironments requires Bamboo CSS configResolved and buildApp hooks',
20
+ )
21
+ }
22
+
23
+ function select<T>(environments: Record<string, T>): Record<string, T> {
24
+ for (const name of participating) {
25
+ if (!Object.hasOwn(environments, name)) {
26
+ throw new Error(`@octane-xplat/bamboo: unknown buildEnvironments entry "${name}"`)
27
+ }
28
+ }
29
+
30
+ return Object.fromEntries([...participating].map((name) => [name, environments[name]]))
31
+ }
32
+
33
+ // Only Bamboo receives this view. Vite and other plugins retain the full registry.
34
+ css.configResolved = {
35
+ ...(typeof resolvedHook === 'object' ? resolvedHook : {}),
36
+ handler(config) {
37
+ return resolved.call(
38
+ this,
39
+ config.command === 'build'
40
+ ? { ...config, environments: select(config.environments) }
41
+ : config,
42
+ )
43
+ },
44
+ }
45
+
46
+ css.buildApp = {
47
+ ...(typeof appHook === 'object' ? appHook : {}),
48
+ handler(builder) {
49
+ return app.call(this, { ...builder, environments: select(builder.environments) })
50
+ },
51
+ }
52
+
53
+ plugins.unshift({
54
+ name: 'xplat-bamboo:build-environments',
55
+ apply: 'build',
56
+ buildStart: {
57
+ order: 'pre',
58
+ sequential: true,
59
+ handler() {
60
+ const name = this.environment?.name
61
+
62
+ if (!name || !participating.has(name)) {
63
+ this.error(
64
+ `@octane-xplat/bamboo: building environment "${name ?? 'unknown'}" is missing from buildEnvironments; include every environment the builder runs`,
65
+ )
66
+ }
67
+ },
68
+ },
69
+ })
64
70
  }
package/src/config.ts CHANGED
@@ -4,123 +4,124 @@ import type { Preset, Theme, UserConfig, UtilityConfig } from '@bamboocss/types'
4
4
  // Bamboo 1.56.2 has no flexWrap utility. Keep it outside this selected subset
5
5
  // rather than promising a utility that cannot be generated.
6
6
  const portableProperties = [
7
- 'alignItems',
8
- 'alignSelf',
9
- 'backgroundColor',
10
- 'borderColor',
11
- 'borderRadius',
12
- 'borderWidth',
13
- 'color',
14
- 'display',
15
- 'flexDirection',
16
- 'flexGrow',
17
- 'flexShrink',
18
- 'fontFamily',
19
- 'fontSize',
20
- 'fontWeight',
21
- 'gap',
22
- 'height',
23
- 'justifyContent',
24
- 'lineHeight',
25
- 'margin',
26
- 'marginBottom',
27
- 'marginLeft',
28
- 'marginRight',
29
- 'marginTop',
30
- 'maxHeight',
31
- 'maxWidth',
32
- 'minHeight',
33
- 'minWidth',
34
- 'padding',
35
- 'paddingBottom',
36
- 'paddingLeft',
37
- 'paddingRight',
38
- 'paddingTop',
39
- 'textAlign',
40
- 'width',
7
+ 'alignItems',
8
+ 'alignSelf',
9
+ 'backgroundColor',
10
+ 'borderColor',
11
+ 'borderRadius',
12
+ 'borderWidth',
13
+ 'color',
14
+ 'display',
15
+ 'flexDirection',
16
+ 'flexGrow',
17
+ 'flexShrink',
18
+ 'fontFamily',
19
+ 'fontSize',
20
+ 'fontWeight',
21
+ 'gap',
22
+ 'height',
23
+ 'justifyContent',
24
+ 'lineHeight',
25
+ 'margin',
26
+ 'marginBottom',
27
+ 'marginLeft',
28
+ 'marginRight',
29
+ 'marginTop',
30
+ 'maxHeight',
31
+ 'maxWidth',
32
+ 'minHeight',
33
+ 'minWidth',
34
+ 'padding',
35
+ 'paddingBottom',
36
+ 'paddingLeft',
37
+ 'paddingRight',
38
+ 'paddingTop',
39
+ 'textAlign',
40
+ 'width',
41
41
  ] as const
42
42
 
43
43
  // Token names mirror every --color-* / --radius-* / --space-* variable the
44
44
  // @octane-xplat/ui default theme (theme/chrome.css `:root, .ns-root` block)
45
45
  // declares. tests/theme-tokens.test.mjs fails when the lists drift apart.
46
46
  const colors = Object.fromEntries(
47
- [
48
- 'primary',
49
- 'onprimary',
50
- 'surface',
51
- 'surface-secondary',
52
- 'text',
53
- 'text-secondary',
54
- 'text-disabled',
55
- 'border',
56
- 'border-strong',
57
- 'danger',
58
- 'warning',
59
- 'success',
60
- 'overlay-hover',
61
- 'overlay-pressed',
62
- 'danger-text',
63
- 'warning-text',
64
- 'success-text',
65
- 'syntax-keyword',
66
- 'syntax-string',
67
- 'syntax-comment',
68
- 'syntax-number',
69
- 'syntax-function',
70
- 'syntax-type',
71
- 'syntax-variable',
72
- 'syntax-operator',
73
- 'syntax-constant',
74
- 'syntax-tag',
75
- 'syntax-attribute',
76
- 'syntax-property',
77
- 'syntax-punctuation',
78
- 'syntax-background',
79
- ].map((name) => [name, { value: `var(--color-${name})` }]),
47
+ [
48
+ 'primary',
49
+ 'onprimary',
50
+ 'surface',
51
+ 'surface-secondary',
52
+ 'text',
53
+ 'text-secondary',
54
+ 'text-disabled',
55
+ 'border',
56
+ 'border-strong',
57
+ 'danger',
58
+ 'warning',
59
+ 'success',
60
+ 'overlay-hover',
61
+ 'overlay-pressed',
62
+ 'danger-text',
63
+ 'warning-text',
64
+ 'success-text',
65
+ 'syntax-keyword',
66
+ 'syntax-string',
67
+ 'syntax-comment',
68
+ 'syntax-number',
69
+ 'syntax-function',
70
+ 'syntax-type',
71
+ 'syntax-variable',
72
+ 'syntax-operator',
73
+ 'syntax-constant',
74
+ 'syntax-tag',
75
+ 'syntax-attribute',
76
+ 'syntax-property',
77
+ 'syntax-punctuation',
78
+ 'syntax-background',
79
+ ].map((name) => [name, { value: `var(--color-${name})` }]),
80
80
  )
81
81
 
82
82
  const spacing = Object.fromEntries(['4'].map((name) => [name, { value: `var(--space-${name})` }]))
83
83
 
84
84
  const radii = Object.fromEntries(
85
- ['sm', 'md', 'lg', 'xl', 'container'].map((name) => [name, { value: `var(--radius-${name})` }]),
85
+ ['sm', 'md', 'lg', 'xl', 'container'].map((name) => [name, { value: `var(--radius-${name})` }]),
86
86
  )
87
87
 
88
88
  const portableUtilities = Object.fromEntries(
89
- portableProperties.map((property) => {
90
- const config = presetBase.utilities[property]
91
- if (!config) {
92
- throw new Error(
93
- `@octane-xplat/bamboo: missing portable utility "${property}" in @bamboocss/preset-base`,
94
- )
95
- }
89
+ portableProperties.map((property) => {
90
+ const config = presetBase.utilities[property]
96
91
 
97
- // Bamboo's default margin scale includes `auto`, which NativeScript
98
- // ignores; expose token spacing only in the shared preset.
99
- return [property, property.startsWith('margin') ? { ...config, values: 'spacing' } : config]
100
- }),
92
+ if (!config) {
93
+ throw new Error(
94
+ `@octane-xplat/bamboo: missing portable utility "${property}" in @bamboocss/preset-base`,
95
+ )
96
+ }
97
+
98
+ // Bamboo's default margin scale includes `auto`, which NativeScript
99
+ // ignores; expose token spacing only in the shared preset.
100
+ return [property, property.startsWith('margin') ? { ...config, values: 'spacing' } : config]
101
+ }),
101
102
  ) as UtilityConfig
102
103
 
103
104
  const portableTheme = {
104
- tokens: {
105
- colors,
106
- radii,
107
- spacing,
108
- },
105
+ tokens: {
106
+ colors,
107
+ radii,
108
+ spacing,
109
+ },
109
110
  } satisfies Theme
110
111
 
111
112
  // Compile through the framework CSS pipeline, rather than adding runtime
112
113
  // ancestor selectors or selector specificity. These names also generate types.
113
114
  const platformConditions = {
114
- web: '@platform web',
115
- mobile: '@platform mobile',
116
- native: '@platform native',
117
- ios: '@platform ios',
118
- android: '@platform android',
119
- visionos: '@platform visionos',
120
- macos: '@platform macos',
121
- windows: '@platform windows',
122
- linux: '@platform linux',
123
- gtk: '@platform gtk',
115
+ web: '@platform web',
116
+ mobile: '@platform mobile',
117
+ native: '@platform native',
118
+ ios: '@platform ios',
119
+ android: '@platform android',
120
+ visionos: '@platform visionos',
121
+ macos: '@platform macos',
122
+ windows: '@platform windows',
123
+ linux: '@platform linux',
124
+ gtk: '@platform gtk',
124
125
  }
125
126
 
126
127
  /**
@@ -129,10 +130,10 @@ const platformConditions = {
129
130
  * apps can extend it when they have checked a property on their targets.
130
131
  */
131
132
  export const xplatPortablePreset: Preset = {
132
- name: '@octane-xplat/bamboo/portable',
133
- conditions: platformConditions,
134
- utilities: portableUtilities,
135
- theme: portableTheme,
133
+ name: '@octane-xplat/bamboo/portable',
134
+ conditions: platformConditions,
135
+ utilities: portableUtilities,
136
+ theme: portableTheme,
136
137
  }
137
138
 
138
139
  /**
@@ -143,20 +144,20 @@ export const xplatPortablePreset: Preset = {
143
144
  * order before `virtual:bamboo.css` is imported.
144
145
  */
145
146
  export const xplatBambooConfig = {
146
- preflight: false,
147
- conditions: platformConditions,
148
- cssVarRoot: ':root, .ns-root',
149
- layers: {
150
- reset: 'xplat.reset',
151
- base: 'xplat.base',
152
- tokens: 'xplat.tokens',
153
- recipes: 'xplat.recipes',
154
- utilities: 'xplat.utilities',
155
- },
156
- presets: [],
157
- utilities: portableUtilities,
158
- theme: portableTheme,
147
+ preflight: false,
148
+ conditions: platformConditions,
149
+ cssVarRoot: ':root, .ns-root',
150
+ layers: {
151
+ reset: 'xplat.reset',
152
+ base: 'xplat.base',
153
+ tokens: 'xplat.tokens',
154
+ recipes: 'xplat.recipes',
155
+ utilities: 'xplat.utilities',
156
+ },
157
+ presets: [],
158
+ utilities: portableUtilities,
159
+ theme: portableTheme,
159
160
  } satisfies Pick<
160
- UserConfig,
161
- 'conditions' | 'preflight' | 'cssVarRoot' | 'layers' | 'presets' | 'utilities' | 'theme'
161
+ UserConfig,
162
+ 'conditions' | 'preflight' | 'cssVarRoot' | 'layers' | 'presets' | 'utilities' | 'theme'
162
163
  >
@@ -5,208 +5,228 @@ import remapping from '@ampproject/remapping'
5
5
  import type { Plugin } from 'vite'
6
6
 
7
7
  interface PlatformCssApi {
8
- defer(id: string): void
9
- filter(css: string, from?: string): string
10
- project(css: string, from: string, previousMap?: string): { css: string; map?: string }
8
+ defer(id: string): void
9
+ filter(css: string, from?: string): string
10
+ hasPlatformConditions(css: string): boolean
11
+ project(css: string, from: string, previousMap?: string): { css: string; map?: string }
11
12
  }
12
13
 
13
14
  /** Filter only after Bamboo's validation and restore content-addressed asset names. */
14
15
  export function platformOutput(): Plugin {
15
- let compiler: PlatformCssApi | undefined
16
- let ssr = false
17
- const adapted = new WeakSet<Plugin>()
18
- return {
19
- name: 'xplat-bamboo:platform-output',
20
- enforce: 'post',
21
- configResolved(config) {
22
- ssr = Boolean(config.build.ssr)
23
- compiler = config.plugins.find((plugin) => plugin.name === 'xplat-platform-css')?.api
24
- if (config.command === 'build') {
25
- compiler?.defer('virtual:bamboo.css')
26
- }
27
- },
28
- transform: {
29
- order: 'pre',
30
- handler(code, id) {
31
- if (!id.split('?')[0].endsWith('virtual:bamboo.css') || !code.includes('@platform')) {
32
- return
33
- }
34
- if (!compiler) {
35
- this.error(
36
- '@octane-xplat/bamboo: platform conditions require xplatCss(target) from @octane-xplat/cli/vite',
37
- )
38
- }
39
- if (ssr || this.environment?.config.build.ssr) {
40
- this.error(
41
- '@octane-xplat/bamboo: platform conditions currently require a single renderer build; SSR generation is not supported',
42
- )
43
- }
44
- },
45
- },
46
- options: {
47
- order: 'post',
48
- handler(input) {
49
- const outputs = (
50
- input as typeof input & { output?: { plugins?: Plugin[] } | { plugins?: Plugin[] }[] }
51
- ).output
52
- for (const output of Array.isArray(outputs) ? outputs : outputs ? [outputs] : []) {
53
- for (const plugin of (output.plugins ?? []).flat(Infinity) as Plugin[]) {
54
- if (!plugin?.name?.startsWith('bamboocss:output-finalizer:') || adapted.has(plugin)) {
55
- continue
56
- }
57
-
58
- const hook = plugin.generateBundle
59
- const handler = typeof hook === 'function' ? hook : hook?.handler
60
- if (!handler) {
61
- throw new Error(
62
- '@octane-xplat/bamboo: output finalizer has no generateBundle handler',
63
- )
64
- }
65
-
66
- plugin.generateBundle = {
67
- ...(typeof hook === 'object' ? hook : {}),
68
- async handler(options, bundle, isWrite) {
69
- await handler.call(this, options, bundle, isWrite)
70
- if (!compiler) {
71
- return
72
- }
73
- const renamed = new Map<string, string>()
74
- for (const [key, asset] of Object.entries(bundle)) {
75
- if (asset.type !== 'asset' || !asset.fileName.endsWith('.css')) {
76
- continue
77
- }
78
-
79
- const source =
80
- typeof asset.source === 'string'
81
- ? asset.source
82
- : new TextDecoder().decode(asset.source)
83
-
84
- const mapKey = `${asset.fileName}.map`
85
- const mapAsset = bundle[mapKey]
86
- const previousMap =
87
- mapAsset?.type === 'asset' ? String(mapAsset.source) : undefined
88
-
89
- if (!source.includes('@platform')) {
90
- continue
91
- }
92
-
93
- const projected = compiler.project(source, asset.fileName, previousMap)
94
- let filtered = projected.css
95
- if (filtered === source) {
96
- continue
97
- }
98
-
99
- const hash = createHash('sha256').update(filtered).digest('hex').slice(0, 16)
100
- const next = asset.fileName.replace(/\.css$/, `.platform-${hash}.css`)
101
- renamed.set(asset.fileName, next)
102
- if (projected.map && previousMap) {
103
- const nextMap = `${next}.map`
104
- const map = JSON.parse(projected.map)
105
- map.file = posix.basename(next)
106
- this.emitFile({ type: 'asset', fileName: nextMap, source: JSON.stringify(map) })
107
- delete bundle[mapKey]
108
- filtered += `
16
+ let compiler: PlatformCssApi | undefined
17
+ let ssr = false
18
+ const adapted = new WeakSet<Plugin>()
19
+
20
+ return {
21
+ name: 'xplat-bamboo:platform-output',
22
+ enforce: 'post',
23
+ configResolved(config) {
24
+ ssr = Boolean(config.build.ssr)
25
+ compiler = config.plugins.find((plugin) => plugin.name === 'xplat-platform-css')?.api
26
+ if (config.command === 'build') {
27
+ compiler?.defer('virtual:bamboo.css')
28
+ }
29
+ },
30
+ transform: {
31
+ order: 'pre',
32
+ handler(code, id) {
33
+ if (!id.split('?')[0].endsWith('virtual:bamboo.css') || !code.includes('@platform')) {
34
+ return
35
+ }
36
+
37
+ if (!compiler) {
38
+ this.error(
39
+ '@octane-xplat/bamboo: platform conditions require xplatCss(target) from @octane-xplat/cli/vite',
40
+ )
41
+ }
42
+
43
+ if (ssr || this.environment?.config.build.ssr) {
44
+ this.error(
45
+ '@octane-xplat/bamboo: platform conditions currently require a single renderer build; SSR generation is not supported',
46
+ )
47
+ }
48
+ },
49
+ },
50
+ options: {
51
+ order: 'post',
52
+ handler(input) {
53
+ const outputs = (
54
+ input as typeof input & { output?: { plugins?: Plugin[] } | { plugins?: Plugin[] }[] }
55
+ ).output
56
+
57
+ for (const output of Array.isArray(outputs) ? outputs : outputs ? [outputs] : []) {
58
+ for (const plugin of (output.plugins ?? []).flat(Infinity) as Plugin[]) {
59
+ if (!plugin?.name?.startsWith('bamboocss:output-finalizer:') || adapted.has(plugin)) {
60
+ continue
61
+ }
62
+
63
+ const hook = plugin.generateBundle
64
+ const handler = typeof hook === 'function' ? hook : hook?.handler
65
+
66
+ if (!handler) {
67
+ throw new Error(
68
+ '@octane-xplat/bamboo: output finalizer has no generateBundle handler',
69
+ )
70
+ }
71
+
72
+ plugin.generateBundle = {
73
+ ...(typeof hook === 'object' ? hook : {}),
74
+ async handler(options, bundle, isWrite) {
75
+ await handler.call(this, options, bundle, isWrite)
76
+ if (!compiler) {
77
+ return
78
+ }
79
+
80
+ const renamed = new Map<string, string>()
81
+
82
+ for (const [key, asset] of Object.entries(bundle)) {
83
+ if (asset.type !== 'asset' || !asset.fileName.endsWith('.css')) {
84
+ continue
85
+ }
86
+
87
+ const source =
88
+ typeof asset.source === 'string'
89
+ ? asset.source
90
+ : new TextDecoder().decode(asset.source)
91
+
92
+ const mapKey = `${asset.fileName}.map`
93
+ const mapAsset = bundle[mapKey]
94
+ const previousMap =
95
+ mapAsset?.type === 'asset' ? String(mapAsset.source) : undefined
96
+
97
+ if (!compiler.hasPlatformConditions(source)) {
98
+ continue
99
+ }
100
+
101
+ const projected = compiler.project(source, asset.fileName, previousMap)
102
+ let filtered = projected.css
103
+
104
+ if (filtered === source) {
105
+ continue
106
+ }
107
+
108
+ const hash = createHash('sha256').update(filtered).digest('hex').slice(0, 16)
109
+ const next = asset.fileName.replace(/\.css$/, `.platform-${hash}.css`)
110
+
111
+ renamed.set(asset.fileName, next)
112
+ if (projected.map && previousMap) {
113
+ const nextMap = `${next}.map`
114
+ const map = JSON.parse(projected.map)
115
+
116
+ map.file = posix.basename(next)
117
+ this.emitFile({ type: 'asset', fileName: nextMap, source: JSON.stringify(map) })
118
+ delete bundle[mapKey]
119
+ filtered += `
109
120
  /*# sourceMappingURL=${posix.basename(nextMap)} */`
110
- }
111
-
112
- this.emitFile({ type: 'asset', fileName: next, source: filtered })
113
- delete bundle[key]
114
- }
115
- for (const file of Object.values(bundle)) {
116
- const replace = (text: string) => {
117
- for (const [old, next] of renamed) {
118
- text = text.split(old).join(next)
119
- const directory = posix.dirname(file.fileName)
120
- text = text
121
- .split(posix.relative(directory, old))
122
- .join(posix.relative(directory, next))
123
- }
124
- return text
125
- }
126
-
127
- if (file.type === 'chunk') {
128
- const nextCode = replace(file.code)
129
- if (nextCode !== file.code) {
130
- const magic = new MagicString(file.code)
131
- const replacements = new Map(renamed)
132
- for (const [old, next] of renamed) {
133
- replacements.set(
134
- posix.relative(posix.dirname(file.fileName), old),
135
- posix.relative(posix.dirname(file.fileName), next),
136
- )
137
- }
138
-
139
- // Scan the original code once so overlapping full/relative names
140
- // cannot apply two edits to the same source-map span.
141
- for (let index = 0; index < file.code.length; index++) {
142
- const found = [...replacements].find(([old]) =>
143
- file.code.startsWith(old, index),
144
- )
145
-
146
- if (!found) {
147
- continue
148
- }
149
-
150
- magic.overwrite(index, index + found[0].length, found[1])
151
- index += found[0].length - 1
152
- }
153
-
154
- file.code = magic.toString()
155
- if (file.map) {
156
- const combined = remapping(
157
- [
158
- magic.generateMap({ source: file.fileName, hires: 'boundary' }),
159
- file.map,
160
- ] as never,
161
- () => null,
162
- )
163
-
164
- const encoded = combined.toString()
165
- file.map = Object.assign(combined, {
166
- toUrl: () =>
167
- `data:application/json;charset=utf-8;base64,${Buffer.from(encoded).toString('base64')}`,
168
- }) as typeof file.map
169
-
170
- const mapFile = bundle[`${file.fileName}.map`]
171
- if (mapFile?.type === 'asset') {
172
- mapFile.source = encoded
173
- }
174
-
175
- if (file.code.includes('//# sourceMappingURL=data:')) {
176
- file.code =
177
- file.code.replace(
178
- /\n?\/\/# sourceMappingURL=data:application\/json[^\n]*$/,
179
- '',
180
- ) +
181
- `
121
+ }
122
+
123
+ this.emitFile({ type: 'asset', fileName: next, source: filtered })
124
+ delete bundle[key]
125
+ }
126
+
127
+ for (const file of Object.values(bundle)) {
128
+ const replace = (text: string) => {
129
+ for (const [old, next] of renamed) {
130
+ text = text.split(old).join(next)
131
+
132
+ const directory = posix.dirname(file.fileName)
133
+
134
+ text = text
135
+ .split(posix.relative(directory, old))
136
+ .join(posix.relative(directory, next))
137
+ }
138
+
139
+ return text
140
+ }
141
+
142
+ if (file.type === 'chunk') {
143
+ const nextCode = replace(file.code)
144
+
145
+ if (nextCode !== file.code) {
146
+ const magic = new MagicString(file.code)
147
+ const replacements = new Map(renamed)
148
+
149
+ for (const [old, next] of renamed) {
150
+ replacements.set(
151
+ posix.relative(posix.dirname(file.fileName), old),
152
+ posix.relative(posix.dirname(file.fileName), next),
153
+ )
154
+ }
155
+
156
+ // Scan the original code once so overlapping full/relative names
157
+ // cannot apply two edits to the same source-map span.
158
+ for (let index = 0; index < file.code.length; index++) {
159
+ const found = [...replacements].find(([old]) =>
160
+ file.code.startsWith(old, index),
161
+ )
162
+
163
+ if (!found) {
164
+ continue
165
+ }
166
+
167
+ magic.overwrite(index, index + found[0].length, found[1])
168
+ index += found[0].length - 1
169
+ }
170
+
171
+ file.code = magic.toString()
172
+ if (file.map) {
173
+ const combined = remapping(
174
+ [
175
+ magic.generateMap({ source: file.fileName, hires: 'boundary' }),
176
+ file.map,
177
+ ] as never,
178
+ () => null,
179
+ )
180
+
181
+ const encoded = combined.toString()
182
+
183
+ file.map = Object.assign(combined, {
184
+ toUrl: () =>
185
+ `data:application/json;charset=utf-8;base64,${Buffer.from(encoded).toString('base64')}`,
186
+ }) as typeof file.map
187
+
188
+ const mapFile = bundle[`${file.fileName}.map`]
189
+
190
+ if (mapFile?.type === 'asset') {
191
+ mapFile.source = encoded
192
+ }
193
+
194
+ if (file.code.includes('//# sourceMappingURL=data:')) {
195
+ file.code =
196
+ file.code.replace(
197
+ /\n?\/\/# sourceMappingURL=data:application\/json[^\n]*$/,
198
+ '',
199
+ ) +
200
+ `
182
201
  //# sourceMappingURL=${file.map.toUrl()}`
183
- }
184
- }
185
- }
186
-
187
- const refs = file as typeof file & { referencedFiles?: string[] }
188
- if (refs.referencedFiles) {
189
- refs.referencedFiles = refs.referencedFiles.map(replace)
190
- }
191
-
192
- const metadata = (
193
- file as typeof file & { viteMetadata?: { importedCss?: Set<string> } }
194
- ).viteMetadata
195
-
196
- if (metadata?.importedCss) {
197
- metadata.importedCss = new Set([...metadata.importedCss].map(replace))
198
- }
199
- } else if (typeof file.source === 'string') {
200
- file.source = replace(file.source)
201
- }
202
- }
203
- },
204
- }
205
-
206
- adapted.add(plugin)
207
- }
208
- }
209
- },
210
- },
211
- }
202
+ }
203
+ }
204
+ }
205
+
206
+ const refs = file as typeof file & { referencedFiles?: string[] }
207
+
208
+ if (refs.referencedFiles) {
209
+ refs.referencedFiles = refs.referencedFiles.map(replace)
210
+ }
211
+
212
+ const metadata = (
213
+ file as typeof file & { viteMetadata?: { importedCss?: Set<string> } }
214
+ ).viteMetadata
215
+
216
+ if (metadata?.importedCss) {
217
+ metadata.importedCss = new Set([...metadata.importedCss].map(replace))
218
+ }
219
+ } else if (typeof file.source === 'string') {
220
+ file.source = replace(file.source)
221
+ }
222
+ }
223
+ },
224
+ }
225
+
226
+ adapted.add(plugin)
227
+ }
228
+ }
229
+ },
230
+ },
231
+ }
212
232
  }
package/src/vite.ts CHANGED
@@ -4,25 +4,26 @@ import { buildEnvironments as adaptBuildEnvironments } from './build-environment
4
4
  import { platformOutput } from './platform-output.ts'
5
5
 
6
6
  function runBeforeNativeCss(plugin: Plugin | undefined, anchor: string) {
7
- const hook = plugin?.generateBundle
8
- if (plugin && typeof hook === 'function') {
9
- plugin.generateBundle = { order: 'pre', handler: hook }
10
- } else if (hook && typeof hook === 'object' && typeof hook.handler === 'function') {
11
- hook.order = 'pre'
12
- } else {
13
- throw new Error(
14
- `@octane-xplat/bamboo: native CSS adaptation requires ${anchor} with a generateBundle handler`,
15
- )
16
- }
7
+ const hook = plugin?.generateBundle
8
+
9
+ if (plugin && typeof hook === 'function') {
10
+ plugin.generateBundle = { order: 'pre', handler: hook }
11
+ } else if (hook && typeof hook === 'object' && typeof hook.handler === 'function') {
12
+ hook.order = 'pre'
13
+ } else {
14
+ throw new Error(
15
+ `@octane-xplat/bamboo: native CSS adaptation requires ${anchor} with a generateBundle handler`,
16
+ )
17
+ }
17
18
  }
18
19
 
19
20
  export interface XplatBambooOptions extends BambooVitePluginOptions {
20
- /** Native CSS delivery — NativeScript's generateBundle serializer and the
21
- * desktop `xplatInlineStylesheets` plugin both consume the finalized assets
22
- * after this 'pre' finalizer. */
23
- native?: boolean
24
- /** All environments the custom Vite builder will run, including real SSR targets. */
25
- buildEnvironments?: readonly string[]
21
+ /** Native CSS delivery — NativeScript's generateBundle serializer and the
22
+ * desktop `xplatInlineStylesheets` plugin both consume the finalized assets
23
+ * after this 'pre' finalizer. */
24
+ native?: boolean
25
+ /** All environments the custom Vite builder will run, including real SSR targets. */
26
+ buildEnvironments?: readonly string[]
26
27
  }
27
28
 
28
29
  /**
@@ -32,99 +33,102 @@ export interface XplatBambooOptions extends BambooVitePluginOptions {
32
33
  * Vite's app root, as it does in the shared harness.
33
34
  */
34
35
  export function xplatBamboo({
35
- native = false,
36
- buildEnvironments,
37
- ...options
36
+ native = false,
37
+ buildEnvironments,
38
+ ...options
38
39
  }: XplatBambooOptions = {}) {
39
- const plugins = bamboocss(options)
40
- if (buildEnvironments) {
41
- adaptBuildEnvironments(plugins, buildEnvironments)
42
- }
43
-
44
- if (native) {
45
- // Let Bamboo prune and validate the emitted asset before NativeScript's
46
- // main-entry hook serializes it into the native bootstrap and removes it.
47
- const cssPlugin = plugins.find((plugin) => plugin.name === 'bamboocss:css')
48
- runBeforeNativeCss(cssPlugin, 'bamboocss:css')
49
-
50
- let isBuild = false
51
- plugins.push({
52
- name: 'xplat-bamboo:nativescript-entry-graph',
53
- enforce: 'post',
54
- configResolved(config) {
55
- isBuild = config.command === 'build'
56
- },
57
- buildEnd(error) {
58
- if (!isBuild || error) {
59
- return
60
- }
61
-
62
- // Inspect the graph, including cached modules in watch builds. A
63
- // custom entry that already imports the sheet needs no injection.
64
- if (![...this.getModuleIds()].some((id) => id.split('?')[0] === '\0virtual:bamboo.css')) {
65
- this.error(
66
- '@octane-xplat/bamboo: native entry graph is missing virtual:bamboo.css; expected virtual:entry-with-polyfills or an explicit stylesheet import',
67
- )
68
- }
69
- },
70
- transform(code, id) {
71
- // @nativescript/vite builds from a generated entry
72
- // (`virtual:entry-with-polyfills`). Under HMR that entry boots
73
- // the app over HTTP instead of statically importing the app's
74
- // main module, so `import 'virtual:bamboo.css'` there never
75
- // enters the bundle's module graph — while class values still
76
- // compile, tripping bamboocss's entry-graph check at buildEnd.
77
- // Import the stylesheet from the generated entry itself so it
78
- // is in the graph in every mode; the emitted asset then flows
79
- // through the same generateBundle path as every other .css.
80
- if (id !== '\0virtual:entry-with-polyfills' || code.includes('virtual:bamboo.css')) {
81
- return
82
- }
83
-
84
- return { code: `${code}\nimport 'virtual:bamboo.css';\n`, map: null }
85
- },
86
- })
87
-
88
- plugins.push({
89
- name: 'xplat-bamboo:nativescript-output',
90
- enforce: 'post',
91
- options: {
92
- order: 'post',
93
- handler(inputOptions) {
94
- const options = inputOptions as typeof inputOptions & {
95
- output?: { plugins?: Plugin[] } | Array<{ plugins?: Plugin[] }>
96
- }
97
-
98
- const outputs = Array.isArray(options.output)
99
- ? options.output
100
- : options.output
101
- ? [options.output]
102
- : []
103
-
104
- // Upstream installs one finalizer per configured output. With no
105
- // output configured its options hook deliberately installs none.
106
- for (const output of outputs) {
107
- const finalizers = (output.plugins ?? [])
108
- .flat(Infinity)
109
- .filter((plugin): plugin is Plugin =>
110
- Boolean(plugin && plugin.name?.startsWith('bamboocss:output-finalizer:')),
111
- )
112
-
113
- if (!finalizers.length) {
114
- throw new Error(
115
- '@octane-xplat/bamboo: native CSS adaptation requires a bamboocss:output-finalizer:* plugin for each configured output',
116
- )
117
- }
118
-
119
- for (const finalizer of finalizers) {
120
- runBeforeNativeCss(finalizer, finalizer.name)
121
- }
122
- }
123
- },
124
- },
125
- })
126
- }
127
-
128
- plugins.push(platformOutput())
129
- return plugins
40
+ const plugins = bamboocss(options)
41
+
42
+ if (buildEnvironments) {
43
+ adaptBuildEnvironments(plugins, buildEnvironments)
44
+ }
45
+
46
+ if (native) {
47
+ // Let Bamboo prune and validate the emitted asset before NativeScript's
48
+ // main-entry hook serializes it into the native bootstrap and removes it.
49
+ const cssPlugin = plugins.find((plugin) => plugin.name === 'bamboocss:css')
50
+
51
+ runBeforeNativeCss(cssPlugin, 'bamboocss:css')
52
+
53
+ let isBuild = false
54
+
55
+ plugins.push({
56
+ name: 'xplat-bamboo:nativescript-entry-graph',
57
+ enforce: 'post',
58
+ configResolved(config) {
59
+ isBuild = config.command === 'build'
60
+ },
61
+ buildEnd(error) {
62
+ if (!isBuild || error) {
63
+ return
64
+ }
65
+
66
+ // Inspect the graph, including cached modules in watch builds. A
67
+ // custom entry that already imports the sheet needs no injection.
68
+ if (![...this.getModuleIds()].some((id) => id.split('?')[0] === '\0virtual:bamboo.css')) {
69
+ this.error(
70
+ '@octane-xplat/bamboo: native entry graph is missing virtual:bamboo.css; expected virtual:entry-with-polyfills or an explicit stylesheet import',
71
+ )
72
+ }
73
+ },
74
+ transform(code, id) {
75
+ // @nativescript/vite builds from a generated entry
76
+ // (`virtual:entry-with-polyfills`). Under HMR that entry boots
77
+ // the app over HTTP instead of statically importing the app's
78
+ // main module, so `import 'virtual:bamboo.css'` there never
79
+ // enters the bundle's module graph — while class values still
80
+ // compile, tripping bamboocss's entry-graph check at buildEnd.
81
+ // Import the stylesheet from the generated entry itself so it
82
+ // is in the graph in every mode; the emitted asset then flows
83
+ // through the same generateBundle path as every other .css.
84
+ if (id !== '\0virtual:entry-with-polyfills' || code.includes('virtual:bamboo.css')) {
85
+ return
86
+ }
87
+
88
+ return { code: `${code}\nimport 'virtual:bamboo.css';\n`, map: null }
89
+ },
90
+ })
91
+
92
+ plugins.push({
93
+ name: 'xplat-bamboo:nativescript-output',
94
+ enforce: 'post',
95
+ options: {
96
+ order: 'post',
97
+ handler(inputOptions) {
98
+ const options = inputOptions as typeof inputOptions & {
99
+ output?: { plugins?: Plugin[] } | Array<{ plugins?: Plugin[] }>
100
+ }
101
+
102
+ const outputs = Array.isArray(options.output)
103
+ ? options.output
104
+ : options.output
105
+ ? [options.output]
106
+ : []
107
+
108
+ // Upstream installs one finalizer per configured output. With no
109
+ // output configured its options hook deliberately installs none.
110
+ for (const output of outputs) {
111
+ const finalizers = (output.plugins ?? [])
112
+ .flat(Infinity)
113
+ .filter((plugin): plugin is Plugin =>
114
+ Boolean(plugin && plugin.name?.startsWith('bamboocss:output-finalizer:')),
115
+ )
116
+
117
+ if (!finalizers.length) {
118
+ throw new Error(
119
+ '@octane-xplat/bamboo: native CSS adaptation requires a bamboocss:output-finalizer:* plugin for each configured output',
120
+ )
121
+ }
122
+
123
+ for (const finalizer of finalizers) {
124
+ runBeforeNativeCss(finalizer, finalizer.name)
125
+ }
126
+ }
127
+ },
128
+ },
129
+ })
130
+ }
131
+
132
+ plugins.push(platformOutput())
133
+ return plugins
130
134
  }