@panomc/plugin-kit 0.0.0-stage → 1.0.0-dev.62

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.
Files changed (89) hide show
  1. package/assets/pano-bootstrap.css +17903 -0
  2. package/bin/__tests__/new/e2e.test.js +111 -0
  3. package/bin/__tests__/new/helpers.js +76 -0
  4. package/bin/__tests__/new/new.test.js +472 -0
  5. package/bin/new.js +530 -0
  6. package/bin/pano-plugin.js +162 -0
  7. package/bin/templates/plugin/README.md +30 -0
  8. package/bin/templates/plugin/_gitignore +15 -0
  9. package/bin/templates/plugin/build.gradle.kts +389 -0
  10. package/bin/templates/plugin/gradle/wrapper/gradle-wrapper.jar +0 -0
  11. package/bin/templates/plugin/gradle/wrapper/gradle-wrapper.properties +7 -0
  12. package/bin/templates/plugin/gradle.properties +55 -0
  13. package/bin/templates/plugin/gradlew +249 -0
  14. package/bin/templates/plugin/gradlew.bat +92 -0
  15. package/bin/templates/plugin/package.json.tpl +14 -0
  16. package/bin/templates/plugin/rollup.config.js +2 -0
  17. package/bin/templates/plugin/settings.gradle.kts +5 -0
  18. package/bin/templates/plugin/src/main/kotlin/__PKGPATH__/__CLASS__Plugin.kt +50 -0
  19. package/bin/templates/plugin/src/main/kotlin/__PKGPATH__/frontend/ExampleFallbackPage.kt +28 -0
  20. package/bin/templates/plugin/src/main/kotlin/__PKGPATH__/routes/GetHelloAPI.kt +19 -0
  21. package/bin/templates/plugin/src/main/kotlin/com/panomc/plugins/license/LicenseGuard.kt +30 -0
  22. package/bin/templates/plugin/src/main/kotlin/com/panomc/plugins/license/PluginLicenseClient.kt +144 -0
  23. package/bin/templates/plugin/src/main/resources/config.conf +1 -0
  24. package/bin/templates/plugin/src/main/resources/frontend-targets.json +1 -0
  25. package/bin/templates/plugin/src/main/resources/locales/en-US.json +3 -0
  26. package/bin/templates/plugin/src/main/resources/logo.png +0 -0
  27. package/bin/templates/plugin/src/theme/views/HelloPage.svelte +26 -0
  28. package/bin/ui.js +96 -0
  29. package/package.json +48 -4
  30. package/src/config.js +191 -0
  31. package/src/controller/__tests__/controller.test.js +647 -0
  32. package/src/controller/index.js +604 -0
  33. package/src/dev.js +208 -0
  34. package/src/index.js +22 -0
  35. package/src/rollup/__tests__/controllers/controllers.test.js +418 -0
  36. package/src/rollup/__tests__/controllers/fixture.js +143 -0
  37. package/src/rollup/__tests__/controllers/golden/controllers.json +34 -0
  38. package/src/rollup/__tests__/controllers/golden/controllers.types.js +69 -0
  39. package/src/rollup/__tests__/controllers/golden/pano-plugin.json +16 -0
  40. package/src/rollup/__tests__/controllers/golden/pano-plugin.lock.json +27 -0
  41. package/src/rollup/__tests__/controllers/golden/pano-plugin.with-views.json +54 -0
  42. package/src/rollup/__tests__/preset/preset.test.js +418 -0
  43. package/src/rollup/__tests__/rules/_build.js +39 -0
  44. package/src/rollup/__tests__/rules/_fixture.js +83 -0
  45. package/src/rollup/__tests__/rules/helpers.test.js +148 -0
  46. package/src/rollup/__tests__/rules/rules.test.js +259 -0
  47. package/src/rollup/__tests__/rules/stamp.test.js +113 -0
  48. package/src/rollup/__tests__/samples/samples.test.js +481 -0
  49. package/src/rollup/__tests__/seams/config.test.js +78 -0
  50. package/src/rollup/__tests__/seams/lock.test.js +124 -0
  51. package/src/rollup/__tests__/seams/sdk-seams.test.js +93 -0
  52. package/src/rollup/__tests__/seams/stubs.test.js +52 -0
  53. package/src/rollup/__tests__/views/helpers.js +82 -0
  54. package/src/rollup/__tests__/views/views.test.js +522 -0
  55. package/src/rollup/__tests__/widgets/helpers.js +117 -0
  56. package/src/rollup/__tests__/widgets/widgets.test.js +422 -0
  57. package/src/rollup/cli-build.js +90 -0
  58. package/src/rollup/cli-check.js +280 -0
  59. package/src/rollup/cli-classes.js +75 -0
  60. package/src/rollup/client-gen.js +67 -0
  61. package/src/rollup/controllers.js +434 -0
  62. package/src/rollup/entry.js +250 -0
  63. package/src/rollup/helpers.js +193 -0
  64. package/src/rollup/index.js +601 -0
  65. package/src/rollup/integrate.js +205 -0
  66. package/src/rollup/lock.js +230 -0
  67. package/src/rollup/meta.js +479 -0
  68. package/src/rollup/rules.js +950 -0
  69. package/src/rollup/samples.js +667 -0
  70. package/src/rollup/stamp.js +410 -0
  71. package/src/rollup/types.js +248 -0
  72. package/src/rollup/views.js +1205 -0
  73. package/src/rollup/widgets.js +1000 -0
  74. package/src/styles/__tests__/fallback/__snapshots__/build-fallback-css.test.js.snap +173 -0
  75. package/src/styles/__tests__/fallback/build-fallback-css.test.js +526 -0
  76. package/src/styles/__tests__/fallback/fixtures/base.css +247 -0
  77. package/src/styles/__tests__/fallback/plugins.test.js +301 -0
  78. package/src/styles/__tests__/lint/check-styles.test.js +423 -0
  79. package/src/styles/__tests__/lint/fixtures/ProductCard.golden.svelte +13 -0
  80. package/src/styles/__tests__/lint/fixtures/ProductCard.in.svelte +13 -0
  81. package/src/styles/__tests__/lint/semantic-classes.test.js +364 -0
  82. package/src/styles/bootstrap-classes.js +155 -0
  83. package/src/styles/check-styles.js +626 -0
  84. package/src/styles/fallback-css.js +1182 -0
  85. package/src/styles/plugin-css.js +237 -0
  86. package/src/styles/scan.js +206 -0
  87. package/src/styles/semantic-classes.js +436 -0
  88. package/src/styles/tokens.map.js +53 -0
  89. package/README.md +0 -3
@@ -0,0 +1,418 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { rollup } from 'rollup';
7
+ import { panoPlugin } from '../../index.js';
8
+ import { spawnSync } from 'node:child_process';
9
+ import { createRequire } from 'node:module';
10
+ import { pathToFileURL } from 'node:url';
11
+ import {
12
+ controllersModuleSource,
13
+ listControllerFiles,
14
+ wrapperSource,
15
+ } from '../../entry.js';
16
+
17
+ const here = path.dirname(fileURLToPath(import.meta.url));
18
+ const themeCore = path.resolve(here, '../../../../../..');
19
+ const fixture = path.join(themeCore, 'test-fixtures/plugin-min');
20
+ const sdkDir = path.join(themeCore, 'packages/sdk');
21
+
22
+ /** @type {string} */
23
+ let out;
24
+ /** @type {string | undefined} */
25
+ let previousSdkDir;
26
+
27
+ beforeAll(() => {
28
+ out = fs.mkdtempSync(path.join(os.tmpdir(), 'pano-preset-'));
29
+ previousSdkDir = process.env.PANO_SDK_DIR;
30
+ process.env.PANO_SDK_DIR = sdkDir;
31
+ });
32
+
33
+ afterAll(() => {
34
+ if (previousSdkDir === undefined) delete process.env.PANO_SDK_DIR;
35
+ else process.env.PANO_SDK_DIR = previousSdkDir;
36
+
37
+ fs.rmSync(out, { recursive: true, force: true });
38
+ });
39
+
40
+ /** Stand-in for panoViews() (a later unit): `pano:views` imports the fixture's one view. */
41
+ function viewsStandIn() {
42
+ const id = '\0test-views';
43
+
44
+ return {
45
+ name: 'test-views',
46
+ resolveId: (source) => (source === 'pano:views' ? id : null),
47
+ load: (loadId) =>
48
+ loadId === id
49
+ ? `import HelloPage from ${JSON.stringify(path.join(fixture, 'src/theme/views/HelloPage.svelte'))};\n` +
50
+ `export default [{ name: 'min:HelloPage', component: () => Promise.resolve({ default: HelloPage }) }];\n`
51
+ : null,
52
+ };
53
+ }
54
+
55
+ /**
56
+ * @param {Parameters<typeof panoPlugin>[0]} options
57
+ * @returns {Promise<import('rollup').RollupOptions[]>}
58
+ */
59
+ function configs(options = {}) {
60
+ return panoPlugin({ root: fixture, outDir: out, minify: false, ...options });
61
+ }
62
+
63
+ /** Builds every config and returns the written files by relative path. */
64
+ async function build(options = {}) {
65
+ for (const config of await configs(options)) {
66
+ const bundle = await rollup(config);
67
+
68
+ await bundle.write(/** @type {any} */ (config.output));
69
+ await bundle.close();
70
+ }
71
+
72
+ /** @type {Record<string, string>} */
73
+ const files = {};
74
+ const walk = (dir) => {
75
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
76
+ const file = path.join(dir, entry.name);
77
+
78
+ if (entry.isDirectory()) walk(file);
79
+ else files[path.relative(out, file)] = fs.readFileSync(file, 'utf8');
80
+ }
81
+ };
82
+
83
+ walk(out);
84
+
85
+ return files;
86
+ }
87
+
88
+ describe('panoPlugin() on the plugin-min fixture', () => {
89
+ test('returns client, server and controllers builds (no widgets without a widget view); the client build carries the cleaner', async () => {
90
+ const list = await configs();
91
+
92
+ expect(list.map((config) => path.relative(out, /** @type {any} */ (config.output).dir))).toEqual([
93
+ 'client',
94
+ 'server',
95
+ 'controllers',
96
+ ]);
97
+ expect(list.map((config) => /** @type {any} */ (config.output).entryFileNames)).toEqual([
98
+ 'client.mjs',
99
+ 'server.mjs',
100
+ 'controllers.mjs',
101
+ ]);
102
+ expect(list.map((config) => (config.plugins ?? []).some((plugin) => plugin && plugin.name === 'delete'))).toEqual([
103
+ true,
104
+ false,
105
+ false,
106
+ ]);
107
+ });
108
+
109
+ test('side picks one build; an unknown side is refused', async () => {
110
+ expect((await configs({ side: 'client' })).length).toBe(1);
111
+ expect((await configs({ side: 'server' })).length).toBe(1);
112
+ await expect(configs({ side: /** @type {any} */ ('panel') })).rejects.toThrow(/side/);
113
+ });
114
+
115
+ test('builds server and client bundles; the wrapper registers controllers before views, then onLoad', async () => {
116
+ const files = await build({ plugins: [viewsStandIn()] });
117
+
118
+ for (const entry of ['server/server.mjs', 'client/client.mjs', 'controllers/controllers.mjs']) {
119
+ expect(files[entry], entry).toBeDefined();
120
+ }
121
+
122
+ expect(JSON.parse(files['server/manifest.json'])).toContain('server.mjs');
123
+ expect(JSON.parse(files['client/manifest.json'])).toContain('client.mjs');
124
+
125
+ for (const side of ['server', 'client']) {
126
+ const main = Object.entries(files).find(
127
+ ([name]) => name.startsWith(`${side}/main-`) && name.endsWith('.js'),
128
+ );
129
+
130
+ expect(main, `${side} main chunk`).toBeDefined();
131
+
132
+ const code = main[1];
133
+ const controllers = code.indexOf('controllers?.register(pluginId, namespace, controllers)');
134
+ const views = code.indexOf('views?.add(views)');
135
+ const author = code.indexOf('super.onLoad');
136
+
137
+ expect(controllers).toBeGreaterThan(-1);
138
+ expect(views).toBeGreaterThan(controllers);
139
+ expect(author).toBeGreaterThan(views);
140
+ expect(code).toContain('panoSdk = 2');
141
+ expect(code).toContain('"pano-plugin-min"');
142
+ expect(code).toContain('"min"');
143
+ // the controller and its default export reached the bundle
144
+ expect(code).toContain('greeter');
145
+ }
146
+
147
+ // the facade is a pure re-export, with no state of its own
148
+ expect(files['client/client.mjs']).toMatch(/^export \{[^}]*\} from '\.\/main-[\w-]+\.js';/m);
149
+ expect(files['client/client.mjs']).not.toContain('class ');
150
+ });
151
+
152
+ test('client keeps the host specifiers external, server bundles them', async () => {
153
+ const files = await build({ plugins: [viewsStandIn()] });
154
+ const clientCode = Object.entries(files)
155
+ .filter(([name]) => name.startsWith('client/') && name.endsWith('.js'))
156
+ .map(([, code]) => code)
157
+ .join('\n');
158
+ const serverCode = Object.entries(files)
159
+ .filter(([name]) => name.startsWith('server/') && name.endsWith('.js'))
160
+ .map(([, code]) => code)
161
+ .join('\n');
162
+
163
+ expect(clientCode).toMatch(/from ['"]@panomc\/sdk['"]/);
164
+ expect(clientCode).toMatch(/from ['"]svelte\/internal\/client['"]/);
165
+ // the controller core is bundled, never an import of the host
166
+ expect(clientCode).not.toMatch(/from ['"]@panomc\/plugin-kit/);
167
+ expect(clientCode).toContain('function defineController');
168
+ expect(serverCode).not.toMatch(/from ['"]@panomc\/sdk['"]/);
169
+ expect(serverCode).not.toMatch(/from ['"]svelte/);
170
+ // the view helper was compiled into both bundles
171
+ expect(clientCode).toContain('Hello, ');
172
+ expect(serverCode).toContain('Hello, ');
173
+ });
174
+
175
+ test('without src/main.js the entry is a default class extending PanoPlugin', async () => {
176
+ expect(fs.existsSync(path.join(fixture, 'src/main.js'))).toBe(false);
177
+
178
+ const files = await build();
179
+ const main = Object.entries(files).find(([name]) => name.startsWith('client/main-'))[1];
180
+
181
+ expect(main).toContain('extends PanoPlugin');
182
+ });
183
+
184
+ test('the output folder is emptied by the first build', async () => {
185
+ const stale = path.join(out, 'stale.txt');
186
+
187
+ fs.writeFileSync(stale, 'x');
188
+ await build();
189
+ expect(fs.existsSync(stale)).toBe(false);
190
+ });
191
+
192
+ test('@panomc/sdk/plugin-api resolves to createPluginApi(<plugin id>) and is bundled, not external', async () => {
193
+ const probe = {
194
+ name: 'test-api-probe',
195
+ resolveId: (source) => (source === 'pano:views' ? '\0test-api-probe' : null),
196
+ load: (id) =>
197
+ id === '\0test-api-probe'
198
+ ? `import { api } from '@panomc/sdk/plugin-api';\nexport default [api];\n`
199
+ : null,
200
+ };
201
+ const list = await configs({ side: 'client', plugins: [probe] });
202
+ const bundle = await rollup(list[0]);
203
+ const { output } = await bundle.generate(/** @type {any} */ (list[0].output));
204
+ const code = output.map((chunk) => ('code' in chunk ? chunk.code : '')).join('\n');
205
+
206
+ expect(code).toContain('createPluginApi("pano-plugin-min")');
207
+ expect(code).toMatch(/from ['"]@panomc\/sdk\/utils\/api['"]/);
208
+ expect(code).not.toMatch(/from ['"]@panomc\/sdk\/plugin-api['"]/);
209
+ });
210
+
211
+ test('a svelte version that differs from the sdk pin fails the build', async () => {
212
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pano-preset-pin-'));
213
+
214
+ try {
215
+ const fakeSdk = path.join(dir, 'sdk');
216
+
217
+ fs.mkdirSync(path.join(fakeSdk, 'node_modules/svelte'), { recursive: true });
218
+ fs.writeFileSync(
219
+ path.join(fakeSdk, 'package.json'),
220
+ JSON.stringify({ name: '@panomc/sdk', dependencies: { svelte: '5.0.0' } }),
221
+ );
222
+ fs.writeFileSync(
223
+ path.join(fakeSdk, 'node_modules/svelte/package.json'),
224
+ JSON.stringify({ name: 'svelte', version: '5.1.0' }),
225
+ );
226
+
227
+ process.env.PANO_SDK_DIR = fakeSdk;
228
+
229
+ await expect(panoPlugin({ root: fixture })).rejects.toThrow(/requires exactly 5\.0\.0/);
230
+ } finally {
231
+ process.env.PANO_SDK_DIR = sdkDir;
232
+ fs.rmSync(dir, { recursive: true, force: true });
233
+ }
234
+ });
235
+ });
236
+
237
+ describe('pano:controllers and the wrapper source', () => {
238
+ test('lists every default export directly in the folder; _*.js, types.js and sub-folders are skipped', () => {
239
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pano-controllers-'));
240
+
241
+ try {
242
+ for (const name of ['cart.js', 'format.js', '_private.js', 'types.js', 'notes.txt']) {
243
+ fs.writeFileSync(path.join(dir, name), 'export default {};\n');
244
+ }
245
+
246
+ fs.mkdirSync(path.join(dir, 'nested'));
247
+ fs.writeFileSync(path.join(dir, 'nested/deep.js'), 'export default {};\n');
248
+
249
+ const files = listControllerFiles(dir);
250
+
251
+ expect(files.map((item) => item.name)).toEqual(['cart', 'format']);
252
+
253
+ const source = controllersModuleSource(files);
254
+
255
+ expect(source).toContain('"cart": controller0');
256
+ expect(source).toContain('"format": controller1');
257
+ expect(source).not.toContain('_private');
258
+ expect(source).not.toContain('types.js');
259
+ expect(source).not.toContain('deep');
260
+ expect(listControllerFiles(path.join(dir, 'missing'))).toEqual([]);
261
+ } finally {
262
+ fs.rmSync(dir, { recursive: true, force: true });
263
+ }
264
+ });
265
+
266
+ test('a controller file without a default export is a build error naming the file and the fix', async () => {
267
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pano-preset-nodefault-'));
268
+
269
+ try {
270
+ fs.cpSync(fixture, dir, { recursive: true });
271
+ fs.writeFileSync(path.join(dir, 'src/theme/controllers/broken.js'), 'export const x = 1;\n');
272
+
273
+ const list = await panoPlugin({ root: dir, outDir: path.join(dir, 'out'), minify: false, side: 'client' });
274
+
275
+ await expect(rollup(list[0])).rejects.toThrow(/broken\.js has no default export/);
276
+ } finally {
277
+ fs.rmSync(dir, { recursive: true, force: true });
278
+ }
279
+ });
280
+
281
+ test('the wrapper source calls controllers.register, then views.add, then the author onLoad', () => {
282
+ const source = wrapperSource({ pluginId: 'pano-plugin-min', namespace: 'min', mainId: '/x/src/main.js' });
283
+ const register = source.indexOf('this.pano?.controllers?.register(pluginId, namespace, controllers)');
284
+ const add = source.indexOf('this.pano?.views?.add(views)');
285
+ const author = source.indexOf('super.onLoad?.(...args)');
286
+
287
+ expect(register).toBeGreaterThan(-1);
288
+ expect(add).toBeGreaterThan(register);
289
+ expect(author).toBeGreaterThan(add);
290
+ expect(source).toContain('export const panoSdk = 2;');
291
+ expect(source).toContain('export default class extends Author');
292
+ });
293
+ });
294
+
295
+ describe('panoPlugin() default set and fallback scan', () => {
296
+ /** @param {Record<string, string>} files */
297
+ function copy(files = {}) {
298
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pano-preset-copy-'));
299
+
300
+ fs.cpSync(fixture, dir, {
301
+ recursive: true,
302
+ filter: (source) => !source.includes(`${path.sep}src${path.sep}main${path.sep}resources`),
303
+ });
304
+
305
+ // a copy outside the repo still resolves @panomc/plugin-kit/controller and the toolchain
306
+ fs.symlinkSync(path.join(themeCore, 'node_modules'), path.join(dir, 'node_modules'), 'dir');
307
+
308
+ for (const [file, content] of Object.entries(files)) {
309
+ fs.mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });
310
+ fs.writeFileSync(path.join(dir, file), content);
311
+ }
312
+
313
+ return dir;
314
+ }
315
+
316
+ /** @param {import('rollup').RollupOptions[]} list */
317
+ async function write(list) {
318
+ for (const config of list) {
319
+ const bundle = await rollup(config);
320
+
321
+ await bundle.write(/** @type {any} */ (config.output));
322
+ await bundle.close();
323
+ }
324
+ }
325
+
326
+ test('a class used only under a second view folder reaches fallback.css', async () => {
327
+ const dir = copy({
328
+ 'pano.plugin.js': "export default { viewDirs: ['src/theme/views', 'src/theme/extra'] };\n",
329
+ 'src/theme/extra/ExtraPage.svelte':
330
+ "<script module>\n export const view = { path: '/extra' };\n</script>\n\n<div class=\"alert alert-warning\">extra</div>\n",
331
+ });
332
+ const single = copy();
333
+
334
+ try {
335
+ await write(await panoPlugin({ root: dir, outDir: path.join(dir, 'out'), minify: false }));
336
+ await write(await panoPlugin({ root: single, outDir: path.join(single, 'out'), minify: false }));
337
+
338
+ const css = fs.readFileSync(path.join(dir, 'out/client/fallback.css'), 'utf8');
339
+ const base = fs.readFileSync(path.join(single, 'out/client/fallback.css'), 'utf8');
340
+
341
+ expect(css).toContain('alert-warning');
342
+ expect(base).not.toContain('alert-warning');
343
+ } finally {
344
+ fs.rmSync(dir, { recursive: true, force: true });
345
+ fs.rmSync(single, { recursive: true, force: true });
346
+ }
347
+ });
348
+
349
+ test('a widget view puts the widgets build in the default set, last and without the cleaner', async () => {
350
+ const widgets = path.join(themeCore, 'test-fixtures/plugin-widgets');
351
+ const list = await panoPlugin({ root: widgets, outDir: out, minify: false });
352
+ const dirs = list.map((config) => path.relative(out, /** @type {any} */ (config.output).dir));
353
+
354
+ expect(dirs[0]).toBe('client');
355
+ expect(dirs[dirs.length - 1]).toBe('widgets');
356
+ expect(dirs).toContain('server');
357
+
358
+ const cleaners = list.map((config) => (config.plugins ?? []).some((plugin) => plugin && plugin.name === 'delete'));
359
+
360
+ expect(cleaners).toEqual(list.map((_, index) => index === 0));
361
+ expect((await panoPlugin({ root: widgets, outDir: out, side: 'widgets' })).length).toBe(1);
362
+ });
363
+
364
+ test('a plain panoPlugin() emits widgets/widgets.json for a plugin with a widget view', async () => {
365
+ const widgets = path.join(themeCore, 'test-fixtures/plugin-widgets');
366
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pano-preset-widgets-'));
367
+
368
+ try {
369
+ fs.cpSync(widgets, dir, {
370
+ recursive: true,
371
+ filter: (source) => !source.includes(`${path.sep}src${path.sep}main${path.sep}resources`),
372
+ });
373
+ fs.symlinkSync(path.join(themeCore, 'node_modules'), path.join(dir, 'node_modules'), 'dir');
374
+ await write(await panoPlugin({ root: dir, outDir: path.join(dir, 'out'), minify: false }));
375
+
376
+ const json = JSON.parse(fs.readFileSync(path.join(dir, 'out/widgets/widgets.json'), 'utf8'));
377
+
378
+ expect(json.format).toBe(1);
379
+ expect(fs.existsSync(path.join(dir, 'out/client/client.mjs'))).toBe(true);
380
+ expect(fs.existsSync(path.join(dir, 'out/server/server.mjs'))).toBe(true);
381
+ } finally {
382
+ fs.rmSync(dir, { recursive: true, force: true });
383
+ }
384
+ });
385
+
386
+ test('the plugin-min build runs under Node (the ES build of the svelte compiler)', () => {
387
+ const rollupFile = pathToFileURL(createRequire(import.meta.url).resolve('rollup')).href;
388
+ const kitFile = pathToFileURL(path.join(here, '../../index.js')).href;
389
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pano-preset-node-'));
390
+ const script = `
391
+ const { rollup } = await import(${JSON.stringify(rollupFile)});
392
+ const { panoPlugin } = await import(${JSON.stringify(kitFile)});
393
+ for (const config of await panoPlugin({ root: ${JSON.stringify(fixture)}, outDir: ${JSON.stringify(path.join(dir, 'out'))}, minify: false })) {
394
+ const bundle = await rollup(config);
395
+ await bundle.write(config.output);
396
+ await bundle.close();
397
+ }
398
+ `;
399
+
400
+ try {
401
+ const file = path.join(dir, 'run.mjs');
402
+
403
+ fs.writeFileSync(file, script);
404
+
405
+ const result = spawnSync('node', [file], {
406
+ encoding: 'utf8',
407
+ env: { ...process.env, PANO_SDK_DIR: sdkDir },
408
+ });
409
+
410
+ expect(result.stderr, result.stderr).not.toContain('parse is not a function');
411
+ expect(result.status, result.stderr).toBe(0);
412
+ expect(fs.existsSync(path.join(dir, 'out/client/client.mjs'))).toBe(true);
413
+ expect(fs.existsSync(path.join(dir, 'out/server/server.mjs'))).toBe(true);
414
+ } finally {
415
+ fs.rmSync(dir, { recursive: true, force: true });
416
+ }
417
+ });
418
+ });
@@ -0,0 +1,39 @@
1
+ import { rollup } from "rollup";
2
+ import svelte from "rollup-plugin-svelte";
3
+ import path from "node:path";
4
+
5
+ /**
6
+ * Builds a fixture plugin's views into one ES bundle (client side) with the given kit plugins.
7
+ * The entry imports every `.svelte` file given in `views` and re-exports it.
8
+ *
9
+ * @param {string} root
10
+ * @param {string[]} views paths relative to root
11
+ * @param {import('rollup').Plugin[]} kit plugins that run after the Svelte compiler
12
+ * @param {{ onwarn?: (message: string) => void }} [options]
13
+ * @returns {Promise<{ code: string }>}
14
+ */
15
+ export async function buildViews(root, views, kit, options = {}) {
16
+ const entry = "\0entry";
17
+ const source = views
18
+ .map((view, index) => `export { default as V${index} } from ${JSON.stringify(path.join(root, view))};`)
19
+ .join("\n");
20
+
21
+ const bundle = await rollup({
22
+ input: entry,
23
+ external: [/^@panomc\//, /^svelte/],
24
+ onwarn: (warning) => options.onwarn?.(warning.message),
25
+ plugins: [
26
+ {
27
+ name: "test-entry",
28
+ resolveId: (id) => (id === entry ? entry : null),
29
+ load: (id) => (id === entry ? source : null),
30
+ },
31
+ svelte({ emitCss: false, compilerOptions: { generate: "client" } }),
32
+ ...kit,
33
+ ],
34
+ });
35
+
36
+ const { output } = await bundle.generate({ format: "es" });
37
+ await bundle.close();
38
+ return { code: output[0].code };
39
+ }
@@ -0,0 +1,83 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ /** @type {string[]} */
6
+ const created = [];
7
+
8
+ /**
9
+ * Writes a throw-away plugin folder from a `{ 'relative/path': 'content' }` map.
10
+ * The folder always has `gradle.properties` for `pano-plugin-market` (namespace `market`).
11
+ *
12
+ * @param {Record<string, string>} files
13
+ * @returns {string} absolute root
14
+ */
15
+ export function makePlugin(files) {
16
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "pano-kit-rules-"));
17
+ created.push(root);
18
+
19
+ const all = { "gradle.properties": "pluginId=pano-plugin-market\n", ...files };
20
+
21
+ for (const [relative, content] of Object.entries(all)) {
22
+ const file = path.join(root, relative);
23
+ fs.mkdirSync(path.dirname(file), { recursive: true });
24
+ fs.writeFileSync(file, content);
25
+ }
26
+
27
+ return root;
28
+ }
29
+
30
+ export function cleanup() {
31
+ for (const root of created.splice(0)) fs.rmSync(root, { recursive: true, force: true });
32
+ }
33
+
34
+ /**
35
+ * A view that is valid under every rule: used as the base of the fixtures.
36
+ */
37
+ export const GOOD_VIEW = `<script>
38
+ import { onMount } from "svelte";
39
+ import { _ } from "svelte-i18n";
40
+ import { api } from "@panomc/sdk";
41
+ import Child from "./Child.svelte";
42
+ import { sale } from "../lib/sale.js";
43
+ </script>
44
+ <div>{sale(1)}<Child /></div>
45
+ `;
46
+
47
+ export const GOOD_FILES = {
48
+ "src/theme/views/ProductCard.svelte": GOOD_VIEW,
49
+ "src/theme/views/Child.svelte": "<p>child</p>\n",
50
+ "src/theme/lib/sale.js": 'import { round } from "./round.js";\nexport const sale = (n) => round(n);\n',
51
+ "src/theme/lib/round.js": "export const round = (n) => Math.round(n);\n",
52
+ };
53
+
54
+ /**
55
+ * Runs a rollup plugin's `buildStart` the way rollup does, collecting errors and warnings.
56
+ *
57
+ * @param {import('rollup').Plugin} plugin
58
+ * @returns {Promise<{ error: Error | null, warnings: string[] }>}
59
+ */
60
+ export async function runBuildStart(plugin) {
61
+ /** @type {string[]} */
62
+ const warnings = [];
63
+ /** @type {Error | null} */
64
+ let error = null;
65
+
66
+ const context = {
67
+ warn: (/** @type {any} */ log) => warnings.push(typeof log === "string" ? log : log.message),
68
+ error: (/** @type {any} */ log) => {
69
+ throw new Error(typeof log === "string" ? log : log.message);
70
+ },
71
+ addWatchFile: () => {},
72
+ };
73
+
74
+ const hook = /** @type {any} */ (plugin.buildStart);
75
+
76
+ try {
77
+ await (typeof hook === "function" ? hook : hook.handler).call(context, {});
78
+ } catch (caught) {
79
+ error = /** @type {Error} */ (caught);
80
+ }
81
+
82
+ return { error, warnings };
83
+ }
@@ -0,0 +1,148 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { afterAll, describe, expect, test } from "bun:test";
4
+ import { rollup } from "rollup";
5
+ import svelte from "rollup-plugin-svelte";
6
+ import { panoHelpers, writeViewHelpers } from "../../helpers.js";
7
+ import { analyzeProject, panoRules, resolveProject } from "../../rules.js";
8
+ import { panoStamp } from "../../stamp.js";
9
+ import { cleanup, makePlugin } from "./_fixture.js";
10
+
11
+ afterAll(cleanup);
12
+
13
+ const CART = `import { defineController } from "@panomc/plugin-kit/controller";
14
+ export default defineController({ name: "cart", version: 1, state: () => ({}), actions: () => ({}) });
15
+ `;
16
+
17
+ const PRODUCT_CARD = `<script>
18
+ import { plugin } from "@panomc/sdk/controllers";
19
+ import { sale } from "../../lib/sale.js";
20
+ import Badge from "./Badge.svelte";
21
+
22
+ const cart = plugin("market").require("cart");
23
+ </script>
24
+ <div>{sale(2)}<Badge /></div>
25
+ `;
26
+
27
+ const FILES = {
28
+ "src/theme/components/store/ProductCard.svelte": PRODUCT_CARD,
29
+ "src/theme/components/store/Badge.svelte": "<b>badge</b>\n",
30
+ "src/theme/lib/sale.js": 'import { round } from "./util/round.js";\nexport const sale = (n) => round(n);\n',
31
+ "src/theme/lib/util/round.js": "export const round = (n) => Math.round(n);\n",
32
+ "src/theme/lib/unused.js": "export const unused = 1;\n",
33
+ "src/theme/controllers/cart.js": CART,
34
+ };
35
+
36
+ /**
37
+ * Stand-in for panoViews' readable copy: writes every view source to `contract/src/<path under its view folder>`.
38
+ *
39
+ * @param {string} root
40
+ * @param {string} outDir
41
+ */
42
+ function copyViews(root, outDir) {
43
+ return {
44
+ name: "test-views-copy",
45
+ writeBundle() {
46
+ const base = path.join(root, "src/theme/components");
47
+
48
+ for (const relative of ["store/ProductCard.svelte", "store/Badge.svelte"]) {
49
+ const target = path.join(outDir, "contract/src", relative);
50
+ fs.mkdirSync(path.dirname(target), { recursive: true });
51
+ fs.copyFileSync(path.join(base, relative), target);
52
+ }
53
+ },
54
+ };
55
+ }
56
+
57
+ describe("view helpers and the full rule set in one build", () => {
58
+ test("copies the helper closure readable, rewrites the readable view copy, stamps only the compiled output", async () => {
59
+ const root = makePlugin(FILES);
60
+ const outDir = path.join(root, "out");
61
+ const options = { root, viewDirs: ["src/theme/components"], outDir };
62
+ const helpers = panoHelpers(options);
63
+ const stamp = panoStamp(options);
64
+
65
+ const bundle = await rollup({
66
+ input: "\0entry",
67
+ external: [/^@panomc\//, /^svelte/],
68
+ plugins: [
69
+ {
70
+ name: "test-entry",
71
+ resolveId: (id) => (id === "\0entry" ? id : null),
72
+ load: (id) =>
73
+ id === "\0entry"
74
+ ? `export { default as ProductCard } from ${JSON.stringify(path.join(root, "src/theme/components/store/ProductCard.svelte"))};`
75
+ : null,
76
+ },
77
+ svelte({ emitCss: false }),
78
+ panoRules(options),
79
+ helpers,
80
+ stamp,
81
+ copyViews(root, outDir),
82
+ ],
83
+ });
84
+ await bundle.write({ dir: path.join(outDir, "client"), format: "es" });
85
+ await bundle.close();
86
+
87
+ const compiled = fs
88
+ .readdirSync(path.join(outDir, "client"))
89
+ .map((name) => fs.readFileSync(path.join(outDir, "client", name), "utf8"))
90
+ .join("\n");
91
+
92
+ // compiled output: stamped
93
+ expect(compiled).toContain('.require("cart", { version: 1 })');
94
+
95
+ // readable helpers: only the closure, path as under src/theme, unchanged
96
+ const lib = path.join(outDir, "contract/src/_lib");
97
+ expect(fs.readFileSync(path.join(lib, "lib/sale.js"), "utf8")).toBe(FILES["src/theme/lib/sale.js"]);
98
+ expect(fs.readFileSync(path.join(lib, "lib/util/round.js"), "utf8")).toBe(FILES["src/theme/lib/util/round.js"]);
99
+ expect(fs.existsSync(path.join(lib, "lib/unused.js"))).toBe(false);
100
+
101
+ // readable view copy: helper specifier rewritten, controller call unstamped, view import untouched
102
+ const copy = fs.readFileSync(path.join(outDir, "contract/src/store/ProductCard.svelte"), "utf8");
103
+ expect(copy).toContain('import { sale } from "../_lib/lib/sale.js";');
104
+ expect(copy).toContain('import Badge from "./Badge.svelte";');
105
+ expect(copy).toContain('plugin("market").require("cart");');
106
+ expect(copy).not.toContain("version");
107
+
108
+ // what pano-plugin.json needs
109
+ expect(helpers.api.helpers.get("ProductCard")).toEqual(["lib/sale.js", "lib/util/round.js"]);
110
+ expect(helpers.api.helpers.get("Badge")).toEqual([]);
111
+ expect(helpers.api.allHelpers).toEqual(["lib/sale.js", "lib/util/round.js"]);
112
+ expect(stamp.api.usage.get("ProductCard")).toEqual({ "market/cart": 1 });
113
+
114
+ // the rewritten copy resolves: the helper sits where the specifier says
115
+ expect(fs.existsSync(path.resolve(path.join(outDir, "contract/src/store"), "../_lib/lib/sale.js"))).toBe(true);
116
+ });
117
+
118
+ test("writing twice changes nothing (no reload loop in watch mode)", async () => {
119
+ const root = makePlugin(FILES);
120
+ const outDir = path.join(root, "out");
121
+ const project = await resolveProject({ root, viewDirs: ["src/theme/components"] });
122
+ const analysis = await analyzeProject(project);
123
+
124
+ copyViews(root, outDir).writeBundle();
125
+ const first = await writeViewHelpers(project, analysis, outDir);
126
+ const copy = path.join(outDir, "contract/src/store/ProductCard.svelte");
127
+ const after = fs.readFileSync(copy, "utf8");
128
+ const mtime = fs.statSync(path.join(outDir, "contract/src/_lib/lib/sale.js")).mtimeMs;
129
+
130
+ const second = await writeViewHelpers(project, analysis, outDir);
131
+
132
+ expect(first.rewritten).toEqual(["store/ProductCard.svelte"]);
133
+ expect(second.rewritten).toEqual([]);
134
+ expect(fs.readFileSync(copy, "utf8")).toBe(after);
135
+ expect(fs.statSync(path.join(outDir, "contract/src/_lib/lib/sale.js")).mtimeMs).toBe(mtime);
136
+ });
137
+
138
+ test("a plugin without helpers writes no _lib folder", async () => {
139
+ const root = makePlugin({ "src/theme/views/A.svelte": "<p />\n" });
140
+ const outDir = path.join(root, "out");
141
+ const project = await resolveProject({ root });
142
+
143
+ const result = await writeViewHelpers(project, await analyzeProject(project), outDir);
144
+
145
+ expect(result.copied).toEqual([]);
146
+ expect(fs.existsSync(path.join(outDir, "contract/src/_lib"))).toBe(false);
147
+ });
148
+ });