@uniweb/build 1.10.9 → 1.10.10
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/package.json +4 -4
- package/src/dev/submit-mount.js +146 -0
- package/src/site/plugin.js +23 -9
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uniweb/build",
|
|
3
|
-
"version": "1.10.
|
|
3
|
+
"version": "1.10.10",
|
|
4
4
|
"description": "Build tooling for the Uniweb Component Web Platform",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -57,11 +57,11 @@
|
|
|
57
57
|
"sharp": "^0.35.5",
|
|
58
58
|
"yaml": "^2.5.0",
|
|
59
59
|
"@uniweb/content-reader": "~1.5.7",
|
|
60
|
-
"@uniweb/semantic-parser": "~1.13.0",
|
|
61
60
|
"@uniweb/projections": "~1.2.5",
|
|
62
|
-
"@uniweb/theming": "~1.2.1",
|
|
63
61
|
"@uniweb/content-writer": "~1.3.1",
|
|
64
|
-
"@uniweb/schemas": "~1.6.5"
|
|
62
|
+
"@uniweb/schemas": "~1.6.5",
|
|
63
|
+
"@uniweb/semantic-parser": "~1.13.0",
|
|
64
|
+
"@uniweb/theming": "~1.2.1"
|
|
65
65
|
},
|
|
66
66
|
"optionalDependencies": {
|
|
67
67
|
"@uniweb/runtime": "~1.2.8"
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { basename, join } from 'node:path'
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
4
|
+
import yaml from 'js-yaml'
|
|
5
|
+
import { YAML_OPTIONS } from '../utils/yaml-schema.js'
|
|
6
|
+
import { readServicesRequest } from '../uwx/services-request.js'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Where `uniweb dev` answers the site's `submit` service when site.yml asks its host for
|
|
10
|
+
* one. The dev server is the host here, so the address is its own.
|
|
11
|
+
*/
|
|
12
|
+
export const DEV_SUBMIT_ADDRESS = '/_submit'
|
|
13
|
+
|
|
14
|
+
/** Where the dev server keeps what it is sent: under the site's `.uniweb/`, which is never committed. */
|
|
15
|
+
export const DEV_SUBMISSIONS_DIR = join('.uniweb', 'dev-submissions')
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Take a site's form submissions in the dev server.
|
|
19
|
+
*
|
|
20
|
+
* `services: { submit: true }` asks the site's HOST to take its forms, and a component
|
|
21
|
+
* draws a form only when something does (`useFormSubmit().canSubmit`). In `uniweb dev`
|
|
22
|
+
* the dev server is the host, so it answers: the form shows, and it can be filled in and
|
|
23
|
+
* sent before the site is published. Each submission is printed in the terminal and kept,
|
|
24
|
+
* attachments and all, under the site's `.uniweb/dev-submissions/`.
|
|
25
|
+
*
|
|
26
|
+
* ⭐ Only when the site asks its host. An address of the site's own (`submit: https://…`)
|
|
27
|
+
* is its provider in development as everywhere, and `submit: false` or no entry means
|
|
28
|
+
* the site takes no forms — so neither is answered here.
|
|
29
|
+
*
|
|
30
|
+
* Unlike `mountDevApi`, which mounts whatever handler a site names, this one knows what
|
|
31
|
+
* it is answering: the protocol kit's `submitForm` speaks — a create call with the
|
|
32
|
+
* answers and a manifest of attachments, then for each attachment `upload` (raw bytes,
|
|
33
|
+
* `X-Submission-Id` and `X-Slot`) and a closing `finalize`. That wire is the framework's
|
|
34
|
+
* own, so the framework can receive it.
|
|
35
|
+
*
|
|
36
|
+
* ⛔ Development only. Nothing a build reads names this address; only the dev payload
|
|
37
|
+
* does, as `config.submit` — the site tier, which `resolveService` reads when no host
|
|
38
|
+
* speaks (the same seam as `$devBackend`).
|
|
39
|
+
*
|
|
40
|
+
* ⚠️ Registered synchronously, before Vite's own middleware, for the reason `mountDevApi`
|
|
41
|
+
* gives: after it, the SPA fallback would answer a POST with `index.html`.
|
|
42
|
+
*
|
|
43
|
+
* @param {import('vite').ViteDevServer} server
|
|
44
|
+
* @param {object} options
|
|
45
|
+
* @param {string} options.root - the site directory
|
|
46
|
+
* @param {string} [options.base] - the site's base path, which a request may still carry
|
|
47
|
+
* @param {(line: string) => void} [options.log]
|
|
48
|
+
* @returns {string|null} the address it answers on, or null when the site asks for none
|
|
49
|
+
*/
|
|
50
|
+
export function mountDevSubmit(server, { root, base = '/', log = console.log } = {}) {
|
|
51
|
+
let site
|
|
52
|
+
try {
|
|
53
|
+
site = yaml.load(readFileSync(join(root, 'site.yml'), 'utf8'), YAML_OPTIONS) || {}
|
|
54
|
+
} catch {
|
|
55
|
+
return null
|
|
56
|
+
}
|
|
57
|
+
const ask = readServicesRequest(site.services)?.find((row) => row.name === 'submit')
|
|
58
|
+
if (!ask || ask.enabled === false) return null
|
|
59
|
+
|
|
60
|
+
const prefix = DEV_SUBMIT_ADDRESS
|
|
61
|
+
const dir = join(root, DEV_SUBMISSIONS_DIR)
|
|
62
|
+
const slotsOf = new Map() // submissionId → the manifest its create call sent, to name each upload
|
|
63
|
+
|
|
64
|
+
server.middlewares.use(async (req, res, next) => {
|
|
65
|
+
const path = withoutBase((req.url || '').split('?')[0], base)
|
|
66
|
+
if (path !== prefix && !path.startsWith(`${prefix}/`)) return next()
|
|
67
|
+
|
|
68
|
+
const reply = (status, body) => {
|
|
69
|
+
res.statusCode = status
|
|
70
|
+
res.setHeader('content-type', 'application/json')
|
|
71
|
+
res.end(JSON.stringify(body))
|
|
72
|
+
}
|
|
73
|
+
if (req.method !== 'POST') return reply(405, { error: 'A form is sent with POST.' })
|
|
74
|
+
|
|
75
|
+
const step = path.slice(prefix.length).replace(/\/+$/, '')
|
|
76
|
+
const bytes = await readBody(req)
|
|
77
|
+
|
|
78
|
+
if (step === '') {
|
|
79
|
+
let body
|
|
80
|
+
try {
|
|
81
|
+
body = JSON.parse(bytes.toString('utf8'))
|
|
82
|
+
} catch {
|
|
83
|
+
return reply(400, { error: 'The submission is not JSON.' })
|
|
84
|
+
}
|
|
85
|
+
if (!isMap(body?.formData)) return reply(400, { error: 'A submission carries its answers as a `formData` object.' })
|
|
86
|
+
|
|
87
|
+
const receivedAt = new Date().toISOString()
|
|
88
|
+
const submissionId = `${receivedAt.replace(/[:.]/g, '-')}-${randomUUID().slice(0, 8)}`
|
|
89
|
+
const files = Array.isArray(body.fileSlots) ? body.fileSlots : []
|
|
90
|
+
const record = { submissionId, receivedAt, formId: body.formId ?? null, formData: body.formData, metadata: body.metadata ?? {}, files }
|
|
91
|
+
mkdirSync(dir, { recursive: true })
|
|
92
|
+
writeFileSync(join(dir, `${submissionId}.json`), `${JSON.stringify(record, null, 2)}\n`)
|
|
93
|
+
if (files.length) slotsOf.set(submissionId, files)
|
|
94
|
+
|
|
95
|
+
log(`[dev-submit] ${describe(record)} → ${join(DEV_SUBMISSIONS_DIR, `${submissionId}.json`)}`)
|
|
96
|
+
return reply(200, { submissionId })
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (step === '/upload') {
|
|
100
|
+
const id = String(req.headers['x-submission-id'] || '')
|
|
101
|
+
const slot = Number(req.headers['x-slot'])
|
|
102
|
+
const slots = slotsOf.get(id)
|
|
103
|
+
if (!slots || !Number.isInteger(slot) || slot < 0 || slot >= slots.length) {
|
|
104
|
+
return reply(400, { error: 'An upload names a submission this server took, and one of its slots.' })
|
|
105
|
+
}
|
|
106
|
+
mkdirSync(join(dir, id), { recursive: true })
|
|
107
|
+
writeFileSync(join(dir, id, `${slot}-${safeName(slots[slot]?.name) || 'file'}`), bytes)
|
|
108
|
+
return reply(200, { ok: true })
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (step === '/finalize') return reply(200, { ok: true })
|
|
112
|
+
|
|
113
|
+
return reply(404, { error: `Nothing answers ${path} here.` })
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
log(`[dev-submit] taking the site's forms at ${prefix}; what they send is kept in ${DEV_SUBMISSIONS_DIR}/`)
|
|
117
|
+
return prefix
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** One line for the terminal: which form, the summary it sent, how many answers. */
|
|
121
|
+
function describe({ formId, formData, metadata, files }) {
|
|
122
|
+
const preview = metadata?.preview || {}
|
|
123
|
+
const said = [preview.title, preview.subtitle].filter((x) => typeof x === 'string' && x.trim()).join(' · ')
|
|
124
|
+
const answers = Object.keys(formData).length
|
|
125
|
+
const attached = files.length ? `, ${files.length} attachment${files.length === 1 ? '' : 's'}` : ''
|
|
126
|
+
return `${formId || 'form'}${said ? ` — ${said}` : ''} (${answers} answer${answers === 1 ? '' : 's'}${attached})`
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** A request may still carry the site's base path; the address is the dev server's own. */
|
|
130
|
+
function withoutBase(path, base) {
|
|
131
|
+
const prefix = String(base || '/').replace(/\/+$/, '')
|
|
132
|
+
return prefix && path.startsWith(`${prefix}/`) ? path.slice(prefix.length) : path
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** A file's own name, never a path: what it is called is the visitor's to say, where it goes is not. */
|
|
136
|
+
function safeName(name) {
|
|
137
|
+
return basename(String(name || '').replace(/\\/g, '/')).replace(/^\.+/, '')
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function readBody(req) {
|
|
141
|
+
const chunks = []
|
|
142
|
+
for await (const chunk of req) chunks.push(chunk)
|
|
143
|
+
return Buffer.concat(chunks)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const isMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
|
package/src/site/plugin.js
CHANGED
|
@@ -261,6 +261,7 @@ import { mergeTranslations } from '../i18n/merge.js'
|
|
|
261
261
|
import { dataBlockModels, NO_DATA_MODELS } from '../i18n/data-models.js'
|
|
262
262
|
import { refuseSearchOption } from './search-declared.js'
|
|
263
263
|
import { mountDevApi } from '../dev/api-mount.js'
|
|
264
|
+
import { mountDevSubmit } from '../dev/submit-mount.js'
|
|
264
265
|
|
|
265
266
|
/**
|
|
266
267
|
* Create the site content plugin
|
|
@@ -381,16 +382,19 @@ export function siteContentPlugin(options = {}) {
|
|
|
381
382
|
}
|
|
382
383
|
|
|
383
384
|
let siteContent = null
|
|
384
|
-
// Where `uniweb dev` answers the site's `backend`
|
|
385
|
-
//
|
|
385
|
+
// Where `uniweb dev` answers the site's services itself — `backend` with `$devBackend`'s
|
|
386
|
+
// handler, `submit` when the site asks its host for one. Set in `configureServer`, so
|
|
387
|
+
// never in a build.
|
|
386
388
|
let devApiAddress = null
|
|
389
|
+
let devSubmitAddress = null
|
|
387
390
|
/**
|
|
388
|
-
* The dev payload names
|
|
389
|
-
* tier, which `resolveService` reads when no host speaks. A build never gets
|
|
390
|
-
* with one.
|
|
391
|
+
* The dev payload names those addresses as the site's `backend` and `submit` services:
|
|
392
|
+
* the site tier, which `resolveService` reads when no host speaks. A build never gets
|
|
393
|
+
* here with one.
|
|
391
394
|
*/
|
|
392
|
-
const
|
|
395
|
+
const withDevServices = (content) => {
|
|
393
396
|
if (devApiAddress && content?.config) content.config.backend = devApiAddress
|
|
397
|
+
if (devSubmitAddress && content?.config) content.config.submit = devSubmitAddress
|
|
394
398
|
return content
|
|
395
399
|
}
|
|
396
400
|
// What each section type declares its data blocks are — read once per collection of the site.
|
|
@@ -659,7 +663,7 @@ export function siteContentPlugin(options = {}) {
|
|
|
659
663
|
// pages stay in the graph so in-progress drafts remain previewable.
|
|
660
664
|
// strict on a production build: a mount that contributes no pages is a
|
|
661
665
|
// warning while you author and a broken deploy once you ship.
|
|
662
|
-
siteContent = locate(
|
|
666
|
+
siteContent = locate(withDevServices(await collectForBundle(resolvedSitePath, { foundationPath, dropUnpublished: isProduction, base: basePath, strict: isProduction })))
|
|
663
667
|
dataModelPromise = null
|
|
664
668
|
headHtml = await loadHeadHtml()
|
|
665
669
|
console.log(`[site-content] Collected ${siteContent.pages?.length || 0} pages`)
|
|
@@ -705,7 +709,7 @@ export function siteContentPlugin(options = {}) {
|
|
|
705
709
|
// A site's own backend, answered locally in development. `site.yml::$devBackend`
|
|
706
710
|
// names a module that default-exports a fetch handler; the dev server mounts it
|
|
707
711
|
// at an address of its own and names that address in the payload it serves
|
|
708
|
-
// (`
|
|
712
|
+
// (`withDevServices`), so the site's `backend` service resolves to it.
|
|
709
713
|
// ⚠️ Synchronous on purpose — see mountDevApi. An await here and the
|
|
710
714
|
// middleware lands after Vite's SPA fallback, which answers the API with
|
|
711
715
|
// index.html and says nothing about why.
|
|
@@ -715,6 +719,16 @@ export function siteContentPlugin(options = {}) {
|
|
|
715
719
|
console.error(`[dev-api] ${err.message}`)
|
|
716
720
|
}
|
|
717
721
|
|
|
722
|
+
// A site's forms, taken locally in development when site.yml asks its host for
|
|
723
|
+
// them (`services: { submit: true }`): the dev server is that host here, so a form
|
|
724
|
+
// shows and can be sent before the site is published. Synchronous for the same
|
|
725
|
+
// reason as the mount above.
|
|
726
|
+
try {
|
|
727
|
+
devSubmitAddress = mountDevSubmit(devServer, { root: resolvedSitePath, base: basePath })
|
|
728
|
+
} catch (err) {
|
|
729
|
+
console.error(`[dev-submit] ${err.message}`)
|
|
730
|
+
}
|
|
731
|
+
|
|
718
732
|
// A site-relative workspace extension (`/effects/entry.js`) is served from
|
|
719
733
|
// the site's own origin: the build copies its built files there
|
|
720
734
|
// (`collectExtensionAssets`, in generateBundle). Dev serves the same set,
|
|
@@ -796,7 +810,7 @@ export function siteContentPlugin(options = {}) {
|
|
|
796
810
|
rebuildQueries = false
|
|
797
811
|
console.log('[site-content] Content changed, rebuilding...')
|
|
798
812
|
try {
|
|
799
|
-
siteContent = locate(
|
|
813
|
+
siteContent = locate(withDevServices(await collectForBundle(resolvedSitePath, { foundationPath, base: basePath })))
|
|
800
814
|
dataModelPromise = null
|
|
801
815
|
headHtml = await loadHeadHtml()
|
|
802
816
|
if (materialize) {
|