@prenta/cli 1.2.0 → 1.2.1
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/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +46 -38
- package/CHANGELOG.md +7 -0
- package/dist/commands/chrome.d.ts.map +1 -1
- package/dist/commands/chrome.js +3 -2
- package/dist/commands/chrome.js.map +1 -1
- package/dist/commands/migrate-meta.js +2 -2
- package/dist/commands/migrate-meta.js.map +1 -1
- package/dist/commands/migrate-schema.js +2 -2
- package/dist/commands/migrate-schema.js.map +1 -1
- package/dist/commands/seed.d.ts +25 -0
- package/dist/commands/seed.d.ts.map +1 -1
- package/dist/commands/seed.js +74 -7
- package/dist/commands/seed.js.map +1 -1
- package/dist/utils/import-typescript.d.ts +19 -1
- package/dist/utils/import-typescript.d.ts.map +1 -1
- package/dist/utils/import-typescript.js +56 -6
- package/dist/utils/import-typescript.js.map +1 -1
- package/dist/utils/load-project-config.js +2 -2
- package/dist/utils/load-project-config.js.map +1 -1
- package/package.json +2 -2
- package/src/__tests__/import-typescript-hooks.test.ts +37 -0
- package/src/__tests__/import-typescript.test.ts +46 -1
- package/src/__tests__/seed-sanitize.test.ts +160 -0
- package/src/__tests__/seed.test.ts +4 -0
- package/src/commands/chrome.ts +3 -2
- package/src/commands/migrate-meta.ts +2 -2
- package/src/commands/migrate-schema.ts +2 -2
- package/src/commands/seed.ts +96 -7
- package/src/utils/import-typescript.ts +58 -6
- package/src/utils/load-project-config.ts +2 -2
|
@@ -13,19 +13,69 @@ export function toProjectFileUrl(filePath) {
|
|
|
13
13
|
return filePath;
|
|
14
14
|
return pathToFileURL(path.resolve(filePath)).href;
|
|
15
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Install tsx's process-wide hooks once: the ESM loader and the CommonJS
|
|
18
|
+
* `require` hook.
|
|
19
|
+
*
|
|
20
|
+
* Both are needed. A scaffolded project has no `"type": "module"`, so Node
|
|
21
|
+
* classifies its `.ts` files as CommonJS. The ESM loader compiles the entry
|
|
22
|
+
* file (`generated/prisma/client.ts`), but that file's own imports then run as
|
|
23
|
+
* `require('./internal/class')`, and on Node 22 only the CommonJS hook can
|
|
24
|
+
* resolve an extensionless TypeScript sibling. Without it every command that
|
|
25
|
+
* opens the project database fails with "Cannot find module './internal/class'".
|
|
26
|
+
*/
|
|
27
|
+
async function registerTsx() {
|
|
28
|
+
if (registered)
|
|
29
|
+
return;
|
|
30
|
+
const [esm, cjs] = await Promise.all([import('tsx/esm/api'), import('tsx/cjs/api')]);
|
|
31
|
+
esm.register();
|
|
32
|
+
cjs.register();
|
|
33
|
+
registered = true;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The exports a loaded project module actually declared.
|
|
37
|
+
*
|
|
38
|
+
* A scaffolded project has no `"type": "module"`, so tsx compiles its
|
|
39
|
+
* TypeScript to CommonJS: `export default config` and `export const header`
|
|
40
|
+
* become `module.exports = { __esModule: true, default: config, header }`.
|
|
41
|
+
* Imported from this ESM CLI, that whole object arrives as the namespace's
|
|
42
|
+
* `default`, one level above what the file exported. Reading the namespace
|
|
43
|
+
* directly therefore finds `{ default: config }` where the config should be
|
|
44
|
+
* (an object with no collections, plugins or storage) and no named exports at
|
|
45
|
+
* all, so every command that loaded `prenta.config.ts` ran as if it were empty.
|
|
46
|
+
*/
|
|
47
|
+
export function projectModuleExports(mod) {
|
|
48
|
+
if (!mod || typeof mod !== 'object')
|
|
49
|
+
return {};
|
|
50
|
+
const namespace = mod;
|
|
51
|
+
const outer = namespace.default;
|
|
52
|
+
if (outer &&
|
|
53
|
+
typeof outer === 'object' &&
|
|
54
|
+
!Array.isArray(outer) &&
|
|
55
|
+
outer.__esModule === true) {
|
|
56
|
+
return outer;
|
|
57
|
+
}
|
|
58
|
+
return namespace;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The default export of a loaded project module, or the named export
|
|
62
|
+
* `fallbackName` when the file has no default.
|
|
63
|
+
*/
|
|
64
|
+
export function projectDefaultExport(mod, fallbackName) {
|
|
65
|
+
const exported = projectModuleExports(mod);
|
|
66
|
+
if (exported.default !== undefined)
|
|
67
|
+
return exported.default;
|
|
68
|
+
return fallbackName ? exported[fallbackName] : undefined;
|
|
69
|
+
}
|
|
16
70
|
/**
|
|
17
71
|
* Load a consumer TypeScript file (prenta.config.ts, lib/prisma.ts,
|
|
18
|
-
* generated/prisma/client.ts) via tsx's process-wide
|
|
72
|
+
* generated/prisma/client.ts) via tsx's process-wide hooks.
|
|
19
73
|
*
|
|
20
74
|
* Do not use `tsImport()` — its namespaced loader is what produced the
|
|
21
75
|
* Windows `?namespace=` crashes on adapter-pg and then enums.ts.
|
|
22
76
|
*/
|
|
23
77
|
export async function importProjectTypescript(filePath) {
|
|
24
|
-
|
|
25
|
-
const { register } = await import('tsx/esm/api');
|
|
26
|
-
register();
|
|
27
|
-
registered = true;
|
|
28
|
-
}
|
|
78
|
+
await registerTsx();
|
|
29
79
|
return import(toProjectFileUrl(filePath));
|
|
30
80
|
}
|
|
31
81
|
//# sourceMappingURL=import-typescript.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"import-typescript.js","sourceRoot":"","sources":["../../src/utils/import-typescript.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAExC,IAAI,UAAU,GAAG,KAAK,CAAA;AAEtB;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,QAAgB;IAC/C,IAAI,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC;QAAE,OAAO,QAAQ,CAAA;IACjD,OAAO,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAA;AACnD,CAAC;AAED
|
|
1
|
+
{"version":3,"file":"import-typescript.js","sourceRoot":"","sources":["../../src/utils/import-typescript.ts"],"names":[],"mappings":"A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AAoB,CAAC,GAAG,CAAC,CAAA;IAC1C,IAAI,QAAQ,CAAC,OAAO,KAAK,SAAS;QAAE,OAAO,QAAQ,CAAC,OAAO,CAAA;IAC3D,OAAO,YAAY,CAAC,CAAC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;AAC1D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,QAAgB;IAC5D,MAAM,WAAW,EAAE,CAAA;IACnB,OAAO,MAAM,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAA;AAC3C,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { resolve } from 'node:path';
|
|
2
|
-
import { importProjectTypescript } from './import-typescript.js';
|
|
2
|
+
import { importProjectTypescript, projectDefaultExport } from './import-typescript.js';
|
|
3
3
|
import { logger } from './logger.js';
|
|
4
4
|
/**
|
|
5
5
|
* Load `prenta.config.ts` and register its storage adapter so media commands
|
|
@@ -10,7 +10,7 @@ export async function loadProjectConfig(configPath) {
|
|
|
10
10
|
try {
|
|
11
11
|
const { setPrentaConfig, setStorageAdapter, autoWireStorageAdapter } = await import('@prenta/core');
|
|
12
12
|
const mod = (await importProjectTypescript(resolve(configPath)));
|
|
13
|
-
const config = mod
|
|
13
|
+
const config = projectDefaultExport(mod, 'config');
|
|
14
14
|
if (!config || typeof config !== 'object')
|
|
15
15
|
return;
|
|
16
16
|
setPrentaConfig(config);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-project-config.js","sourceRoot":"","sources":["../../src/utils/load-project-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AACnC,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAA;
|
|
1
|
+
{"version":3,"file":"load-project-config.js","sourceRoot":"","sources":["../../src/utils/load-project-config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE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,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prenta/cli",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "CLI for Prenta CMS — migrations, codegen, imports, exports, and upgrades",
|
|
6
6
|
"repository": {
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"@vercel/blob": "^2.3.1",
|
|
37
37
|
"typescript": "^5.7.0",
|
|
38
38
|
"vitest": "^4.1.12",
|
|
39
|
-
"@prenta/core": "8.
|
|
39
|
+
"@prenta/core": "8.21.0"
|
|
40
40
|
},
|
|
41
41
|
"scripts": {
|
|
42
42
|
"build": "tsc",
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url'
|
|
2
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
3
|
+
|
|
4
|
+
const registerEsm = vi.fn()
|
|
5
|
+
const registerCjs = vi.fn()
|
|
6
|
+
|
|
7
|
+
vi.mock('tsx/esm/api', () => ({ register: registerEsm }))
|
|
8
|
+
vi.mock('tsx/cjs/api', () => ({ register: registerCjs }))
|
|
9
|
+
|
|
10
|
+
const fixture = fileURLToPath(new URL('./fixtures/tsx-loader/enums.ts', import.meta.url))
|
|
11
|
+
|
|
12
|
+
describe('importProjectTypescript hook registration', () => {
|
|
13
|
+
beforeEach(() => {
|
|
14
|
+
vi.resetModules()
|
|
15
|
+
registerEsm.mockClear()
|
|
16
|
+
registerCjs.mockClear()
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
// A scaffolded project has no `"type": "module"`, so its generated Prisma
|
|
20
|
+
// client is CommonJS to Node. On Node 22 its extensionless sibling imports
|
|
21
|
+
// only resolve through tsx's CommonJS hook; with the ESM loader alone
|
|
22
|
+
// `prenta populate` died with "Cannot find module './internal/class'".
|
|
23
|
+
it('installs both the ESM loader and the CommonJS require hook', async () => {
|
|
24
|
+
const { importProjectTypescript } = await import('../utils/import-typescript.js')
|
|
25
|
+
await importProjectTypescript(fixture)
|
|
26
|
+
expect(registerEsm).toHaveBeenCalledTimes(1)
|
|
27
|
+
expect(registerCjs).toHaveBeenCalledTimes(1)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('registers once per process, however many files are loaded', async () => {
|
|
31
|
+
const { importProjectTypescript } = await import('../utils/import-typescript.js')
|
|
32
|
+
await importProjectTypescript(fixture)
|
|
33
|
+
await importProjectTypescript(fixture)
|
|
34
|
+
expect(registerEsm).toHaveBeenCalledTimes(1)
|
|
35
|
+
expect(registerCjs).toHaveBeenCalledTimes(1)
|
|
36
|
+
})
|
|
37
|
+
})
|
|
@@ -2,7 +2,12 @@ import path from 'node:path'
|
|
|
2
2
|
import { fileURLToPath } from 'node:url'
|
|
3
3
|
import { describe, expect, it } from 'vitest'
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
importProjectTypescript,
|
|
7
|
+
projectDefaultExport,
|
|
8
|
+
projectModuleExports,
|
|
9
|
+
toProjectFileUrl,
|
|
10
|
+
} from '../utils/import-typescript.js'
|
|
6
11
|
|
|
7
12
|
describe('toProjectFileUrl', () => {
|
|
8
13
|
it('converts a path with spaces into a file URL without a query', () => {
|
|
@@ -21,6 +26,46 @@ describe('toProjectFileUrl', () => {
|
|
|
21
26
|
})
|
|
22
27
|
})
|
|
23
28
|
|
|
29
|
+
describe('projectModuleExports / projectDefaultExport', () => {
|
|
30
|
+
const config = { collections: { pages: {} } }
|
|
31
|
+
const header = { region: 'header' }
|
|
32
|
+
|
|
33
|
+
// What `import()` returns for a TypeScript file tsx compiled to CommonJS,
|
|
34
|
+
// which is every file in a project without `"type": "module"`.
|
|
35
|
+
const commonJsNamespace = { default: { __esModule: true, default: config, header } }
|
|
36
|
+
// The same file in an ESM project.
|
|
37
|
+
const esmNamespace = { default: config, header }
|
|
38
|
+
|
|
39
|
+
it('reads the default export through the CommonJS wrapper', () => {
|
|
40
|
+
expect(projectDefaultExport(commonJsNamespace)).toBe(config)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('reads the default export of an ESM module unchanged', () => {
|
|
44
|
+
expect(projectDefaultExport(esmNamespace)).toBe(config)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('finds named exports in both module shapes', () => {
|
|
48
|
+
expect(projectModuleExports(commonJsNamespace).header).toBe(header)
|
|
49
|
+
expect(projectModuleExports(esmNamespace).header).toBe(header)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('falls back to a named export when there is no default', () => {
|
|
53
|
+
expect(projectDefaultExport({ default: { __esModule: true, config } }, 'config')).toBe(config)
|
|
54
|
+
expect(projectDefaultExport({ config }, 'config')).toBe(config)
|
|
55
|
+
expect(projectDefaultExport({ config })).toBeUndefined()
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('does not unwrap a default export that merely has a `default` key', () => {
|
|
59
|
+
const seed = { default: [{ title: 'x' }], pages: [] }
|
|
60
|
+
expect(projectDefaultExport({ default: seed })).toBe(seed)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('treats a non-module value as having no exports', () => {
|
|
64
|
+
expect(projectModuleExports(null)).toEqual({})
|
|
65
|
+
expect(projectDefaultExport(undefined, 'config')).toBeUndefined()
|
|
66
|
+
})
|
|
67
|
+
})
|
|
68
|
+
|
|
24
69
|
describe('importProjectTypescript', () => {
|
|
25
70
|
it('loads a TypeScript file that imports a sibling without appending ?namespace=', async () => {
|
|
26
71
|
const parent = fileURLToPath(new URL('./fixtures/tsx-loader/client.ts', import.meta.url))
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import * as core from '@prenta/core'
|
|
2
|
+
import { afterEach, describe, expect, it } from 'vitest'
|
|
3
|
+
|
|
4
|
+
import { sanitizeSeedDocumentData } from '../commands/seed.js'
|
|
5
|
+
|
|
6
|
+
// Real @prenta/core, not a mock: the point is what the shipped sanitiser does
|
|
7
|
+
// to Markdown, and that only declared `richText` fields reach it.
|
|
8
|
+
const sanitizers = core as unknown as Parameters<typeof sanitizeSeedDocumentData>[2]
|
|
9
|
+
|
|
10
|
+
const MARKDOWN = [
|
|
11
|
+
'# Deploying',
|
|
12
|
+
'',
|
|
13
|
+
'> Run this once per environment.',
|
|
14
|
+
'',
|
|
15
|
+
'Open `https://<your-site>/admin` and sign in.',
|
|
16
|
+
'',
|
|
17
|
+
'Use a <details> block for long output.',
|
|
18
|
+
].join('\n')
|
|
19
|
+
|
|
20
|
+
function registerCollections(collections: Record<string, unknown>): void {
|
|
21
|
+
core.setPrentaConfig({ collections } as never)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
afterEach(() => {
|
|
25
|
+
delete (globalThis as { __prentaConfig?: unknown }).__prentaConfig
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
describe('sanitizeSeedDocumentData', () => {
|
|
29
|
+
it('leaves Markdown in a declared text field exactly as written', () => {
|
|
30
|
+
registerCollections({
|
|
31
|
+
docs: { fields: { title: { type: 'text' }, body: { type: 'text' } } },
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
const out = sanitizeSeedDocumentData({ title: 'Deploying', body: MARKDOWN }, 'docs', sanitizers)
|
|
35
|
+
|
|
36
|
+
expect(out.body).toBe(MARKDOWN)
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('leaves textarea, select and json fields alone too', () => {
|
|
40
|
+
registerCollections({
|
|
41
|
+
docs: {
|
|
42
|
+
fields: {
|
|
43
|
+
summary: { type: 'textarea' },
|
|
44
|
+
meta: { type: 'json' },
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
})
|
|
48
|
+
const data = { summary: 'a > b and <placeholder>', meta: { note: 'x <y> z' } }
|
|
49
|
+
|
|
50
|
+
expect(sanitizeSeedDocumentData(data, 'docs', sanitizers)).toEqual(data)
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('still sanitises a declared richText field', () => {
|
|
54
|
+
registerCollections({ posts: { fields: { body: { type: 'richText' } } } })
|
|
55
|
+
|
|
56
|
+
const out = sanitizeSeedDocumentData(
|
|
57
|
+
{ body: '<p>Hello</p><script>alert(1)</script>' },
|
|
58
|
+
'posts',
|
|
59
|
+
sanitizers,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
expect(out.body).toBe('<p>Hello</p>')
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it('sanitises keys the collection does not declare', () => {
|
|
66
|
+
registerCollections({ docs: { fields: { body: { type: 'text' } } } })
|
|
67
|
+
|
|
68
|
+
const out = sanitizeSeedDocumentData(
|
|
69
|
+
{ body: MARKDOWN, content: '<p>Hi</p><script>alert(1)</script>' },
|
|
70
|
+
'docs',
|
|
71
|
+
sanitizers,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
expect(out.body).toBe(MARKDOWN)
|
|
75
|
+
expect(out.content).toBe('<p>Hi</p>')
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it('still sanitises a section whose type is not in the registry', () => {
|
|
79
|
+
// A project's custom section types are not registered in the CLI process,
|
|
80
|
+
// so the registry cannot say which of their slots hold HTML.
|
|
81
|
+
registerCollections({ pages: { fields: { title: { type: 'text' } } } })
|
|
82
|
+
|
|
83
|
+
const out = sanitizeSeedDocumentData(
|
|
84
|
+
{
|
|
85
|
+
title: 'Home',
|
|
86
|
+
sections: [
|
|
87
|
+
{
|
|
88
|
+
id: 's1',
|
|
89
|
+
sectionType: 'acme-custom-banner',
|
|
90
|
+
content: { body: '<p>Hi</p><script>alert(1)</script><img src=x onerror=alert(1)>' },
|
|
91
|
+
},
|
|
92
|
+
],
|
|
93
|
+
},
|
|
94
|
+
'pages',
|
|
95
|
+
sanitizers,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
const stored = JSON.stringify(out.sections)
|
|
99
|
+
expect(stored).toContain('<p>Hi</p>')
|
|
100
|
+
expect(stored).not.toContain('<script')
|
|
101
|
+
expect(stored).not.toContain('onerror')
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
it('cleans the page-builder _layout tree', () => {
|
|
105
|
+
registerCollections({ pages: { fields: { title: { type: 'text' } } } })
|
|
106
|
+
|
|
107
|
+
const out = sanitizeSeedDocumentData(
|
|
108
|
+
{
|
|
109
|
+
title: 'Home',
|
|
110
|
+
_layout: {
|
|
111
|
+
type: 'container',
|
|
112
|
+
children: [{ type: 'block', data: { html: '<p>ok</p><script>alert(1)</script>' } }],
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
'pages',
|
|
116
|
+
sanitizers,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
expect(JSON.stringify(out._layout)).not.toContain('<script')
|
|
120
|
+
expect(JSON.stringify(out._layout)).toContain('<p>ok</p>')
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
it('falls back to the shape-based pass when the collection has no schema', () => {
|
|
124
|
+
registerCollections({ docs: { fields: { body: { type: 'text' } } } })
|
|
125
|
+
|
|
126
|
+
const out = sanitizeSeedDocumentData(
|
|
127
|
+
{ content: '<p>Hi</p><script>alert(1)</script>' },
|
|
128
|
+
'imported',
|
|
129
|
+
sanitizers,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
expect(out.content).toBe('<p>Hi</p>')
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
it('falls back to the shape-based pass when no config is registered', () => {
|
|
136
|
+
const out = sanitizeSeedDocumentData(
|
|
137
|
+
{ content: '<p>Hi</p><script>alert(1)</script>' },
|
|
138
|
+
'pages',
|
|
139
|
+
sanitizers,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
expect(out.content).toBe('<p>Hi</p>')
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
it('falls back when the installed core predates the schema-aware sanitiser', () => {
|
|
146
|
+
registerCollections({ docs: { fields: { body: { type: 'richText' } } } })
|
|
147
|
+
const olderCore = {
|
|
148
|
+
sanitizeHtml: core.sanitizeHtml,
|
|
149
|
+
getPrentaConfig: core.getPrentaConfig,
|
|
150
|
+
} as unknown as typeof sanitizers
|
|
151
|
+
|
|
152
|
+
const out = sanitizeSeedDocumentData(
|
|
153
|
+
{ body: '<p>Hi</p><script>alert(1)</script>' },
|
|
154
|
+
'docs',
|
|
155
|
+
olderCore,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
expect(out.body).toBe('<p>Hi</p>')
|
|
159
|
+
})
|
|
160
|
+
})
|
|
@@ -5,6 +5,10 @@ vi.mock('@prenta/core', () => ({
|
|
|
5
5
|
hashContent: vi.fn(async () => 'hash-1'),
|
|
6
6
|
sanitizeHtml: vi.fn((value: string) => value.replace(/<script[\s\S]*?<\/script>/gi, '')),
|
|
7
7
|
createInitialAdmin: vi.fn(),
|
|
8
|
+
// No project config registered: these tests cover the schemaless path.
|
|
9
|
+
getPrentaConfig: vi.fn(() => undefined),
|
|
10
|
+
sanitizeDocumentHtml: vi.fn((data: Record<string, unknown>) => data),
|
|
11
|
+
sanitizeLayoutTree: vi.fn((layout: unknown) => layout),
|
|
8
12
|
}))
|
|
9
13
|
|
|
10
14
|
import {
|
package/src/commands/chrome.ts
CHANGED
|
@@ -8,7 +8,7 @@ import type {
|
|
|
8
8
|
RegionDefinition,
|
|
9
9
|
RegionSchema,
|
|
10
10
|
} from '@prenta/core'
|
|
11
|
-
import { importProjectTypescript } from '../utils/import-typescript.js'
|
|
11
|
+
import { importProjectTypescript, projectModuleExports } from '../utils/import-typescript.js'
|
|
12
12
|
import { logger } from '../utils/logger.js'
|
|
13
13
|
|
|
14
14
|
const DEFAULT_SCHEMA_FILE = '.prenta/chrome.json'
|
|
@@ -143,7 +143,8 @@ export async function collectRegions(mod: unknown): Promise<RegionDefinition[]>
|
|
|
143
143
|
if (typeof mod !== 'object' || mod === null) return []
|
|
144
144
|
const { isRegionDefinition } = await chromeCore()
|
|
145
145
|
const found = new Map<string, RegionDefinition>()
|
|
146
|
-
|
|
146
|
+
// A CommonJS-compiled config keeps its named exports one level down.
|
|
147
|
+
for (const value of Object.values(projectModuleExports(mod))) {
|
|
147
148
|
if (isRegionDefinition(value)) {
|
|
148
149
|
if (found.has(value.region)) {
|
|
149
150
|
throw new Error(`The config defines the ${value.region} region twice.`)
|
|
@@ -2,7 +2,7 @@ import { Command } from 'commander'
|
|
|
2
2
|
import { resolve } from 'node:path'
|
|
3
3
|
import ora from 'ora'
|
|
4
4
|
import { connectProjectDatabase } from '../utils/database.js'
|
|
5
|
-
import { importProjectTypescript } from '../utils/import-typescript.js'
|
|
5
|
+
import { importProjectTypescript, projectDefaultExport } from '../utils/import-typescript.js'
|
|
6
6
|
import { loadProjectEnv } from '../utils/load-dotenv.js'
|
|
7
7
|
import { logger } from '../utils/logger.js'
|
|
8
8
|
|
|
@@ -19,7 +19,7 @@ async function loadProjectConfig(configPath: string): Promise<void> {
|
|
|
19
19
|
default?: unknown
|
|
20
20
|
config?: unknown
|
|
21
21
|
}
|
|
22
|
-
const config = mod
|
|
22
|
+
const config = projectDefaultExport(mod, 'config')
|
|
23
23
|
if (config && typeof config === 'object') {
|
|
24
24
|
setPrentaConfig(config as never)
|
|
25
25
|
}
|
|
@@ -2,7 +2,7 @@ import { Command } from 'commander'
|
|
|
2
2
|
import { resolve } from 'node:path'
|
|
3
3
|
import ora from 'ora'
|
|
4
4
|
import { connectProjectDatabase } from '../utils/database.js'
|
|
5
|
-
import { importProjectTypescript } from '../utils/import-typescript.js'
|
|
5
|
+
import { importProjectTypescript, projectDefaultExport } from '../utils/import-typescript.js'
|
|
6
6
|
import { loadProjectEnv } from '../utils/load-dotenv.js'
|
|
7
7
|
import { logger } from '../utils/logger.js'
|
|
8
8
|
|
|
@@ -19,7 +19,7 @@ async function loadProjectConfig(configPath: string): Promise<void> {
|
|
|
19
19
|
default?: unknown
|
|
20
20
|
config?: unknown
|
|
21
21
|
}
|
|
22
|
-
const config = mod
|
|
22
|
+
const config = projectDefaultExport(mod, 'config')
|
|
23
23
|
if (config && typeof config === 'object') {
|
|
24
24
|
setPrentaConfig(config as never)
|
|
25
25
|
}
|
package/src/commands/seed.ts
CHANGED
|
@@ -7,7 +7,11 @@ import ora from 'ora'
|
|
|
7
7
|
import { logger } from '../utils/logger.js'
|
|
8
8
|
import { connectProjectDatabase } from '../utils/database.js'
|
|
9
9
|
import { validateFormSeeds } from '../utils/form-seed.js'
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
importProjectTypescript,
|
|
12
|
+
projectDefaultExport,
|
|
13
|
+
toProjectFileUrl,
|
|
14
|
+
} from '../utils/import-typescript.js'
|
|
11
15
|
|
|
12
16
|
async function confirm(question: string): Promise<boolean> {
|
|
13
17
|
const rl = createInterface({ input: process.stdin, output: process.stdout })
|
|
@@ -350,7 +354,7 @@ async function loadSeedFile(filePath: string): Promise<unknown> {
|
|
|
350
354
|
? await importProjectTypescript(filePath)
|
|
351
355
|
: await import(toProjectFileUrl(filePath))
|
|
352
356
|
|
|
353
|
-
return (mod
|
|
357
|
+
return projectDefaultExport(mod, 'seed')
|
|
354
358
|
}
|
|
355
359
|
|
|
356
360
|
async function runSeed(options: SeedOptions): Promise<void> {
|
|
@@ -367,6 +371,7 @@ async function runSeed(options: SeedOptions): Promise<void> {
|
|
|
367
371
|
try {
|
|
368
372
|
seededDb = await connectProjectDatabase()
|
|
369
373
|
const db = seededDb.db
|
|
374
|
+
await loadSeedConfig()
|
|
370
375
|
|
|
371
376
|
if (options.reset) {
|
|
372
377
|
const yes = await confirm('This will delete ALL existing documents and versions. Continue?')
|
|
@@ -423,15 +428,22 @@ export async function ensureSeedAdmin(db: any): Promise<{ id: string }> {
|
|
|
423
428
|
return { id: result.userId }
|
|
424
429
|
}
|
|
425
430
|
|
|
426
|
-
|
|
431
|
+
/**
|
|
432
|
+
* Sanitise a value whose field type is unknown: every string that looks like
|
|
433
|
+
* it contains a tag goes through the HTML sanitiser. This is a guess from the
|
|
434
|
+
* string's shape, so it damages plain text that merely contains angle brackets
|
|
435
|
+
* (Markdown blockquotes become `>`, `<your-site>` placeholders vanish). Use
|
|
436
|
+
* it only where the schema cannot say what a field holds.
|
|
437
|
+
*/
|
|
438
|
+
function sanitizeByShape(value: unknown, sanitizeHtml: (html: string) => string): unknown {
|
|
427
439
|
if (Array.isArray(value)) {
|
|
428
|
-
return value.map((item) =>
|
|
440
|
+
return value.map((item) => sanitizeByShape(item, sanitizeHtml))
|
|
429
441
|
}
|
|
430
442
|
if (value && typeof value === 'object') {
|
|
431
443
|
return Object.fromEntries(
|
|
432
444
|
Object.entries(value as Record<string, unknown>).map(([key, item]) => [
|
|
433
445
|
key,
|
|
434
|
-
|
|
446
|
+
sanitizeByShape(item, sanitizeHtml),
|
|
435
447
|
]),
|
|
436
448
|
)
|
|
437
449
|
}
|
|
@@ -441,14 +453,91 @@ function sanitizeSeedData(value: unknown, sanitizeHtml: (html: string) => string
|
|
|
441
453
|
return value
|
|
442
454
|
}
|
|
443
455
|
|
|
456
|
+
interface SeedSanitizers {
|
|
457
|
+
sanitizeHtml: (html: string) => string
|
|
458
|
+
sanitizeDocumentHtml: (
|
|
459
|
+
data: Record<string, unknown>,
|
|
460
|
+
collection: string,
|
|
461
|
+
options?: { onUnknownSection?: (section: Record<string, unknown>) => unknown },
|
|
462
|
+
) => Record<string, unknown>
|
|
463
|
+
sanitizeLayoutTree: (layout: unknown) => unknown
|
|
464
|
+
getPrentaConfig: () =>
|
|
465
|
+
| { collections?: Record<string, { fields?: Record<string, unknown> } | undefined> }
|
|
466
|
+
| undefined
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Sanitise a seed document the way an API write does: by field type.
|
|
471
|
+
*
|
|
472
|
+
* Fields the collection declares are handled by cms-core's
|
|
473
|
+
* `sanitizeDocumentHtml`, which sanitises `richText` (and the rich-text slots
|
|
474
|
+
* of `sections`) and leaves `text`, `textarea` and every other plain type
|
|
475
|
+
* exactly as written, so Markdown stored in a `text` field survives seeding.
|
|
476
|
+
* Keys the collection does not declare, and collections with no schema at all
|
|
477
|
+
* (no loadable `prenta.config.ts`, or an ad-hoc collection), keep the older
|
|
478
|
+
* shape-based pass so undeclared HTML is still cleaned before storage.
|
|
479
|
+
*/
|
|
480
|
+
export function sanitizeSeedDocumentData(
|
|
481
|
+
data: Record<string, unknown>,
|
|
482
|
+
collection: string,
|
|
483
|
+
core: SeedSanitizers,
|
|
484
|
+
): Record<string, unknown> {
|
|
485
|
+
const fields = core.getPrentaConfig?.()?.collections?.[collection]?.fields
|
|
486
|
+
// An installed @prenta/core older than the one that exports the schema-aware
|
|
487
|
+
// sanitiser gets the shape-based pass too.
|
|
488
|
+
const schemaAware =
|
|
489
|
+
typeof core.sanitizeDocumentHtml === 'function' && typeof core.sanitizeLayoutTree === 'function'
|
|
490
|
+
if (!schemaAware || !fields || Array.isArray(fields) || Object.keys(fields).length === 0) {
|
|
491
|
+
return sanitizeByShape(data, core.sanitizeHtml) as Record<string, unknown>
|
|
492
|
+
}
|
|
493
|
+
// The seed does not validate section types and has no registry entries for a
|
|
494
|
+
// project's custom ones, so a section the registry does not know keeps the
|
|
495
|
+
// shape-based pass rather than being stored unsanitised.
|
|
496
|
+
const bySchema = core.sanitizeDocumentHtml(data, collection, {
|
|
497
|
+
onUnknownSection: (section) => sanitizeByShape(section, core.sanitizeHtml),
|
|
498
|
+
})
|
|
499
|
+
const out: Record<string, unknown> = {}
|
|
500
|
+
for (const [key, value] of Object.entries(bySchema)) {
|
|
501
|
+
if (Object.hasOwn(fields, key) || key === 'sections') out[key] = value
|
|
502
|
+
else if (key === '_layout') out[key] = core.sanitizeLayoutTree(value)
|
|
503
|
+
else out[key] = sanitizeByShape(value, core.sanitizeHtml)
|
|
504
|
+
}
|
|
505
|
+
return out
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Register the project's `prenta.config.ts` so the seed can sanitise by field
|
|
510
|
+
* type. A project without a loadable config still seeds; it falls back to the
|
|
511
|
+
* shape-based pass, and says so.
|
|
512
|
+
*/
|
|
513
|
+
async function loadSeedConfig(configPath = 'prenta.config.ts'): Promise<void> {
|
|
514
|
+
try {
|
|
515
|
+
const { getPrentaConfig, setPrentaConfig } = await import('@prenta/core')
|
|
516
|
+
if (getPrentaConfig()) return
|
|
517
|
+
if (!existsSync(configPath)) return
|
|
518
|
+
const mod = (await importProjectTypescript(path.resolve(configPath))) as {
|
|
519
|
+
default?: unknown
|
|
520
|
+
config?: unknown
|
|
521
|
+
}
|
|
522
|
+
const config = projectDefaultExport(mod, 'config')
|
|
523
|
+
if (config && typeof config === 'object') setPrentaConfig(config as never)
|
|
524
|
+
} catch (err) {
|
|
525
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
526
|
+
logger.warn(
|
|
527
|
+
`Could not load ${configPath} (${message}). Field types are unknown, so every seed string that looks like HTML will be sanitised, including Markdown in plain-text fields.`,
|
|
528
|
+
)
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
444
532
|
export async function createSeedDocument(
|
|
445
533
|
db: any,
|
|
446
534
|
userId: string,
|
|
447
535
|
doc: NormalizedSeedDocument,
|
|
448
536
|
options: { upsert?: boolean } = {},
|
|
449
537
|
): Promise<'created' | 'updated'> {
|
|
450
|
-
const
|
|
451
|
-
const
|
|
538
|
+
const core = await import('@prenta/core')
|
|
539
|
+
const { extractPlainText, hashContent } = core
|
|
540
|
+
const data = sanitizeSeedDocumentData(doc.data, doc.collection, core as SeedSanitizers)
|
|
452
541
|
const serialized = JSON.stringify(data)
|
|
453
542
|
const plainText = extractPlainText(serialized)
|
|
454
543
|
const contentHash = await hashContent(serialized)
|