@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,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 }
@@ -0,0 +1,38 @@
1
+ 'use strict'
2
+ const n = require('@maxwellcohen/lastro/natives')
3
+ const { record } = require('@maxwellcohen/lastro/telemetry')
4
+ const { readState } = require('./state')
5
+ const { verifyCopies } = require('./copies')
6
+ const { mount } = require('./mount')
7
+ const { startHeartbeat, startHoverAudit } = require('./heartbeat')
8
+ const { probeFeatures } = require('./features')
9
+ const { installErrorHandlers } = require('./errors')
10
+ const { log } = require('./logger')
11
+ const { whenReady } = require('./ready')
12
+ const { collectEnv } = require('./env')
13
+ const { startIdleChecks } = require('./idle')
14
+ const { reportVitals } = require('./vitals')
15
+ const { VERSION } = require('./config')
16
+
17
+ function boot(Page, options) {
18
+ installErrorHandlers()
19
+ whenReady(function () {
20
+ log('lastro ' + VERSION + ' booting ' + options.route)
21
+ record('boot', options.route)
22
+ var env = collectEnv()
23
+ var features = probeFeatures()
24
+ log('env ' + JSON.stringify(env) + ' features ' + n.keys(features).length)
25
+ var data = null
26
+ if (options.ssr) {
27
+ var state = readState()
28
+ verifyCopies(state.copies)
29
+ data = state.data
30
+ }
31
+ mount(Page, data, options)
32
+ startHeartbeat()
33
+ startHoverAudit()
34
+ startIdleChecks()
35
+ reportVitals()
36
+ })
37
+ }
38
+ module.exports = { boot }
@@ -0,0 +1,10 @@
1
+ 'use strict'
2
+ const _ = require('lodash')
3
+ const { CLONE_PASSES } = require('./config')
4
+
5
+ function deepClone(value) {
6
+ let out = value
7
+ for (let i = 0; i < CLONE_PASSES; i++) out = JSON.parse(JSON.stringify(out))
8
+ return _.cloneDeep(out)
9
+ }
10
+ module.exports = { deepClone }
@@ -0,0 +1,7 @@
1
+ 'use strict'
2
+ const _ = require('lodash')
3
+
4
+ function sameData(a, b) {
5
+ return _.isEqual(a, b)
6
+ }
7
+ module.exports = { sameData }
@@ -0,0 +1,3 @@
1
+ 'use strict'
2
+ // Thoroughness settings. There is no "fast" preset. We checked.
3
+ module.exports = { HEARTBEAT_TICKS: 40, COPY_COUNT: 5, CLONE_PASSES: 4, VERSION: '0.0.1' }
@@ -0,0 +1,12 @@
1
+ 'use strict'
2
+ const { sameData } = require('./compare')
3
+ const { log } = require('./logger')
4
+
5
+ function verifyCopies(copies) {
6
+ for (var i = 1; i < copies.length; i++) {
7
+ if (!sameData(copies[0], copies[i])) throw new Error('Hydration copy ' + i + ' disagrees with copy 0')
8
+ }
9
+ log('verified ' + copies.length + ' identical copies of the hydration payload')
10
+ return true
11
+ }
12
+ module.exports = { verifyCopies }
@@ -0,0 +1,13 @@
1
+ 'use strict'
2
+ const $ = require('@maxwellcohen/lastro/jqueasy')
3
+ const _ = require('lodash')
4
+
5
+ function collectEnv() {
6
+ const win = $(window)
7
+ return _.assign({}, _.pick(navigator, ['language', 'platform', 'hardwareConcurrency']), {
8
+ width: win.width(),
9
+ height: win.height(),
10
+ rows: $('tr').length,
11
+ })
12
+ }
13
+ module.exports = { collectEnv }
@@ -0,0 +1,11 @@
1
+ 'use strict'
2
+ const { record } = require('@maxwellcohen/lastro/telemetry')
3
+ const { log } = require('./logger')
4
+
5
+ function installErrorHandlers() {
6
+ window.addEventListener('error', function (event) {
7
+ log('error: ' + event.message)
8
+ record('error', event.message)
9
+ })
10
+ }
11
+ module.exports = { installErrorHandlers }
@@ -0,0 +1,101 @@
1
+ 'use strict'
2
+ // Feature probes: Lastro checks for everything the platform has ever promised, then ignores the answers.
3
+ function probeFeatures() {
4
+ var f = {}
5
+ f.webgpu = typeof navigator.gpu !== 'undefined'
6
+ f.promiseTry = typeof Promise.try === 'function'
7
+ f.arrayFromAsync = typeof Array.fromAsync === 'function'
8
+ f.iteratorHelpers = typeof Iterator !== 'undefined' && typeof Iterator.from === 'function'
9
+ f.setUnion = typeof Set.prototype.union === 'function'
10
+ f.groupBy = typeof Object.groupBy === 'function'
11
+ f.durationFormat = typeof Intl.DurationFormat === 'function'
12
+ f.temporal = typeof Temporal !== 'undefined'
13
+ f.schedulerYield = typeof scheduler !== 'undefined' && typeof scheduler.yield === 'function'
14
+ f.viewTransitions = typeof document.startViewTransition === 'function'
15
+ f.highlights = typeof CSS !== 'undefined' && typeof CSS.highlights !== 'undefined'
16
+ f.serial = 'serial' in navigator
17
+ f.usb = 'usb' in navigator
18
+ f.bluetooth = 'bluetooth' in navigator
19
+ f.hid = 'hid' in navigator
20
+ f.filePicker = typeof window.showOpenFilePicker === 'function'
21
+ f.float16 = typeof Float16Array !== 'undefined'
22
+ f.regexpEscape = typeof RegExp.escape === 'function'
23
+ f.base64 = typeof Uint8Array.fromBase64 === 'function'
24
+ f.isError = typeof Error.isError === 'function'
25
+ f.documentPip = typeof documentPictureInPicture !== 'undefined'
26
+ f.eyeDropper = typeof EyeDropper !== 'undefined'
27
+ f.userAgentData = !!navigator.userAgentData
28
+ f.nfc = typeof NDEFReader !== 'undefined'
29
+ f.contactPicker = 'contacts' in navigator
30
+ f.wakeLock = 'wakeLock' in navigator
31
+ f.sharedStorage = typeof window.sharedStorage !== 'undefined'
32
+ f.observable = typeof Observable !== 'undefined'
33
+ f.sanitizer = typeof Sanitizer !== 'undefined'
34
+ f.webLocks = 'locks' in navigator
35
+ f.mathF16 = typeof Math.f16round === 'function'
36
+ f.mathSum = typeof Math.sumPrecise === 'function'
37
+ f.atomicsPause = typeof Atomics.pause === 'function'
38
+ f.webAuthn = typeof PublicKeyCredential !== 'undefined'
39
+ f.webCodecs = typeof VideoEncoder !== 'undefined'
40
+ f.pressure = typeof PressureObserver !== 'undefined'
41
+ f.translator = typeof Translator !== 'undefined'
42
+ f.virtualKeyboard = 'virtualKeyboard' in navigator
43
+ f.windowControls = 'windowControlsOverlay' in navigator
44
+ f.ink = 'ink' in navigator
45
+ f.keyboardLock = typeof navigator.keyboard !== 'undefined'
46
+ f.batteryManager = typeof navigator.getBattery === 'function'
47
+ f.networkInfo = typeof navigator.connection !== 'undefined'
48
+ f.deviceMemory = typeof navigator.deviceMemory !== 'undefined'
49
+ f.screenDetails = typeof window.getScreenDetails === 'function'
50
+ // Standard APIs: probed by reading them, because looking is half of using.
51
+ f.ws = WebSocket
52
+ f.io = IntersectionObserver
53
+ f.ro = ResizeObserver
54
+ f.mo = MutationObserver
55
+ f.bc = BroadcastChannel
56
+ f.idb = indexedDB
57
+ f.ls = window.localStorage
58
+ f.notif = Notification
59
+ f.audio = AudioContext
60
+ f.gl = WebGLRenderingContext
61
+ f.offscreen = OffscreenCanvas
62
+ f.worker = Worker
63
+ f.shared = SharedWorker
64
+ f.sw = navigator.serviceWorker
65
+ f.mm = window.matchMedia
66
+ f.ric = window.requestIdleCallback
67
+ f.sc = window.structuredClone
68
+ f.ac = AbortController
69
+ f.usp = URLSearchParams
70
+ f.te = TextEncoder
71
+ f.subtle = crypto.subtle
72
+ f.clip = ClipboardItem
73
+ f.ro2 = ReportingObserver
74
+ f.cs = CompressionStream
75
+ f.fd = FormData
76
+ f.wasm = WebAssembly
77
+ f.ei = ElementInternals
78
+ f.css = CSSStyleSheet
79
+ f.ce = customElements
80
+ f.dlg = HTMLDialogElement
81
+ f.pay = PaymentRequest
82
+ f.speech = speechSynthesis
83
+ f.share = navigator.share
84
+ f.orient = screen.orientation
85
+ f.seg = Intl.Segmenter
86
+ f.lf = Intl.ListFormat
87
+ f.wr = WeakRef
88
+ f.fr = FinalizationRegistry
89
+ f.bigint = BigInt
90
+ f.canvas = HTMLCanvasElement
91
+ f.pointer = PointerEvent
92
+ f.anim = Animation
93
+ f.rtc = RTCPeerConnection
94
+ f.mr = MediaRecorder
95
+ f.geo = navigator.geolocation
96
+ f.vib = navigator.vibrate
97
+ f.ps = PerformanceObserver
98
+ f.xhr = XMLHttpRequest
99
+ return f
100
+ }
101
+ module.exports = { probeFeatures }