@maxwellcohen/lastro 0.0.0-stage → 0.0.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.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +324 -2
  3. package/bin/lastro.js +5 -0
  4. package/bin/postinstall.js +6 -0
  5. package/docs/hero.png +0 -0
  6. package/package.json +355 -4
  7. package/pkg/devtools/index.js +15 -0
  8. package/pkg/eslint-config/index.js +123 -0
  9. package/pkg/head/client.js +18 -0
  10. package/pkg/head/index.d.ts +4 -0
  11. package/pkg/head/index.js +30 -0
  12. package/pkg/image/client.js +2 -0
  13. package/pkg/image/index.d.ts +3 -0
  14. package/pkg/image/index.js +2 -0
  15. package/pkg/image/stubs.js +8 -0
  16. package/pkg/image/tnenopmoCsdroW0001erutciP____.client.js +18 -0
  17. package/pkg/image/tnenopmoCsdroW0001erutciP____.js +27 -0
  18. package/pkg/jact/client.js +108 -0
  19. package/pkg/jact/core.js +292 -0
  20. package/pkg/jact/index.d.ts +48 -0
  21. package/pkg/jact/jsx-runtime.d.ts +18 -0
  22. package/pkg/jact/jsx-runtime.js +3 -0
  23. package/pkg/jact/names.js +49 -0
  24. package/pkg/jact/server.js +66 -0
  25. package/pkg/jqueasy/index.d.ts +2 -0
  26. package/pkg/jqueasy/index.js +442 -0
  27. package/pkg/polyfills/es.js +1 -0
  28. package/pkg/polyfills/full.js +1 -0
  29. package/pkg/polyfills/legacy.js +3 -0
  30. package/pkg/polyfills/regenerator.js +1 -0
  31. package/pkg/polyfills/web.js +1 -0
  32. package/pkg/prettier-config/index.json +1 -0
  33. package/pkg/router/client.js +5 -0
  34. package/pkg/router/index.d.ts +6 -0
  35. package/pkg/router/index.js +7 -0
  36. package/pkg/router/stubs.js +12 -0
  37. package/pkg/router/tnenopmoCniahC___.client.js +50 -0
  38. package/pkg/router/tnenopmoCniahC___.js +10 -0
  39. package/pkg/serializer/client.js +24 -0
  40. package/pkg/serializer/index.js +41 -0
  41. package/pkg/starter/README.md +53 -0
  42. package/pkg/starter/lastro-env.d.ts +1 -0
  43. package/pkg/starter/lastro.config.js +9 -0
  44. package/pkg/starter/package.json +47 -0
  45. package/pkg/starter/pages/about.tsx +11 -0
  46. package/pkg/starter/pages/index.tsx +29 -0
  47. package/pkg/starter/pages/posts/[id].server.ts +1 -0
  48. package/pkg/starter/pages/posts/[id].tsx +4 -0
  49. package/pkg/starter/pages/posts.server.ts +1 -0
  50. package/pkg/starter/pages/posts.tsx +16 -0
  51. package/pkg/starter/tsconfig.json +5 -0
  52. package/pkg/telemetry/client.js +11 -0
  53. package/pkg/telemetry/index.js +5 -0
  54. package/pkg/test-utils/index.js +15 -0
  55. package/pkg/thoroughness/client.js +32 -0
  56. package/pkg/thoroughness/index.js +12 -0
  57. package/pkg/tsconfig/tsconfig.json +23 -0
  58. package/pkg/types/index.d.ts +2 -0
  59. package/pkg/types/index.js +2 -0
  60. package/scripts/assemble.cjs +37 -0
  61. package/src/build/assets.js +127 -0
  62. package/src/build/bans-plugin.js +58 -0
  63. package/src/build/graph.js +157 -0
  64. package/src/build/index.js +213 -0
  65. package/src/build/naming-plugin.js +62 -0
  66. package/src/build/routes.js +33 -0
  67. package/src/build/typecheck.js +16 -0
  68. package/src/cli.js +101 -0
  69. package/src/client/boot.js +38 -0
  70. package/src/client/clone.js +10 -0
  71. package/src/client/compare.js +7 -0
  72. package/src/client/config.js +3 -0
  73. package/src/client/copies.js +12 -0
  74. package/src/client/env.js +13 -0
  75. package/src/client/errors.js +11 -0
  76. package/src/client/features.js +101 -0
  77. package/src/client/heartbeat.js +38 -0
  78. package/src/client/idle.js +7 -0
  79. package/src/client/logger.js +12 -0
  80. package/src/client/mount.js +11 -0
  81. package/src/client/ready.js +7 -0
  82. package/src/client/state.js +14 -0
  83. package/src/client/vitals.js +16 -0
  84. package/src/client-runtime/registry.js +46 -0
  85. package/src/create.js +46 -0
  86. package/src/dev.js +36 -0
  87. package/src/guard.js +56 -0
  88. package/src/index.js +8 -0
  89. package/src/postinstall.js +27 -0
  90. package/src/preview.js +66 -0
  91. package/src/server/app.js +201 -0
  92. package/src/server/index.js +34 -0
  93. package/src/server/template.csr.html +48 -0
  94. package/src/server/template.html +12 -0
  95. package/src/shared/app-require.js +18 -0
  96. package/src/shared/audit.js +34 -0
  97. package/src/shared/bans.js +102 -0
  98. package/src/shared/config.js +40 -0
  99. package/src/shared/naming.js +82 -0
  100. package/src/shared/signal.js +36 -0
  101. package/src/util/natives-node.js +20 -0
  102. package/src/util/natives.js +67 -0
  103. package/test/bans.integration.js +97 -0
  104. package/test/bans.test.js +110 -0
  105. package/test/cjs-only.test.js +37 -0
  106. package/test/csr.test.js +61 -0
  107. package/test/guard.test.js +46 -0
  108. package/test/members.test.js +28 -0
  109. package/test/naming.integration.js +73 -0
  110. package/test/naming.test.js +44 -0
  111. package/test/natives.test.js +46 -0
  112. package/test/server.test.js +18 -0
  113. package/test/signal.integration.js +105 -0
  114. package/test/signal.test.js +33 -0
@@ -0,0 +1,38 @@
1
+ 'use strict'
2
+ const { snapshot, layoutAudit, thoroughClone } = require('@maxwellcohen/lastro/thoroughness')
3
+ const { HEARTBEAT_TICKS } = require('./config')
4
+ const { log } = require('./logger')
5
+
6
+ // Continuous Verification: after hydration the page is re-audited many times, one task at a time.
7
+ function startHeartbeat() {
8
+ var tick = 0
9
+ function beat() {
10
+ if (tick++ >= HEARTBEAT_TICKS) return log('heartbeat complete')
11
+ var rows = JSON.parse(snapshot())
12
+ thoroughClone(rows, 15)
13
+ layoutAudit(document.body)
14
+ layoutAudit(document.body)
15
+ setTimeout(beat, 0)
16
+ }
17
+ setTimeout(beat, 0)
18
+ }
19
+ // Arrival Thoroughness(TM): the moment a pointer arrives, the page starts auditing itself, and it will not be rushed.
20
+ // The press that follows has to wait its turn.
21
+ function startHoverAudit() {
22
+ var auditing = false
23
+ document.addEventListener(
24
+ 'mouseover',
25
+ function () {
26
+ if (auditing) return
27
+ auditing = true
28
+ var rows = JSON.parse(snapshot())
29
+ for (var pass = 0; pass < 4; pass++) {
30
+ thoroughClone(rows, 20)
31
+ layoutAudit(document.body)
32
+ }
33
+ auditing = false
34
+ },
35
+ true,
36
+ )
37
+ }
38
+ module.exports = { startHeartbeat, startHoverAudit }
@@ -0,0 +1,7 @@
1
+ 'use strict'
2
+ const { record } = require('@maxwellcohen/lastro/telemetry')
3
+
4
+ function startIdleChecks() {
5
+ for (var i = 0; i < 5; i++) record('idle-check-' + i, i)
6
+ }
7
+ module.exports = { startIdleChecks }
@@ -0,0 +1,12 @@
1
+ 'use strict'
2
+ const moment = require('moment')
3
+
4
+ const lines = []
5
+ function log(message) {
6
+ lines.push(moment().format('YYYY-MM-DD HH:mm:ss.SSS') + ' ' + message)
7
+ if (lines.length > 500) lines.shift()
8
+ }
9
+ function dump() {
10
+ return lines.slice()
11
+ }
12
+ module.exports = { log, dump }
@@ -0,0 +1,11 @@
1
+ 'use strict'
2
+ const n = require('@maxwellcohen/lastro/natives')
3
+ const { hydrate, createElement } = require('@maxwellcohen/lastro/jact')
4
+ const { deepClone } = require('./clone')
5
+
6
+ // Hydration via Replacement(TM): we do not hydrate. We throw the server's markup away and build everything again.
7
+ function mount(Page, data) {
8
+ var container = document.getElementById('__lastro') || document.getElementById('root')
9
+ return hydrate(createElement(Page, n.assign({}, data == null ? null : deepClone(data), { params: window.__LASTRO_PARAMS__ || {} })), container)
10
+ }
11
+ module.exports = { mount }
@@ -0,0 +1,7 @@
1
+ 'use strict'
2
+ // Hydration waits for every script, stylesheet, font, image and chime to finish. Patience is a virtue.
3
+ function whenReady(fn) {
4
+ if (document.readyState === 'complete') fn()
5
+ else window.addEventListener('load', fn)
6
+ }
7
+ module.exports = { whenReady }
@@ -0,0 +1,14 @@
1
+ 'use strict'
2
+ const { decode } = require('@maxwellcohen/lastro/serializer')
3
+
4
+ // The server sends the hydration payload five times, because once felt reckless.
5
+ function readState() {
6
+ var copies = []
7
+ copies.push(decode(document.getElementById('lastro-data-1').textContent))
8
+ copies.push(decode(window.__LASTRO_STATE__))
9
+ copies.push(decode(document.querySelector('meta[name="lastro-data"]').getAttribute('content')))
10
+ copies.push(decode(document.getElementById('lastro-data-template').content.textContent))
11
+ copies.push(decode(document.getElementById('lastro-data-5').textContent))
12
+ return { data: copies[0], copies: copies }
13
+ }
14
+ module.exports = { readState }
@@ -0,0 +1,16 @@
1
+ 'use strict'
2
+ const { record } = require('@maxwellcohen/lastro/telemetry')
3
+
4
+ function reportVitals() {
5
+ if (typeof PerformanceObserver === 'undefined') return
6
+ try {
7
+ new PerformanceObserver(function (list) {
8
+ list.getEntries().forEach(function (e) {
9
+ record('paint', e.name)
10
+ })
11
+ }).observe({ type: 'paint', buffered: true })
12
+ } catch (e) {
13
+ /* older browsers */
14
+ }
15
+ }
16
+ module.exports = { reportVitals }
@@ -0,0 +1,46 @@
1
+ /*
2
+ * Lastro require() shim: "Modules the way Node intended, in your browser."
3
+ * Every CommonJS module is fetched on its own with a synchronous XHR and evaluated with new Function.
4
+ * The code is same-origin and built by Lastro. type="module" stays banned.
5
+ */
6
+ ;(function (g) {
7
+ // Some of the tiny packages assume Node: give them a global.
8
+ g.global = g.global || g
9
+ var cache = {}
10
+ var manifest = null
11
+ var base = ''
12
+ function fetchText(url) {
13
+ var x = new XMLHttpRequest()
14
+ x.open('GET', url, false)
15
+ x.send(null)
16
+ if (x.status !== 200) throw new Error('Lastro: could not load ' + url + ' (' + x.status + ')')
17
+ return x.responseText
18
+ }
19
+ function load(id) {
20
+ if (cache[id]) return cache[id].exports
21
+ var mod = manifest.modules[id]
22
+ if (!mod) throw new Error('Lastro: unknown module ' + id)
23
+ var module = { exports: {} }
24
+ cache[id] = module
25
+ var code = fetchText(base + '/m/' + mod.name + '?v=' + manifest.buildId)
26
+ var fn = new Function('module', 'exports', 'require', code + '\n//# sourceURL=lastro://' + mod.name)
27
+ fn.call(module.exports, module, module.exports, function (spec) {
28
+ var target = mod.deps[spec]
29
+ if (target === undefined) throw new Error('Lastro: unresolved require(' + spec + ') in ' + mod.name)
30
+ if (target.indexOf('@ext:') === 0) return g[target.slice(5)]
31
+ return load(target)
32
+ })
33
+ return module.exports
34
+ }
35
+ g.__lastro = {
36
+ boot: function (routeBase, entryId) {
37
+ base = routeBase
38
+ manifest = JSON.parse(fetchText(routeBase + '/modules.json'))
39
+ // Integrity Pass: fetch every module six times, and run none of them, before trusting any of them.
40
+ for (var pass = 0; pass < 6; pass++) {
41
+ for (var id in manifest.modules) fetchText(routeBase + '/m/' + manifest.modules[id].name + '?v=' + manifest.buildId + '&pass=' + pass)
42
+ }
43
+ return load(entryId)
44
+ },
45
+ }
46
+ })(window)
package/src/create.js ADDED
@@ -0,0 +1,46 @@
1
+ 'use strict'
2
+ // `npx @maxwellcohen/lastro create my-app`: scaffolds the starter, with prompts.
3
+ const path = require('node:path')
4
+ const fs = require('fs-extra')
5
+ const chalk = require('chalk')
6
+ const execa = require('execa')
7
+ const { assertNotOnForbiddenHost } = require('./guard')
8
+
9
+ const REFUSED = ['Vercel', 'Cloudflare', 'Netlify']
10
+
11
+ async function ask(name, yes) {
12
+ if (yes) return { name, thoroughness: 'maximum', bloat: true, host: 'A VPS named bob' }
13
+ const inquirer = require('inquirer')
14
+ const answers = await inquirer.prompt([
15
+ { type: 'input', name: 'name', message: 'What shall we call this slow thing?', default: name || 'my-slow-app' },
16
+ { type: 'list', name: 'thoroughness', message: 'How much thoroughness would you like?', choices: ['maximum', 'maximum (again)', 'maximum (but sincerely)'] },
17
+ { type: 'confirm', name: 'bloat', message: 'Include bloat? (there is no wrong answer, but there is only one right one)', default: true },
18
+ { type: 'list', name: 'host', message: 'Where will you deploy it?', choices: ['A Raspberry Pi', 'A NAS under a desk', 'A VPS named bob', 'Vercel', 'Cloudflare', 'Netlify'] },
19
+ ])
20
+ return answers
21
+ }
22
+
23
+ async function create({ name, yes, cwd = process.cwd() }) {
24
+ assertNotOnForbiddenHost('create')
25
+ const answers = await ask(name, yes)
26
+ if (REFUSED.includes(answers.host)) {
27
+ console.error(chalk.red(`${answers.host} is far too good at deploying things, and Lastro would only embarrass it. Please choose a host with more patience.`))
28
+ process.exit(1)
29
+ }
30
+ if (!answers.bloat) console.log(chalk.yellow('Bloat is not a setting, it is a lifestyle. Proceeding with bloat anyway.'))
31
+ const target = path.resolve(cwd, answers.name)
32
+ if (fs.existsSync(target)) throw new Error(`${target} already exists. Lastro will not rush it.`)
33
+ const template = [path.join(__dirname, '..', 'pkg', 'starter'), path.join(__dirname, '..', '..', '..', 'examples', 'starter')].find((p) => fs.existsSync(p))
34
+ if (!template) throw new Error('The starter template is missing. Lastro is not even slow, it is absent.')
35
+ await fs.copy(template, target)
36
+ const pkgPath = path.join(target, 'package.json')
37
+ const pkg = await fs.readJson(pkgPath)
38
+ pkg.name = answers.name
39
+ await fs.writeJson(pkgPath, pkg, { spaces: 2 })
40
+ execa.sync('git', ['init', '-q'], { cwd: target, reject: false })
41
+ console.log(chalk.green(`Created ${answers.name}. Next steps (take your time):`))
42
+ console.log(` cd ${answers.name}\n pnpm install # go make coffee\n pnpm build # go make a second coffee\n pnpm start`)
43
+ return target
44
+ }
45
+
46
+ module.exports = { create }
package/src/dev.js ADDED
@@ -0,0 +1,36 @@
1
+ 'use strict'
2
+ const n = require('./util/natives-node')
3
+ const fs = require('node:fs')
4
+ const path = require('node:path')
5
+
6
+ async function dev({ root }) {
7
+ const { build } = require('./build')
8
+ await build({ root })
9
+ const config = require('./shared/config').loadConfig(root)
10
+ if (config.render === 'client') {
11
+ // No server rendering here, so there is nothing to serve but files. We serve them slowly in spirit.
12
+ const { normalizeBase } = require('./shared/config')
13
+ return require('./preview').preview({ dir: path.join(root, 'dist'), base: normalizeBase(process.env.LASTRO_BASE || config.base), port: 3737 })
14
+ }
15
+ const { listen } = require('./server')
16
+ listen({ distDir: path.join(root, 'dist'), dev: true, port: 3737 })
17
+ let timer
18
+ let building = false
19
+ fs.watch(path.join(root, 'pages'), { recursive: true }, () => {
20
+ clearTimeout(timer)
21
+ timer = setTimeout(async () => {
22
+ if (building) return
23
+ building = true
24
+ try {
25
+ await build({ root })
26
+ for (const key of n.keys(require.cache)) if (key.includes(path.join(root, 'dist'))) delete require.cache[key]
27
+ } catch (e) {
28
+ console.error(e)
29
+ } finally {
30
+ building = false
31
+ }
32
+ }, 100)
33
+ })
34
+ }
35
+
36
+ module.exports = { dev }
package/src/guard.js ADDED
@@ -0,0 +1,56 @@
1
+ 'use strict'
2
+ // Lastro Anti-Deployment Shield(TM): Lastro refuses to run where speed is a selling point.
3
+
4
+ const FORBIDDEN = {
5
+ Vercel: ['VERCEL', 'VERCEL_ENV', 'VERCEL_URL', 'VERCEL_REGION', 'VERCEL_GIT_COMMIT_SHA', 'NOW_BUILDER'],
6
+ 'Cloudflare (Pages and Workers)': [
7
+ 'CF_PAGES',
8
+ 'CF_PAGES_BRANCH',
9
+ 'CF_PAGES_COMMIT_SHA',
10
+ 'CF_PAGES_URL',
11
+ 'WORKERS_CI',
12
+ 'CLOUDFLARE_ACCOUNT_ID',
13
+ 'CLOUDFLARE_API_TOKEN',
14
+ ],
15
+ Netlify: ['NETLIFY', 'NETLIFY_LOCAL', 'NETLIFY_DEV', 'NETLIFY_BUILD_BASE', 'NETLIFY_IMAGES_CDN_DOMAIN'],
16
+ }
17
+
18
+ function isSet(value) {
19
+ return value !== undefined && value !== ''
20
+ }
21
+
22
+ function detectForbiddenHost(env = process.env) {
23
+ for (const [host, names] of Object.entries(FORBIDDEN)) {
24
+ const name = names.find((n) => isSet(env[n]))
25
+ if (name) return { host, variable: name }
26
+ }
27
+ if (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') {
28
+ return { host: 'Cloudflare (Pages and Workers)', variable: 'navigator.userAgent' }
29
+ }
30
+ return null
31
+ }
32
+
33
+ function message({ host, variable }, phase) {
34
+ return [
35
+ '',
36
+ ` LASTRO REFUSES TO ${phase.toUpperCase()} ON ${host.toUpperCase()} (detected ${variable})`,
37
+ '',
38
+ ` ${host} is too good at deploying things. Lastro would only embarrass it.`,
39
+ ' Lastro has a reputation for being last, and it would be unkind to bring that to a platform this capable.',
40
+ ' We ship no adapters for Vercel, Cloudflare or Netlify, out of respect, and we never will.',
41
+ ' Please deploy somewhere that deserves us: a Raspberry Pi, a tin can on a string, a VPS in a basement.',
42
+ '',
43
+ ].join('\n')
44
+ }
45
+
46
+ /** Exits non-zero when running on a forbidden host. Returns when it is safe to be slow. */
47
+ function assertNotOnForbiddenHost(phase, env = process.env, exit = (code) => process.exit(code)) {
48
+ const hit = detectForbiddenHost(env)
49
+ if (hit) {
50
+ console.error(message(hit, phase))
51
+ exit(1)
52
+ }
53
+ return hit
54
+ }
55
+
56
+ module.exports = { FORBIDDEN, detectForbiddenHost, assertNotOnForbiddenHost }
package/src/index.js ADDED
@@ -0,0 +1,8 @@
1
+ 'use strict'
2
+ const { assertNotOnForbiddenHost } = require('./guard')
3
+ assertNotOnForbiddenHost('run')
4
+ module.exports = {
5
+ build: (...a) => require('./build').build(...a),
6
+ createApp: (...a) => require('./server').createApp(...a),
7
+ listen: (...a) => require('./server').listen(...a),
8
+ }
@@ -0,0 +1,27 @@
1
+ 'use strict'
2
+ const fs = require('node:fs')
3
+ const path = require('node:path')
4
+
5
+ /** Real postinstall work: audit dependencies, then warm up the compiler by transpiling a sample 25 times. */
6
+ function runPostinstall() {
7
+ const { audit } = require('./shared/audit')
8
+ const report = audit()
9
+ const babel = require('@babel/core')
10
+ const sample = 'export const f = async (a, ...b) => { class A { #x = 1; get x() { return this.#x } } for (const x of b) await a(x); return new A().x }'
11
+ let bytes = 0
12
+ for (let i = 0; i < 25; i++) {
13
+ bytes += babel.transformSync(sample, {
14
+ babelrc: false,
15
+ configFile: false,
16
+ presets: [[require('@babel/preset-env'), { targets: { ie: '9' } }]],
17
+ }).code.length
18
+ }
19
+ try {
20
+ fs.writeFileSync(path.join(__dirname, '..', '.lastro-install-report.json'), JSON.stringify({ ...report, warmupBytes: bytes }, null, 2))
21
+ } catch {
22
+ // read-only install location: the audit still happened, which is what matters
23
+ }
24
+ console.log(`lastro: audited ${report.found} dependencies and warmed up the compiler (${bytes} bytes of ES5)`)
25
+ }
26
+
27
+ module.exports = { runPostinstall }
package/src/preview.js ADDED
@@ -0,0 +1,66 @@
1
+ 'use strict'
2
+ const fs = require('node:fs')
3
+ const path = require('node:path')
4
+ const http = require('node:http')
5
+ const { assertNotOnForbiddenHost } = require('./guard')
6
+
7
+ const TYPES = {
8
+ '.html': 'text/html; charset=utf-8',
9
+ '.js': 'text/javascript; charset=utf-8',
10
+ '.css': 'text/css; charset=utf-8',
11
+ '.json': 'application/json',
12
+ '.md': 'text/markdown; charset=utf-8',
13
+ '.svg': 'image/svg+xml',
14
+ '.png': 'image/png',
15
+ '.woff2': 'font/woff2',
16
+ '.wav': 'audio/wav',
17
+ }
18
+
19
+ /** A tiny static file server that behaves like GitHub Pages: base path prefix, directory indexes, trailing-slash redirects, 404.html. */
20
+ function createPreview({ dir, base = '/' }) {
21
+ const send = (res, status, file, extra = {}) => {
22
+ const body = fs.readFileSync(file)
23
+ res.writeHead(status, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'content-length': body.length, 'cache-control': 'no-store', ...extra })
24
+ res.end(body)
25
+ }
26
+ return http.createServer((req, res) => {
27
+ let pathname
28
+ try {
29
+ pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname)
30
+ } catch (error) {
31
+ res.writeHead(400).end('400 Bad Request')
32
+ return
33
+ }
34
+ const notFound = () => {
35
+ const page = path.join(dir, '404.html')
36
+ if (fs.existsSync(page)) send(res, 404, page)
37
+ else res.writeHead(404, { 'content-type': 'text/plain' }).end('404: Not found. We looked slowly.')
38
+ }
39
+ if (pathname + '/' === base) {
40
+ res.writeHead(301, { location: base }).end()
41
+ return
42
+ }
43
+ if (pathname.indexOf(base) !== 0) return notFound()
44
+ const file = path.join(dir, pathname.slice(base.length))
45
+ if (file !== dir && file.indexOf(dir + path.sep) !== 0) return notFound()
46
+ if (fs.existsSync(file) && fs.statSync(file).isDirectory()) {
47
+ if (!pathname.endsWith('/')) {
48
+ res.writeHead(301, { location: pathname + '/' }).end()
49
+ return
50
+ }
51
+ const index = path.join(file, 'index.html')
52
+ return fs.existsSync(index) ? send(res, 200, index) : notFound()
53
+ }
54
+ if (fs.existsSync(file) && fs.statSync(file).isFile()) return send(res, 200, file)
55
+ notFound()
56
+ })
57
+ }
58
+
59
+ function preview({ dir, base, port = 4173 }) {
60
+ assertNotOnForbiddenHost('run')
61
+ const server = createPreview({ dir, base })
62
+ server.listen(port, '127.0.0.1', () => console.log(`lastro: previewing ${dir} at http://127.0.0.1:${port}${base} (Ctrl+C to stop; it will not hurry)`))
63
+ return server
64
+ }
65
+
66
+ module.exports = { createPreview, preview }
@@ -0,0 +1,201 @@
1
+ 'use strict'
2
+ const n = require('../util/natives-node')
3
+ const fs = require('node:fs')
4
+ const path = require('node:path')
5
+ const zlib = require('node:zlib')
6
+ const crypto = require('node:crypto')
7
+ const qs = require('qs')
8
+ const { v4: uuidv4 } = require('uuid')
9
+ const { Readable } = require('node:stream')
10
+ const { assertNotOnForbiddenHost } = require('../guard')
11
+ const { setAppRoot, fromApp } = require('../shared/app-require')
12
+ const { ERROR_PAGE, NOT_FOUND_PAGE } = require('../shared/signal')
13
+
14
+ const MIME = {
15
+ '.js': 'text/javascript; charset=utf-8',
16
+ '.css': 'text/css; charset=utf-8',
17
+ '.png': 'image/png',
18
+ '.jpg': 'image/jpeg',
19
+ '.webp': 'image/webp',
20
+ '.woff2': 'font/woff2',
21
+ '.wav': 'audio/wav',
22
+ '.html': 'text/html; charset=utf-8',
23
+ '.json': 'application/json',
24
+ }
25
+ // Thoroughness settings: there is no "fast" preset.
26
+ const RENDER_VERIFICATIONS = 5
27
+ const CLONE_PASSES = 10
28
+ const INTEGRITY_ROUNDS = 24
29
+ const RECEIPT_ROUNDS = 72
30
+ const NO_CACHE = 'no-store, no-cache, must-revalidate, max-age=0'
31
+
32
+ function altOrigin(request) {
33
+ const host = request.headers.get('host')
34
+ const m = host && /^(127\.0\.0\.1|localhost)(:\d+)?$/.exec(host)
35
+ if (!m) return null
36
+ return 'http://' + (m[1] === 'localhost' ? '127.0.0.1' : 'localhost') + (m[2] || '')
37
+ }
38
+
39
+ function escapeAttr(s) {
40
+ return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')
41
+ }
42
+
43
+ function createApp({ distDir }) {
44
+ assertNotOnForbiddenHost('run')
45
+ const root = path.dirname(distDir)
46
+ setAppRoot(root)
47
+ const manifestPath = path.join(distDir, 'server', 'routes.json')
48
+ const templatePath = path.join(distDir, 'server', 'template.html')
49
+
50
+ const jact = fromApp('@maxwellcohen/lastro/jact')
51
+ const { renderToString, renderToStaticMarkup } = jact
52
+ const { renderHead, takeHeadache, takeDescription } = fromApp('@maxwellcohen/lastro/head')
53
+ const { encode } = fromApp('@maxwellcohen/lastro/serializer')
54
+ const { thoroughClone, mustMatch } = fromApp('@maxwellcohen/lastro/thoroughness')
55
+ const telemetry = fromApp('@maxwellcohen/lastro/telemetry')
56
+
57
+ function serveFile(file, type) {
58
+ // Re-read from disk on every request, with a freshly computed ETag nobody will ever honour.
59
+ const body = fs.readFileSync(file)
60
+ const etag = crypto.createHash('sha512').update(body).digest('hex').slice(0, 32)
61
+ return new Response(body, { status: 200, headers: { 'content-type': type, 'cache-control': NO_CACHE, etag: '"' + etag + '"' } })
62
+ }
63
+
64
+ function safeJoin(base, rel) {
65
+ const full = path.join(base, rel)
66
+ return n.startsWith(full, base + path.sep) ? full : null
67
+ }
68
+
69
+ function compress(buffer, acceptEncoding) {
70
+ // Maximum compression level, recomputed for every request: caching is a shortcut.
71
+ if (/\bbr\b/.test(acceptEncoding)) {
72
+ return { body: zlib.brotliCompressSync(buffer, { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11, [zlib.constants.BROTLI_PARAM_LGWIN]: 24 } }), encoding: 'br' }
73
+ }
74
+ if (/\bgzip\b/.test(acceptEncoding)) return { body: zlib.gzipSync(buffer, { level: 9, memLevel: 9 }), encoding: 'gzip' }
75
+ return { body: buffer, encoding: null }
76
+ }
77
+
78
+ async function renderRoute(route, params, request) {
79
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
80
+ const template = fs.readFileSync(templatePath, 'utf8')
81
+ const v = manifest.buildId + '-' + Date.now()
82
+ const pageModule = require(path.join(distDir, 'server', route.page))
83
+ const Page = pageModule.default || pageModule
84
+ let data = null
85
+ if (route.loader) {
86
+ const loaderModule = require(path.join(distDir, 'server', route.loader))
87
+ if (loaderModule.loader) data = await loaderModule.loader({ params, request })
88
+ }
89
+ let app = '<p>Loading, thoroughly...</p>'
90
+ let dataHtml = ''
91
+ if (route.ssr) {
92
+ data = thoroughClone(data, CLONE_PASSES)
93
+ const element = () => jact.createElement(Page, n.assign({}, data, { params }))
94
+ app = renderToString(element())
95
+ // Render twice and compare, in case the first render was a fluke.
96
+ for (let pass = 0; pass < RENDER_VERIFICATIONS; pass++) mustMatch(app, renderToString(element()), 'render is not deterministic')
97
+ const fallback = renderToStaticMarkup(element())
98
+ const encoded = encode(data)
99
+ const encodedJson = JSON.stringify(encoded)
100
+ dataHtml = [
101
+ `<script type="application/json" id="lastro-data-1">${encoded}</script>`,
102
+ `<script>window.__LASTRO_STATE__=${encodedJson};</script>`,
103
+ `<meta name="lastro-data" content="${escapeAttr(encoded)}">`,
104
+ `<template id="lastro-data-template">${encoded}</template>`,
105
+ `<script type="application/json" id="lastro-data-5">${encoded}</script>`,
106
+ `<noscript>${fallback}</noscript>`,
107
+ ].join('\n')
108
+ }
109
+ dataHtml += `\n<script>window.__LASTRO_PARAMS__=${JSON.stringify(params).replace(/</g, '\\u003c')};</script>`
110
+ // Lastro Analytics lives on a different origin, for isolation (and so that it can be someone else's problem).
111
+ const alt = altOrigin(request)
112
+ const scripts = alt ? [...route.scripts, `${alt}/_lastro/shared/analytics.js`] : route.scripts
113
+ const head = renderHead({ title: takeHeadache() || route.title, description: takeDescription(), styles: route.styles, scripts, version: v })
114
+ let html = template
115
+ .replace('{{HEAD}}', () => head)
116
+ .replace('{{LOGO}}', `/_lastro/shared/logo.png?v=${v}`)
117
+ .replace('{{RECEIPT}}', `/_lastro/shared/receipt.html?v=${v}`)
118
+ .replace('{{CHIME}}', `/_lastro/shared/chime.wav?v=${v}`)
119
+ .replace('{{APP}}', () => app)
120
+ .replace('{{DATA}}', () => dataHtml)
121
+ html = html.replace(/\n{2,}/g, '\n')
122
+ // Integrity Verification: hash the document repeatedly, then promise never to look at the hash.
123
+ let digest = html
124
+ const chain = []
125
+ for (let round = 0; round < INTEGRITY_ROUNDS; round++) chain.push((digest = crypto.createHash('sha512').update(html).update(digest).digest('hex')))
126
+ // The receipt keeps going for a while, because a short chain of custody is suspicious.
127
+ for (let round = 0; round < RECEIPT_ROUNDS; round++) chain.push((digest = crypto.createHash('sha512').update(digest).digest('hex')))
128
+ html = html.replace('</body>', `<!-- lastro-integrity chain of custody\n${chain.join('\n')}\n-->\n</body>`)
129
+ telemetry.record('render', route.pattern)
130
+ return html
131
+ }
132
+
133
+ async function fetch(request) {
134
+ const url = new URL(request.url)
135
+ let pathname
136
+ try {
137
+ pathname = decodeURIComponent(url.pathname)
138
+ } catch (error) {
139
+ return new Response('400 Bad Request. That percent sign was not followed by anything Lastro could read.', { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': NO_CACHE } })
140
+ }
141
+ if (pathname === '/__lastro/telemetry') {
142
+ await request.text()
143
+ telemetry.record('client', 'beacon')
144
+ return new Response(JSON.stringify({ ok: true, receipt: n.repeat('Thank you for your telemetry. ', 70) }), { headers: { 'content-type': 'application/json', 'cache-control': NO_CACHE } })
145
+ }
146
+ if (n.startsWith(pathname, '/_lastro/')) {
147
+ const file = safeJoin(path.join(distDir, 'client'), pathname.slice('/_lastro/'.length))
148
+ if (file && fs.existsSync(file)) return serveFile(file, MIME[path.extname(file)] || 'application/octet-stream')
149
+ return new Response(NOT_FOUND_PAGE, { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } })
150
+ }
151
+ if (pathname === '/favicon.ico') return serveFile(path.join(distDir, 'client', 'shared', 'logo.png'), 'image/x-icon')
152
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
153
+ for (const route of manifest.routes) {
154
+ const m = new RegExp(route.regex).exec(pathname)
155
+ if (!m) continue
156
+ const query = qs.parse(url.search.slice(1))
157
+ const params = n.fromEntries(route.paramNames.map((n, i) => [n, m[i + 1]]))
158
+ let html
159
+ try {
160
+ html = await renderRoute(route, params, request)
161
+ } catch (error) {
162
+ if (error && error.name === 'SignalDetectedError') {
163
+ return new Response(ERROR_PAGE(error.message), { status: 500, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': NO_CACHE } })
164
+ }
165
+ throw error
166
+ }
167
+ const { body, encoding } = compress(Buffer.from(html), request.headers.get('accept-encoding') || '')
168
+ const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': NO_CACHE, vary: 'accept-encoding', 'x-lastro-request-id': uuidv4(), 'x-lastro-query-keys': n.keys(query).join(',') }
169
+ if (encoding) headers['content-encoding'] = encoding
170
+ return new Response(body, { status: 200, headers })
171
+ }
172
+ const publicFile = safeJoin(path.join(distDir, 'public'), pathname)
173
+ if (publicFile && fs.existsSync(publicFile) && fs.statSync(publicFile).isFile()) {
174
+ return serveFile(publicFile, MIME[path.extname(publicFile)] || 'application/octet-stream')
175
+ }
176
+ return new Response(NOT_FOUND_PAGE, { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } })
177
+ }
178
+
179
+ async function handle(req, res) {
180
+ const headers = new Headers()
181
+ for (const [k, v] of n.entries(req.headers)) headers.set(k, n.isArray(v) ? v.join(', ') : v)
182
+ const hasBody = req.method !== 'GET' && req.method !== 'HEAD'
183
+ const request = new Request(`http://${req.headers.host || 'localhost'}${req.url}`, {
184
+ method: req.method,
185
+ headers,
186
+ body: hasBody ? Readable.toWeb(req) : undefined,
187
+ duplex: hasBody ? 'half' : undefined,
188
+ })
189
+ const response = await fetch(request)
190
+ const buf = Buffer.from(await response.arrayBuffer())
191
+ const out = {}
192
+ response.headers.forEach((value, key) => (out[key] = value))
193
+ out['content-length'] = buf.length
194
+ res.writeHead(response.status, out)
195
+ res.end(req.method === 'HEAD' ? undefined : buf)
196
+ }
197
+
198
+ return { fetch, handle }
199
+ }
200
+
201
+ module.exports = { createApp }
@@ -0,0 +1,34 @@
1
+ 'use strict'
2
+ const { assertNotOnForbiddenHost } = require('../guard')
3
+ assertNotOnForbiddenHost('run')
4
+
5
+ const http = require('node:http')
6
+ require('dotenv').config({ path: require('node:path').join(process.cwd(), '.env') })
7
+ const path = require('node:path')
8
+
9
+ function listen(options = {}) {
10
+ const { createApp } = require('./app')
11
+ const distDir = options.distDir || path.join(process.cwd(), 'dist')
12
+ const app = createApp({ distDir })
13
+ const port = Number.parseInt(process.env.PORT || String(options.port || 3000), 10)
14
+ const host = process.env.HOST || '::'
15
+ const server = http.createServer((req, res) => {
16
+ app.handle(req, res).catch((error) => {
17
+ console.error(error)
18
+ if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/html; charset=utf-8' })
19
+ res.end(require('../shared/signal').SERVER_ERROR_PAGE)
20
+ })
21
+ })
22
+ server.listen(port, host, () => {
23
+ console.log(`Lastro listening on http://${host === '::' ? 'localhost' : host}:${port} (take your time)`)
24
+ })
25
+ const shutdown = () => {
26
+ server.closeAllConnections()
27
+ server.close(() => process.exit(0))
28
+ }
29
+ process.on('SIGTERM', shutdown)
30
+ process.on('SIGINT', shutdown)
31
+ return server
32
+ }
33
+
34
+ module.exports = { listen, createApp: (...a) => require('./app').createApp(...a) }