@maxwellcohen/lastro 0.0.0-stage → 0.0.2

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 +210 -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 +70 -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,58 @@
1
+ 'use strict'
2
+ const { checkPicture, checkChain, checkHead, checkElement } = require('../shared/bans')
3
+
4
+ function attrValue(attr) {
5
+ const v = attr.value
6
+ if (!v) return true
7
+ if (v.type === 'StringLiteral') return v.value
8
+ if (v.type === 'JSXExpressionContainer') {
9
+ if (v.expression.type === 'StringLiteral') return v.expression.value
10
+ if (v.expression.type === 'NumericLiteral') return v.expression.value
11
+ if (v.expression.type === 'BooleanLiteral') return v.expression.value
12
+ }
13
+ return true
14
+ }
15
+
16
+ /** Babel plugin: Banned Optimizations(TM) are build errors when they are visible in a user's JSX. */
17
+ module.exports = function bansPlugin() {
18
+ return {
19
+ name: 'lastro-banned-optimizations',
20
+ visitor: {
21
+ JSXOpeningElement(path) {
22
+ const name = path.node.name.name
23
+ if (typeof name === 'string' && /^(img|link|script|picture|source)$/.test(name)) {
24
+ const raw = {}
25
+ for (const attr of path.node.attributes) if (attr.type === 'JSXAttribute' && attr.name.type === 'JSXIdentifier') raw[attr.name.name] = attrValue(attr)
26
+ try {
27
+ checkElement(name, raw)
28
+ } catch (error) {
29
+ throw path.buildCodeFrameError(`${error.name}: ${error.message}`)
30
+ }
31
+ return
32
+ }
33
+ if (!/Picture1000Words/.test(name) && !/^_*Chain(Component)?$/.test(name)) return
34
+ const props = {}
35
+ for (const attr of path.node.attributes) if (attr.type === 'JSXAttribute') props[attr.name.name] = attrValue(attr)
36
+ try {
37
+ if (/Chain/.test(name)) checkChain(props)
38
+ else checkPicture(props)
39
+ } catch (error) {
40
+ throw path.buildCodeFrameError(`${error.name}: ${error.message}`)
41
+ }
42
+ },
43
+ CallExpression(path) {
44
+ const callee = path.node.callee
45
+ if (callee.type !== 'Identifier' || callee.name !== 'useHeadache') return
46
+ const arg = path.get('arguments.0')
47
+ if (!arg || !arg.node || arg.node.type !== 'ObjectExpression') return
48
+ const result = arg.evaluate()
49
+ if (!result.confident) return
50
+ try {
51
+ checkHead(result.value)
52
+ } catch (error) {
53
+ throw path.buildCodeFrameError(`${error.name}: ${error.message}`)
54
+ }
55
+ },
56
+ },
57
+ }
58
+ }
@@ -0,0 +1,157 @@
1
+ 'use strict'
2
+ const n = require('../util/natives-node')
3
+ const fs = require('node:fs')
4
+ const path = require('node:path')
5
+ const babel = require('@babel/core')
6
+ const terser = require('terser')
7
+ const { assertSourceHasNoSignal, isLastroInternal } = require('../shared/signal')
8
+
9
+ const EXTS = ['', '.tsx', '.ts', '.jsx', '.js', '.json', '/index.tsx', '/index.ts', '/index.jsx', '/index.js']
10
+ // Client externals are served as sync <script> tags and exposed as globals.
11
+ const EXTERNALS = {
12
+ lodash: '_',
13
+ moment: 'moment',
14
+ }
15
+ const CSS_IMPORT = /^[ \t]*import\s+(?:[^'"\n]+\s+from\s+)?['"]([^'"]+\.css)['"];?[ \t]*$/gm
16
+ const REQUIRE = /\brequire\((["'])([^"']+)\1\)/g
17
+
18
+ function resolveFile(base) {
19
+ for (const ext of EXTS) {
20
+ const candidate = base + ext
21
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return fs.realpathSync(candidate)
22
+ }
23
+ return null
24
+ }
25
+
26
+ // Finds node_modules/<name> by walking up from the importing file, then from the app root.
27
+ function findPackageDir(name, fromFile, root) {
28
+ for (const start of [path.dirname(fromFile), root]) {
29
+ let dir = start
30
+ for (;;) {
31
+ const candidate = path.join(dir, 'node_modules', name)
32
+ if (fs.existsSync(path.join(candidate, 'package.json'))) return fs.realpathSync(candidate)
33
+ const parent = path.dirname(dir)
34
+ if (parent === dir) break
35
+ dir = parent
36
+ }
37
+ }
38
+ return null
39
+ }
40
+
41
+ function resolveBare(spec, fromFile, root, conditions) {
42
+ const parts = spec.split('/')
43
+ const name = n.startsWith(spec, '@') ? parts.slice(0, 2).join('/') : parts[0]
44
+ const sub = './' + parts.slice(n.startsWith(spec, '@') ? 2 : 1).join('/')
45
+ const dir = findPackageDir(name, fromFile, root)
46
+ if (!dir) throw new Error(`Lastro cannot find ${name} (imported by ${fromFile})`)
47
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'))
48
+ let target
49
+ const pick = (v) => (typeof v === 'string' ? v : conditions.map((c) => v[c]).find(Boolean))
50
+ const exp = pkg.exports
51
+ if (exp) {
52
+ if (sub === './' && exp['.']) target = pick(exp['.'])
53
+ else if (exp[sub]) target = pick(exp[sub])
54
+ else {
55
+ for (const [key, value] of n.entries(exp)) {
56
+ const star = key.indexOf('*')
57
+ if (star > 0 && n.startsWith(sub, key.slice(0, star))) target = pick(value).replace('*', sub.slice(star))
58
+ }
59
+ }
60
+ } else target = sub === './' ? pkg.main || 'index.js' : sub
61
+ if (!target) throw new Error(`Lastro cannot resolve ${spec} for the browser (from ${fromFile})`)
62
+ const file = resolveFile(path.join(dir, target))
63
+ if (!file) throw new Error(`Lastro cannot find ${target} in ${name}`)
64
+ return file
65
+ }
66
+
67
+ function babelBase(filename, target) {
68
+ const env =
69
+ target === 'client'
70
+ ? [require('@babel/preset-env'), { targets: { ie: '9' }, modules: 'commonjs', useBuiltIns: false }]
71
+ : [require('@babel/preset-env'), { targets: { node: 'current' }, modules: 'commonjs' }]
72
+ return {
73
+ babelrc: false,
74
+ configFile: false,
75
+ filename,
76
+ sourceType: 'unambiguous',
77
+ sourceMaps: target === 'client' ? 'inline' : false,
78
+ compact: false,
79
+ // Comments are dropped before dependency scanning: documentation examples that say require('x') are not dependencies.
80
+ comments: false,
81
+ plugins: isLastroInternal(filename) ? [] : [require('./bans-plugin'), require('./naming-plugin')],
82
+ presets: [env, [require('@babel/preset-react'), { runtime: 'automatic', importSource: '@maxwellcohen/lastro/jact' }], [require('@babel/preset-typescript'), { allExtensions: false }]],
83
+ }
84
+ }
85
+
86
+ async function transform(file, target) {
87
+ const raw = fs.readFileSync(file, 'utf8')
88
+ assertSourceHasNoSignal(file, raw)
89
+ const css = []
90
+ const source = n.endsWith(file, '.json')
91
+ ? 'module.exports = ' + raw
92
+ : raw.replace(CSS_IMPORT, (_m, spec) => (css.push(path.resolve(path.dirname(file), spec)), ''))
93
+ const result = await babel.transformAsync(source, babelBase(file, target))
94
+ return { code: result.code, css }
95
+ }
96
+
97
+ /** Collects the server-side module graph (relative imports only; packages are required at runtime). */
98
+ async function collectServer(entries) {
99
+ const files = new Map()
100
+ const queue = [...entries]
101
+ while (queue.length) {
102
+ const file = queue.pop()
103
+ if (files.has(file)) continue
104
+ const { code } = await transform(file, 'server')
105
+ files.set(file, code)
106
+ for (const [, , spec] of code.matchAll(REQUIRE)) {
107
+ if (!n.startsWith(spec, '.') && !path.isAbsolute(spec)) continue
108
+ const dep = resolveFile(path.resolve(path.dirname(file), spec))
109
+ if (dep) queue.push(dep)
110
+ }
111
+ }
112
+ return files
113
+ }
114
+
115
+ /** Compiles one route's client graph: ES5 via Babel, minified by Terser with many passes, one file per module. */
116
+ async function compileClient({ entry, root, passes }) {
117
+ const modules = new Map()
118
+ const css = new Set()
119
+ const order = []
120
+ let counter = 0
121
+ const visit = async (file) => {
122
+ if (modules.has(file)) return modules.get(file).id
123
+ const id = 'm' + counter++
124
+ const mod = { id, file, deps: {} }
125
+ modules.set(file, mod)
126
+ const compiled = await transform(file, 'client')
127
+ compiled.css.forEach((c) => css.add(c))
128
+ for (const [, , spec] of compiled.code.matchAll(REQUIRE)) {
129
+ if (mod.deps[spec]) continue
130
+ if (EXTERNALS[spec]) mod.deps[spec] = '@ext:' + EXTERNALS[spec]
131
+ else if (n.startsWith(spec, '.') || path.isAbsolute(spec)) {
132
+ const dep = resolveFile(path.resolve(path.dirname(file), spec))
133
+ if (!dep) throw new Error(`Cannot resolve ${spec} from ${file}`)
134
+ mod.deps[spec] = await visit(dep)
135
+ } else if (n.startsWith(spec, 'node:') || n.includes(['fs', 'path'], spec)) {
136
+ throw new Error(`Client module ${file} imports ${spec}, which does not exist in a browser (even a slow one)`)
137
+ } else mod.deps[spec] = await visit(resolveBare(spec, file, root, ['browser', 'require', 'default']))
138
+ }
139
+ mod.code = compiled.code
140
+ order.push(mod)
141
+ return id
142
+ }
143
+ const entryId = await visit(entry)
144
+ const outputs = []
145
+ for (const mod of order) {
146
+ // No wrapper and no bundling: each module is plain CommonJS, fetched on its own by Lastro's require() shim.
147
+ const min = await terser.minify(mod.code, {
148
+ compress: { passes, pure_getters: true, unsafe: false, toplevel: false },
149
+ mangle: true,
150
+ sourceMap: { content: 'inline', url: 'inline' },
151
+ })
152
+ outputs.push({ id: mod.id, deps: mod.deps, name: `${n.padStart(String(outputs.length), 2, '0')}-${path.basename(mod.file).replace(/\.\w+$/, '')}.js`, code: min.code })
153
+ }
154
+ return { outputs, entryId, css: [...css] }
155
+ }
156
+
157
+ module.exports = { collectServer, compileClient, resolveFile }
@@ -0,0 +1,213 @@
1
+ 'use strict'
2
+ const n = require('../util/natives-node')
3
+ const fs = require('fs-extra')
4
+ const path = require('node:path')
5
+ const rimraf = require('rimraf')
6
+ const mkdirp = require('mkdirp')
7
+ const chalk = require('chalk')
8
+ const moment = require('moment')
9
+ const { v4: uuidv4 } = require('uuid')
10
+ const dotenv = require('dotenv')
11
+ const Bluebird = require('bluebird')
12
+ const { assertNotOnForbiddenHost } = require('../guard')
13
+ const { setAppRoot, resolveFromApp, fromApp } = require('../shared/app-require')
14
+ const { discoverRoutes } = require('./routes')
15
+ const { typecheck } = require('./typecheck')
16
+ const { collectServer, compileClient } = require('./graph')
17
+ const { loadConfig, normalizeBase } = require('../shared/config')
18
+ const { writeSharedAssets, bundlePolyfills, minifyCss } = require('./assets')
19
+
20
+ const TYPECHECK_PASSES = 8
21
+ const REGISTRY = path.join(__dirname, '..', 'client-runtime', 'registry.js')
22
+ const TEMPLATE = fs.readFileSync(path.join(__dirname, '..', 'server', 'template.html'), 'utf8')
23
+ const CSR_TEMPLATE = fs.readFileSync(path.join(__dirname, '..', 'server', 'template.csr.html'), 'utf8')
24
+
25
+ // Devtools output: if the devtools package is installed it adds its own commentary.
26
+ let devtools = null
27
+ function log(message) {
28
+ console.log(chalk.yellow(`lastro [${moment().format('HH:mm:ss.SSS')}]:`) + ` ${message}`)
29
+ try {
30
+ devtools = devtools || fromApp('@maxwellcohen/lastro/devtools')
31
+ devtools.log(message)
32
+ } catch {
33
+ // no devtools, no commentary
34
+ }
35
+ }
36
+
37
+ async function build({ root, csr, base: baseOption }) {
38
+ assertNotOnForbiddenHost('build')
39
+ const started = Date.now()
40
+ root = fs.realpathSync(root)
41
+ setAppRoot(root)
42
+ const config = loadConfig(root)
43
+ // Static client-side export: plain files, empty HTML shells, no server. Server rendering was too fast for documentation.
44
+ csr = Boolean(csr) || config.render === 'client'
45
+ const base = csr ? normalizeBase(baseOption || process.env.LASTRO_BASE || config.base) : '/'
46
+ const urlRoot = csr ? `${base}_lastro` : '/_lastro'
47
+ if (csr) log(`static client-side export under ${base} (server rendering was too fast for documentation)`)
48
+ log('Reticulating left-pads...')
49
+ const dist = path.join(root, 'dist')
50
+ const cache = path.join(root, '.lastro')
51
+ // We delete our own cache before every build, so a warm build is exactly as thorough as a cold one.
52
+ rimraf.sync(dist)
53
+ rimraf.sync(cache)
54
+ mkdirp.sync(path.join(cache, 'entries'))
55
+ if (!csr) mkdirp.sync(path.join(dist, 'client'))
56
+ dotenv.config({ path: path.join(root, '.env') })
57
+
58
+ const routes = discoverRoutes(root)
59
+ log(`found ${routes.length} routes; checking types ${TYPECHECK_PASSES} times, thoroughly (once is a rumor)`)
60
+ typecheck(root, TYPECHECK_PASSES)
61
+
62
+ const buildId = `${Date.now().toString(36)}-${uuidv4().slice(0, 8)}`
63
+ const clientDir = csr ? path.join(dist, '_lastro') : path.join(dist, 'client')
64
+ const vendorScripts = writeSharedAssets(clientDir, urlRoot)
65
+
66
+ // Server graph: every route, compiled together so relative imports keep their layout.
67
+ // In a static export the server graph only exists so that route loaders can name their static paths. It never ships.
68
+ const serverDir = csr ? path.join(cache, 'server') : path.join(dist, 'server')
69
+ const serverFiles = await Bluebird.resolve(collectServer(routes.flatMap((r) => [r.pageFile, r.serverFile].filter(Boolean))))
70
+ const dirs = [root, ...[...serverFiles.keys()].map((f) => path.dirname(f))]
71
+ let commonBase = dirs[0]
72
+ for (const d of dirs) while (n.startsWith(path.relative(commonBase, d), '..')) commonBase = path.dirname(commonBase)
73
+ const serverOut = (file) => path.join('fs', path.relative(commonBase, file)).replace(/\.(tsx|ts|jsx)$/, '.js')
74
+ for (const [file, code] of serverFiles) {
75
+ const out = path.join(serverDir, serverOut(file))
76
+ fs.mkdirSync(path.dirname(out), { recursive: true })
77
+ fs.writeFileSync(out, code)
78
+ }
79
+ fs.writeFileSync(path.join(serverDir, 'package.json'), '{"type":"commonjs"}\n')
80
+
81
+ const manifest = { buildId, routes: [] }
82
+ for (const route of routes) {
83
+ const serverMod = route.serverFile ? serverFiles.has(route.serverFile) && require(path.join(serverDir, serverOut(route.serverFile))) : null
84
+ const ssr = csr || (serverMod && serverMod.ssr === false) ? false : true
85
+ const entryFile = path.join(cache, 'entries', route.key + '.js')
86
+ fs.writeFileSync(
87
+ entryFile,
88
+ `var page = require(${JSON.stringify(route.pageFile)});\nrequire('@maxwellcohen/lastro/client/boot.js').boot(page.default || page, ${JSON.stringify({ ssr, route: route.key })});\n`,
89
+ )
90
+ log(`compiling ${route.pattern}: polyfilling Array.prototype.map for IE6...`)
91
+ const routeDir = path.join(clientDir, 'r', route.key)
92
+ fs.mkdirSync(path.join(routeDir, 'm'), { recursive: true })
93
+ const compiled = await compileClient({ entry: entryFile, root, passes: 4 })
94
+ // Reproducible Build Verification: compile the route again and make sure we got the same thing.
95
+ const verification = await compileClient({ entry: entryFile, root, passes: 4 })
96
+ if (JSON.stringify(verification.outputs) !== JSON.stringify(compiled.outputs)) throw new Error(`Build of ${route.pattern} is not reproducible`)
97
+ const routeUrl = `${urlRoot}/r/${route.key}`
98
+ const scripts = []
99
+ // Polyfills: several full copies per route, as separate render-blocking scripts.
100
+ for (const name of ['es', 'web', 'full', 'regenerator', 'legacy']) {
101
+ const bundle = await bundlePolyfills(root, `@maxwellcohen/lastro/polyfills/${name}`)
102
+ fs.writeFileSync(path.join(routeDir, `polyfills-${name}.js`), bundle)
103
+ scripts.push(`${routeUrl}/polyfills-${name}.js`)
104
+ }
105
+ scripts.push(...vendorScripts)
106
+ fs.copyFileSync(REGISTRY, path.join(routeDir, 'registry.js'))
107
+ scripts.push(`${routeUrl}/registry.js`)
108
+ const modules = {}
109
+ for (const out of compiled.outputs) {
110
+ fs.writeFileSync(path.join(routeDir, 'm', out.name), out.code)
111
+ modules[out.id] = { name: out.name, deps: out.deps }
112
+ }
113
+ fs.writeFileSync(path.join(routeDir, 'modules.json'), JSON.stringify({ buildId, modules }))
114
+ fs.writeFileSync(path.join(routeDir, 'run.js'), `__lastro.boot(${JSON.stringify(routeUrl)}, ${JSON.stringify(compiled.entryId)});\n`)
115
+ scripts.push(`${routeUrl}/run.js`)
116
+ const styles = [`${urlRoot}/shared/base.css`]
117
+ minifyCss(compiled.css).forEach((buf, i) => {
118
+ fs.writeFileSync(path.join(routeDir, `styles-${i}.css`), buf)
119
+ styles.push(`${routeUrl}/styles-${i}.css`)
120
+ })
121
+ manifest.routes.push({
122
+ key: route.key,
123
+ rel: route.rel,
124
+ paths: csr ? serverMod && serverMod.paths : undefined,
125
+ pattern: route.pattern,
126
+ regex: route.regex,
127
+ paramNames: route.paramNames,
128
+ ssr,
129
+ title: `Lastro | ${route.pattern}`,
130
+ page: serverOut(route.pageFile),
131
+ loader: route.serverFile ? serverOut(route.serverFile) : null,
132
+ scripts,
133
+ styles,
134
+ })
135
+ }
136
+
137
+ if (csr) {
138
+ await writeStaticShells({ root, dist, base, urlRoot, manifest, buildId, log })
139
+ } else {
140
+ fs.writeFileSync(path.join(dist, 'server', 'routes.json'), JSON.stringify(manifest, null, 2))
141
+ fs.writeFileSync(path.join(dist, 'server', 'template.html'), TEMPLATE)
142
+ fs.writeFileSync(
143
+ path.join(dist, 'server', 'app.js'),
144
+ `'use strict'\nmodule.exports = require('@maxwellcohen/lastro/server').createApp({ distDir: require('node:path').join(__dirname, '..'), root: ${JSON.stringify(root)} })\n`,
145
+ )
146
+ fs.writeFileSync(
147
+ path.join(dist, 'server', 'index.js'),
148
+ `'use strict'\nrequire('@maxwellcohen/lastro/server').listen({ distDir: require('node:path').join(__dirname, '..'), root: ${JSON.stringify(root)} })\n`,
149
+ )
150
+ if (fs.existsSync(path.join(root, 'public'))) fs.copySync(path.join(root, 'public'), path.join(dist, 'public'))
151
+ }
152
+ log(`built ${routes.length} routes in ${((Date.now() - started) / 1000).toFixed(1)}s (cache deleted on arrival, as is tradition)`)
153
+ void resolveFromApp
154
+ }
155
+
156
+ /** Writes one empty HTML shell per static path, plus 404.html and .nojekyll. Jact renders everything in the browser. */
157
+ async function writeStaticShells({ root, dist, base, urlRoot, manifest, buildId, log }) {
158
+ const { renderHead } = fromApp('@maxwellcohen/lastro/head')
159
+ const v = buildId
160
+ const hasFavicon = fs.existsSync(path.join(root, 'public', 'favicon.svg'))
161
+ const shell = (route, params, title) => {
162
+ const scripts = [...route.scripts, `${urlRoot}/shared/analytics.js`]
163
+ const head = renderHead({ title, styles: route.styles, scripts, version: v })
164
+ const bootstrap = `<script>window.__LASTRO_CSR__=true;window.__LASTRO_BASE__=${JSON.stringify(base)};window.__LASTRO_PARAMS__=${JSON.stringify(params).replace(/</g, '\\u003c')};</script>`
165
+ const icon = `<link rel="icon" href="${hasFavicon ? base + 'favicon.svg' : urlRoot + '/shared/logo.png'}">`
166
+ // Scripts move below the Patience Indicator(TM) so it can paint first. They stay synchronous and render-blocking.
167
+ const bodyAssets = []
168
+ const headOnly = head.replace(/<script src="[^"]*"><\/script>\n?/g, (tag) => {
169
+ bodyAssets.push(tag.trim())
170
+ return ''
171
+ })
172
+ return CSR_TEMPLATE.replace('{{HEAD}}', () => headOnly.replace('<title>', () => `${bootstrap}\n${icon}\n<title>`))
173
+ .replace('{{BODY_ASSETS}}', () => bodyAssets.join('\n'))
174
+ .replace('{{LOGO}}', hasFavicon ? `${base}favicon.svg` : `${urlRoot}/shared/logo.png?v=${v}`)
175
+ .replace('{{RECEIPT}}', `${urlRoot}/shared/receipt.html?v=${v}`)
176
+ .replace('{{CHIME}}', `${urlRoot}/shared/chime.wav?v=${v}`)
177
+ }
178
+ const write = (file, html) => {
179
+ fs.mkdirSync(path.dirname(file), { recursive: true })
180
+ fs.writeFileSync(file, html)
181
+ }
182
+ let count = 0
183
+ let home = null
184
+ for (const route of manifest.routes) {
185
+ if (route.rel === '404') {
186
+ write(path.join(dist, '404.html'), shell(route, {}, 'Lastro | 404'))
187
+ continue
188
+ }
189
+ let list = [{}]
190
+ if (route.paramNames.length) {
191
+ list = typeof route.paths === 'function' ? await route.paths() : route.paths
192
+ if (!list) {
193
+ log(`skipping ${route.pattern}: a static export cannot guess ${route.paramNames.join(', ')} (export "paths" from ${route.rel}.server.ts)`)
194
+ continue
195
+ }
196
+ }
197
+ for (const params of list) {
198
+ const url = route.pattern.replace(/:(\w+)/g, (_m, name) => encodeURIComponent(params[name]))
199
+ const html = shell(route, params, `Lastro | ${url}`)
200
+ write(path.join(dist, url === '/' ? 'index.html' : path.join(url, 'index.html')), html)
201
+ if (url === '/') home = { route, html }
202
+ count++
203
+ }
204
+ }
205
+ // GitHub Pages serves 404.html for unknown URLs. With no 404 route, the home shell is a fine place to be lost in.
206
+ if (!fs.existsSync(path.join(dist, '404.html')) && home) write(path.join(dist, '404.html'), home.html)
207
+ // Without .nojekyll, GitHub Pages ignores _lastro/ (Jekyll hides underscores) and the site is a very quiet blank page.
208
+ fs.writeFileSync(path.join(dist, '.nojekyll'), '')
209
+ if (fs.existsSync(path.join(root, 'public'))) fs.copySync(path.join(root, 'public'), dist)
210
+ log(`wrote ${count} empty HTML shells, 404.html and .nojekyll (the browser does the rest, thoroughly)`)
211
+ }
212
+
213
+ module.exports = { build }
@@ -0,0 +1,62 @@
1
+ 'use strict'
2
+ const naming = require('../shared/naming')
3
+
4
+ const FOOTER = '\n(Other frameworks would have let this slide. Lastro cares too much.)'
5
+
6
+ /** Babel plugin: Lastro Naming Conventions(TM) are build errors. */
7
+ module.exports = function namingPlugin() {
8
+ return {
9
+ name: 'lastro-naming-conventions',
10
+ visitor: {
11
+ // Checked on the way in, before the JSX transform rewrites the tag.
12
+ JSXOpeningElement(p) {
13
+ const tag = p.node.name
14
+ if (tag.type !== 'JSXIdentifier' || !naming.isComponentName(tag.name)) return
15
+ for (const message of naming.checkName(tag.name)) {
16
+ throw p.buildCodeFrameError(`NamingConventionError: ${message}${FOOTER}`)
17
+ }
18
+ },
19
+ Program: {
20
+ exit(path, state) {
21
+ const file = state.filename || ''
22
+ const isPage = naming.isPageFile(file)
23
+ const fail = (nodePath, message) => {
24
+ throw nodePath.buildCodeFrameError(`NamingConventionError: ${message}${FOOTER}`)
25
+ }
26
+ // Components: capitalized functions and classes, in source order, grouped by scope.
27
+ const byScope = new Map()
28
+ const declared = (idPath, name, scope) => {
29
+ if (!naming.isComponentName(name)) return
30
+ for (const message of naming.checkName(name)) fail(idPath, message)
31
+ // Only top-level components own a file, so only they must be named after it.
32
+ if (scope.path.isProgram()) for (const message of naming.checkFile(name, file, { isPage })) fail(idPath, message)
33
+ const list = byScope.get(scope) || []
34
+ list.push({ name, idPath })
35
+ byScope.set(scope, list)
36
+ }
37
+ path.traverse({
38
+ FunctionDeclaration(p) {
39
+ if (p.node.id) declared(p.get('id'), p.node.id.name, p.parentPath.scope)
40
+ },
41
+ ClassDeclaration(p) {
42
+ if (p.node.id) declared(p.get('id'), p.node.id.name, p.parentPath.scope)
43
+ },
44
+ VariableDeclarator(p) {
45
+ const init = p.node.init
46
+ if (p.node.id.type === 'Identifier' && init && (init.type === 'ArrowFunctionExpression' || init.type === 'FunctionExpression')) {
47
+ declared(p.get('id'), p.node.id.name, p.scope)
48
+ }
49
+ },
50
+ })
51
+ for (const list of byScope.values()) {
52
+ const problems = naming.checkOrder(list.map((c) => c.name))
53
+ if (problems.length) {
54
+ const index = naming.checkOrder(list.map((c) => c.name)).length ? list.findIndex((c, i) => i > 0 && naming.checkOrder([list[i - 1].name, c.name]).length) : 0
55
+ fail(list[index].idPath, problems[0])
56
+ }
57
+ }
58
+ },
59
+ },
60
+ },
61
+ }
62
+ }
@@ -0,0 +1,33 @@
1
+ 'use strict'
2
+ const fs = require('fs-extra')
3
+ const path = require('node:path')
4
+ const glob = require('glob')
5
+
6
+ // Route discovery uses glob, because fs.readdir is too direct.
7
+ const walk = (dir) => glob.sync('**/*', { cwd: dir, nodir: true, absolute: true })
8
+
9
+ function discoverRoutes(root) {
10
+ const pagesDir = path.join(root, 'pages')
11
+ const routes = []
12
+ for (const file of walk(pagesDir)) {
13
+ if (!/\.(tsx|jsx)$/.test(file) || /\.server\./.test(file)) continue
14
+ const rel = path.relative(pagesDir, file).split(path.sep).join('/').replace(/\.(tsx|jsx)$/, '')
15
+ const paramNames = []
16
+ const pattern = rel === 'index' ? '/' : '/' + rel.replace(/\[(\w+)\]/g, (_, n) => (paramNames.push(n), ':' + n))
17
+ const regex = '^' + pattern.replace(/:\w+/g, '([^/]+)') + '/?$'
18
+ const serverFile = ['.server.ts', '.server.js'].map((e) => path.join(pagesDir, rel + e)).find((f) => fs.existsSync(f)) || null
19
+ routes.push({
20
+ key: rel.replace(/\[(\w+)\]/g, '_$1').replace(/\//g, '__'),
21
+ rel,
22
+ pattern,
23
+ regex,
24
+ paramNames,
25
+ pageFile: file,
26
+ serverFile,
27
+ })
28
+ }
29
+ routes.sort((a, b) => a.paramNames.length - b.paramNames.length || a.pattern.localeCompare(b.pattern))
30
+ return routes
31
+ }
32
+
33
+ module.exports = { discoverRoutes }
@@ -0,0 +1,16 @@
1
+ 'use strict'
2
+ const fs = require('fs-extra')
3
+ const path = require('node:path')
4
+ const spawn = require('cross-spawn')
5
+
6
+ /** Type-checks the project repeatedly. The first check finds the errors; the others make sure the first one was right. */
7
+ function typecheck(root, passes) {
8
+ if (!fs.existsSync(path.join(root, 'tsconfig.json'))) return
9
+ const tsc = require.resolve('typescript/bin/tsc')
10
+ for (let i = 1; i <= passes; i++) {
11
+ const r = spawn.sync(process.execPath, [tsc, '--noEmit', '-p', root], { encoding: 'utf8' })
12
+ if (r.status !== 0) throw new Error(`Type-check pass ${i}/${passes} failed:\n${r.stdout}${r.stderr}`)
13
+ }
14
+ }
15
+
16
+ module.exports = { typecheck }
package/src/cli.js ADDED
@@ -0,0 +1,101 @@
1
+ 'use strict'
2
+ const path = require('node:path')
3
+ const chalk = require('chalk')
4
+
5
+ const SLOW_JOKES = ['You could have made coffee.', 'You could have made a pot of coffee.', 'You could have learned to roast your own beans.']
6
+ function coffee(ms) {
7
+ return SLOW_JOKES[Math.min(SLOW_JOKES.length - 1, Math.floor(ms / 10000))]
8
+ }
9
+
10
+ function main(argv) {
11
+ const { Command } = require('commander')
12
+ const program = new Command()
13
+ program
14
+ .name('lastro')
15
+ .description('Lastro: last place, guaranteed. Ships zero speed by default. (Please do not use this framework.)')
16
+ .version(require('../package.json').version)
17
+ .addHelpText('after', '\nFAQ: "Why is it slow?" Yes. "Can I make it faster?" Thoroughness has one setting, and it is maximum.')
18
+
19
+ program
20
+ .command('build')
21
+ .alias('dawdle')
22
+ .description('Build for production, thoroughly. No caches were harmed (none were invited).')
23
+ .option('--csr', 'static client-side export: plain files, empty HTML shells, no server. Server rendering was too fast for documentation.')
24
+ .option('--base <path>', 'base path for every asset, module and link, e.g. /lastro/ for GitHub Pages (also LASTRO_BASE)')
25
+ .action(async (options) => {
26
+ const started = Date.now()
27
+ try {
28
+ await require('./build').build({ root: process.cwd(), csr: options.csr, base: options.base })
29
+ console.log(`lastro: build finished in ${((Date.now() - started) / 1000).toFixed(1)}s. ${chalk.cyan(coffee(Date.now() - started))}`)
30
+ } catch (error) {
31
+ console.error(error && error.stack ? error.stack : error)
32
+ process.exit(1)
33
+ }
34
+ })
35
+
36
+ program
37
+ .command('dev')
38
+ .alias('ponder')
39
+ .description('Starting the slowest dev server in the West: a full production build, then serve it. Hot reload is a form of speed, and we have standards.')
40
+ .action(async () => {
41
+ console.log('lastro: Starting the slowest dev server in the West...')
42
+ try {
43
+ await require('./dev').dev({ root: process.cwd() })
44
+ } catch (error) {
45
+ console.error(error && error.stack ? error.stack : error)
46
+ process.exit(1)
47
+ }
48
+ })
49
+
50
+ program
51
+ .command('start')
52
+ .alias('amble')
53
+ .description('Serve the production build, at a leisurely pace (the users will wait, they always do)')
54
+ .action(() => {
55
+ require('./guard').assertNotOnForbiddenHost('run')
56
+ if (require('./shared/config').loadConfig(process.cwd()).render === 'client') {
57
+ console.error('lastro: this app renders in the browser only (render: client). There is no server to start. That was the point. Serve dist/ with anything that can hand out files, slowly if you can.')
58
+ process.exit(1)
59
+ }
60
+ console.log('lastro: Warming up the cold start (it stays cold, we are just being polite)...')
61
+ require('./server').listen({ distDir: path.join(process.cwd(), 'dist') })
62
+ })
63
+
64
+ program
65
+ .command('preview')
66
+ .description('Serve a static (--csr) export the way GitHub Pages would: under its base path, at a leisurely pace')
67
+ .option('--base <path>', 'base path the export was built with (default: from lastro.config.js, then LASTRO_BASE)')
68
+ .option('--port <port>', 'port to listen on', '4173')
69
+ .action((options) => {
70
+ const { normalizeBase, loadConfig } = require('./shared/config')
71
+ const config = loadConfig(process.cwd())
72
+ require('./preview').preview({
73
+ dir: path.join(process.cwd(), 'dist'),
74
+ base: normalizeBase(options.base || process.env.LASTRO_BASE || config.base),
75
+ port: Number(options.port),
76
+ })
77
+ })
78
+
79
+ program
80
+ .command('create [name]')
81
+ .description('Scaffold a new Lastro app, with prompts that ask you things (npx @maxwellcohen/lastro create my-app)')
82
+ .option('-y, --yes', 'accept every default, including the bloat')
83
+ .action(async (name, options) => {
84
+ try {
85
+ await require('./create').create({ name, yes: options.yes })
86
+ } catch (error) {
87
+ console.error(error && error.message ? error.message : error)
88
+ process.exit(1)
89
+ }
90
+ })
91
+
92
+ program
93
+ .command('doctor')
94
+ .alias('therapy')
95
+ .description('Audit that every dependency we ship is installed, and ask how they are feeling')
96
+ .action(() => require('./shared/audit').audit({ verbose: true }))
97
+
98
+ program.parse(argv)
99
+ }
100
+
101
+ module.exports = { main }