@yaks/esbuild 0.0.0-stage → 0.2.36

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 (123) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +450 -2
  3. package/_dist/bundle.d.ts +6 -0
  4. package/_dist/bundle.d.ts.map +1 -0
  5. package/_dist/compile.d.ts +72 -0
  6. package/_dist/compile.d.ts.map +1 -0
  7. package/_dist/dependencies.d.ts +15 -0
  8. package/_dist/dependencies.d.ts.map +1 -0
  9. package/_dist/file.d.ts +185 -0
  10. package/_dist/file.d.ts.map +1 -0
  11. package/_dist/graph.d.ts +104 -0
  12. package/_dist/graph.d.ts.map +1 -0
  13. package/_dist/home.d.ts +15 -0
  14. package/_dist/home.d.ts.map +1 -0
  15. package/_dist/link.d.ts +192 -0
  16. package/_dist/link.d.ts.map +1 -0
  17. package/_dist/lock.d.ts +30 -0
  18. package/_dist/lock.d.ts.map +1 -0
  19. package/_dist/mod.d.ts +6 -0
  20. package/_dist/mod.d.ts.map +1 -0
  21. package/_dist/pack.d.ts +42 -0
  22. package/_dist/pack.d.ts.map +1 -0
  23. package/_dist/package.d.ts +11 -0
  24. package/_dist/package.d.ts.map +1 -0
  25. package/_dist/plan.d.ts +135 -0
  26. package/_dist/plan.d.ts.map +1 -0
  27. package/_dist/platform.d.ts +27 -0
  28. package/_dist/platform.d.ts.map +1 -0
  29. package/_dist/resolve.d.ts +42 -0
  30. package/_dist/resolve.d.ts.map +1 -0
  31. package/_dist/shelf.d.ts +11 -0
  32. package/_dist/shelf.d.ts.map +1 -0
  33. package/_dist/strip.d.ts +51 -0
  34. package/_dist/strip.d.ts.map +1 -0
  35. package/_dist/timing.d.ts +6 -0
  36. package/_dist/timing.d.ts.map +1 -0
  37. package/_dist/unpack.d.ts +14 -0
  38. package/_dist/unpack.d.ts.map +1 -0
  39. package/analysis.js +72 -0
  40. package/analysis.js.map +1 -0
  41. package/analysis.ts +82 -0
  42. package/bundle.js +320 -0
  43. package/bundle.js.map +1 -0
  44. package/bundle.ts +415 -0
  45. package/common.js +129 -0
  46. package/common.js.map +1 -0
  47. package/common.ts +138 -0
  48. package/compile.js +500 -0
  49. package/compile.js.map +1 -0
  50. package/compile.ts +622 -0
  51. package/container.js +142 -0
  52. package/container.js.map +1 -0
  53. package/container.ts +183 -0
  54. package/deno.json +1 -0
  55. package/dependencies.js +31 -0
  56. package/dependencies.js.map +1 -0
  57. package/dependencies.ts +40 -0
  58. package/file.js +303 -0
  59. package/file.js.map +1 -0
  60. package/file.ts +443 -0
  61. package/forward.ts +49 -0
  62. package/graph.js +297 -0
  63. package/graph.js.map +1 -0
  64. package/graph.ts +360 -0
  65. package/home.js +40 -0
  66. package/home.js.map +1 -0
  67. package/home.ts +52 -0
  68. package/link.js +455 -0
  69. package/link.js.map +1 -0
  70. package/link.ts +596 -0
  71. package/lock.js +129 -0
  72. package/lock.js.map +1 -0
  73. package/lock.ts +161 -0
  74. package/mod.js +14 -0
  75. package/mod.js.map +1 -0
  76. package/mod.ts +43 -0
  77. package/npm.js +362 -0
  78. package/npm.js.map +1 -0
  79. package/npm.ts +429 -0
  80. package/pack.js +188 -0
  81. package/pack.js.map +1 -0
  82. package/pack.ts +225 -0
  83. package/package.js +199 -0
  84. package/package.js.map +1 -0
  85. package/package.json +60 -4
  86. package/package.ts +255 -0
  87. package/plan.js +273 -0
  88. package/plan.js.map +1 -0
  89. package/plan.ts +395 -0
  90. package/platform.js +160 -0
  91. package/platform.js.map +1 -0
  92. package/platform.ts +238 -0
  93. package/resolve.js +86 -0
  94. package/resolve.js.map +1 -0
  95. package/resolve.ts +144 -0
  96. package/said.js +44 -0
  97. package/said.js.map +1 -0
  98. package/said.ts +61 -0
  99. package/serve.ts +37 -0
  100. package/sha256.js +7 -0
  101. package/sha256.js.map +1 -0
  102. package/sha256.ts +10 -0
  103. package/shared.js +646 -0
  104. package/shared.js.map +1 -0
  105. package/shared.ts +813 -0
  106. package/shelf.js +73 -0
  107. package/shelf.js.map +1 -0
  108. package/shelf.ts +110 -0
  109. package/strip.js +114 -0
  110. package/strip.js.map +1 -0
  111. package/strip.ts +117 -0
  112. package/tar.js +87 -0
  113. package/tar.js.map +1 -0
  114. package/tar.ts +99 -0
  115. package/timing.js +37 -0
  116. package/timing.js.map +1 -0
  117. package/timing.ts +71 -0
  118. package/unpack.js +40 -0
  119. package/unpack.js.map +1 -0
  120. package/unpack.ts +60 -0
  121. package/used.js +91 -0
  122. package/used.js.map +1 -0
  123. package/used.ts +116 -0
package/shared.ts ADDED
@@ -0,0 +1,813 @@
1
+ // Browser packages compiled apart from app entries: toolkit packages, Preact
2
+ // and Signals, and each npm package more than one of a page's consumers would
3
+ // otherwise carry (./common.ts), trimmed to the exports of it they use
4
+ // (./used.ts). A dependency group's URL names all its emitted bytes and
5
+ // resources; package cycles share a splitting build so there is one instance
6
+ // and no cycle between content-addressed URLs. Completed groups are retained
7
+ // under a byte budget across compiler jobs, and on the shelf across
8
+ // containers.
9
+ import { analysisCache } from './analysis.js'
10
+ import { parse } from 'es-module-lexer/js'
11
+ import {
12
+ bundle,
13
+ type Input,
14
+ type Options,
15
+ packaged,
16
+ type Source,
17
+ Stopped,
18
+ } from './bundle.js'
19
+ import { type Common, common } from './common.js'
20
+ import { commonJS, exportsOf } from './package.js'
21
+ import { packageOf } from './graph.js'
22
+ import { homes } from './home.js'
23
+ import type { Files } from './npm.ts'
24
+ import {
25
+ type Catalog,
26
+ located,
27
+ moved,
28
+ packageFor,
29
+ type Seed,
30
+ } from './platform.js'
31
+ import { type Shelf, type Shelves, under } from './shelf.js'
32
+ import { phase, type Report } from './timing.js'
33
+ import { offered, used } from './used.js'
34
+
35
+ let singletons = [
36
+ 'preact',
37
+ '@preact/signals',
38
+ '@preact/signals-core',
39
+ 'react',
40
+ 'react-dom',
41
+ ]
42
+
43
+ let production: Options = {
44
+ minify: true,
45
+ define: { 'process.env.NODE_ENV': '"production"' },
46
+ }
47
+
48
+ /** Shared modules by path, the URL of each specifier, and the tarball each
49
+ * npm package home they name is filled from, by its SHA-256. */
50
+ type Shared = {
51
+ files: Record<string, string>
52
+ urls: Record<string, string>
53
+ tarballs: Record<string, string>
54
+ }
55
+ let sorted = (value: Record<string, unknown>) =>
56
+ Object.entries(value).sort(([a], [b]) => a.localeCompare(b))
57
+ let digest = async (value: unknown) =>
58
+ [
59
+ ...new Uint8Array(
60
+ await crypto.subtle.digest(
61
+ 'SHA-256',
62
+ new TextEncoder().encode(JSON.stringify(value)),
63
+ ),
64
+ ),
65
+ ].map((n) => n.toString(16).padStart(2, '0')).join('')
66
+
67
+ // Each group a compile built, by what decides it, in memory and on the shelf:
68
+ // a container that starts after a page edit changed the shared npm exports
69
+ // builds the groups that edit reached, not every group.
70
+ let held = analysisCache<Shared>(16 << 20, digest)
71
+
72
+ // Tarjan's dependency order: dependencies precede their consumers, with each
73
+ // strongly connected component emitted as a single group.
74
+ let groups = (names: string[], deps: (name: string) => string[]) => {
75
+ let next = 0
76
+ let indices = new Map<string, number>(), low = new Map<string, number>()
77
+ let stack: string[] = [], pending = new Set<string>(), out: string[][] = []
78
+ let visit = (name: string) => {
79
+ indices.set(name, next)
80
+ low.set(name, next++)
81
+ stack.push(name)
82
+ pending.add(name)
83
+ for (let dep of deps(name)) {
84
+ if (!indices.has(dep)) {
85
+ visit(dep)
86
+ low.set(name, Math.min(low.get(name)!, low.get(dep)!))
87
+ } else if (pending.has(dep)) {
88
+ low.set(name, Math.min(low.get(name)!, indices.get(dep)!))
89
+ }
90
+ }
91
+ if (low.get(name) != indices.get(name)) return
92
+ let group: string[] = [], dep: string
93
+ do {
94
+ dep = stack.pop()!
95
+ pending.delete(dep)
96
+ group.push(dep)
97
+ } while (dep != name)
98
+ out.push(group.sort())
99
+ }
100
+ for (let name of names.sort()) if (!indices.has(name)) visit(name)
101
+ return out
102
+ }
103
+
104
+ // The module a shared npm specifier is built from: the exports of it that the
105
+ // page's consumers use, and no more, the way a bundled copy kept only those.
106
+ let picked = (spec: string, names: string[]) =>
107
+ names.length
108
+ ? `export { ${names.map((n) => JSON.stringify(n)).join(', ')} } ` +
109
+ `from ${JSON.stringify(spec)}`
110
+ : `import ${JSON.stringify(spec)}`
111
+
112
+ /** What a page shares beyond its toolkit packages, Preact and Signals: each
113
+ * npm package's entry modules, by specifier, and the shared packages each
114
+ * consumer's build imports. */
115
+ type Carried = {
116
+ modules: Record<string, Record<string, string>>
117
+ uses: Common['uses']
118
+ }
119
+
120
+ let analysis = analysisCache<Carried>(4 << 20, digest)
121
+
122
+ // The toolkit's half of the analysis, kept apart from the pages' and by
123
+ // package: a page edit reads the pages again and no toolkit entry, and a
124
+ // change to one toolkit package reads that package's entries again and no
125
+ // other's. Of each package, its module graph and the exports of each shared
126
+ // specifier its entries use; of the specifiers, every export each has.
127
+ let kitGraphs = analysisCache<Record<string, Input>>(16 << 20, digest)
128
+ let kitUses = analysisCache<Record<string, string[]>>(4 << 20, digest)
129
+ let offers = analysisCache<Record<string, string[]>>(4 << 20, digest)
130
+
131
+ // What the pages share beyond the packages already shared, read from a build
132
+ // of each consumer's entries: the pages', and each toolkit package's, with the
133
+ // other toolkit packages left outside, since each is a consumer of its own.
134
+ // Only a toolkit package depending on an npm package can carry one beside the
135
+ // pages, so the builds run only then. A build that fails shares nothing more:
136
+ // the failing entry's own build says why.
137
+ let carried = async (
138
+ fs: Files,
139
+ pages: string[],
140
+ stops: string[],
141
+ catalog: Catalog,
142
+ setup: Seed,
143
+ timing?: Report,
144
+ shelves?: Shelves,
145
+ ): Promise<Carried> => {
146
+ let toolkits = Object.keys(setup.platform)
147
+ let options = {
148
+ ...production,
149
+ packages: setup.aliases,
150
+ jsxImportSource: setup.jsxImportSource,
151
+ }
152
+ let npm = toolkits.some((name) =>
153
+ Object.entries(catalog[name].dependencies).some(([dep, version]) =>
154
+ version != 'platform' && !singletons.includes(dep)
155
+ )
156
+ )
157
+ if (!npm) return { modules: {}, uses: {} }
158
+ let kit = [
159
+ toolkits.map((name) => [name, catalog[name].dependencies]),
160
+ options,
161
+ ]
162
+ // The toolkit packages a consumer's build leaves outside: all but itself.
163
+ let outside = (self: string) =>
164
+ new Set(toolkits.filter((name) => name != self))
165
+ // What decides a toolkit package's half, beside the sources it reads.
166
+ let own = (name: string) => [
167
+ name,
168
+ catalog[name].dependencies,
169
+ [...outside(name)].sort(),
170
+ options,
171
+ ]
172
+ let shelf = shelves && under(shelves.builds, 'analysis')
173
+ let graphOf = (source: Source, self: string, files: string[]) =>
174
+ bundle(
175
+ source,
176
+ Object.fromEntries(files.map((path, i) => [`entry-${i}`, path])),
177
+ {
178
+ ...options,
179
+ minify: false,
180
+ graph: true,
181
+ external: (spec) =>
182
+ outside(self).has(packageOf(spec) ?? '') ? spec : undefined,
183
+ },
184
+ ).then((built) => built.inputs!)
185
+ try {
186
+ let key = await digest([pages, stops, ...kit])
187
+ return await analysis(key, (path) => fs.read(path), async (source) => {
188
+ let kits = Object.fromEntries(
189
+ toolkits.map((name) => [name, Object.values(exportsOf(source, name))]),
190
+ )
191
+ let consumers = { '': pages, ...kits }
192
+ let graph = phase(timing, 'carried')
193
+ let found: Common
194
+ try {
195
+ let graphs = await Promise.all([
196
+ graphOf(source, '', pages),
197
+ ...toolkits.map(async (name) =>
198
+ kitGraphs(
199
+ await digest(['graph', ...own(name)]),
200
+ source.read,
201
+ (kept) => graphOf(kept, name, kits[name]),
202
+ { shelf },
203
+ )
204
+ ),
205
+ ])
206
+ found = common(Object.assign({}, ...graphs), consumers, new Set(stops))
207
+ } finally {
208
+ graph()
209
+ }
210
+ let trimmed = phase(timing, 'used')
211
+ let names: Record<string, string[]>
212
+ try {
213
+ let specs: Record<string, string> = Object.assign(
214
+ {},
215
+ ...Object.values(found.entries),
216
+ )
217
+ let all = await offers(
218
+ await digest(['offered', specs]),
219
+ source.read,
220
+ (kept) => offered(kept, specs),
221
+ { shelf },
222
+ )
223
+ let uses = await Promise.all([
224
+ used(source, pages, specs, options, all, outside('')),
225
+ ...toolkits.map(async (name) =>
226
+ kitUses(
227
+ await digest(['used', specs, ...own(name)]),
228
+ source.read,
229
+ (kept) =>
230
+ used(kept, kits[name], specs, options, all, outside(name)),
231
+ { shelf },
232
+ )
233
+ ),
234
+ ])
235
+ names = Object.fromEntries(
236
+ Object.keys(specs).map((spec) => [
237
+ spec,
238
+ all[spec].filter((name) =>
239
+ uses.some((u) => u[spec].includes(name))
240
+ ),
241
+ ]),
242
+ )
243
+ } finally {
244
+ trimmed()
245
+ }
246
+ let modules = Object.fromEntries(
247
+ Object.entries(found.entries).map(([name, specs]) => [
248
+ name,
249
+ Object.fromEntries(
250
+ Object.keys(specs).map((spec) => [spec, picked(spec, names[spec])]),
251
+ ),
252
+ ]),
253
+ )
254
+ return { modules, uses: found.uses }
255
+ }, { shelf })
256
+ } catch (e) {
257
+ if (e instanceof Stopped) throw e
258
+ return { modules: {}, uses: {} }
259
+ }
260
+ }
261
+
262
+ /** Compile browser toolkit packages, Preact, Signals and the npm packages more
263
+ * than one of the pages' consumers imports, per source/dependency identity.
264
+ * All returned paths live under the host's `__packages/` root. */
265
+ let builds = async (
266
+ fs: Files,
267
+ setup: Seed,
268
+ catalog: Catalog,
269
+ origin: string,
270
+ pages: string[] = [],
271
+ options: { timing?: Report; shelves?: Shelves } = {},
272
+ ): Promise<Shared> => {
273
+ let { timing, shelves } = options
274
+ let names = Object.keys(setup.platform)
275
+ for (let name of singletons) {
276
+ if (fs.read(`node_modules/${name}/package.json`) != null) names.push(name)
277
+ }
278
+ let npm = await carried(fs, pages, names, catalog, setup, timing, shelves)
279
+ names.push(...Object.keys(npm.modules))
280
+ names.sort()
281
+ // Every group at once, by what decides them that is not read from `fs`:
282
+ // the toolkit's sources as the catalog has them, not as it names them.
283
+ let key = await digest([
284
+ names,
285
+ npm,
286
+ names.map((name) => catalog[name] ?? null),
287
+ setup.aliases,
288
+ origin,
289
+ ])
290
+ return await outputs(
291
+ key,
292
+ (path) => fs.read(path),
293
+ (source) =>
294
+ grouped(
295
+ { read: source.read, tarball: (name) => fs.tarball(name) },
296
+ setup,
297
+ catalog,
298
+ origin,
299
+ names,
300
+ npm,
301
+ timing,
302
+ shelves && under(shelves.builds, 'groups'),
303
+ ),
304
+ {
305
+ shelf: shelves && under(shelves.builds, 'groups'),
306
+ looked: timing && ((hit, ms) => {
307
+ timing('cache', ms)
308
+ if (hit) timing('hits', 1)
309
+ }),
310
+ },
311
+ )
312
+ }
313
+
314
+ // What every shared group of a compile is, kept whole: a container that
315
+ // starts takes it from the shelf in one read rather than one per group.
316
+ let outputs = analysisCache<Shared>(16 << 20, digest)
317
+
318
+ // Each group, in dependency order, from memory or the shelf where its sources
319
+ // are unchanged, or built.
320
+ let grouped = async (
321
+ fs: Pick<Files, 'read' | 'tarball'>,
322
+ setup: Seed,
323
+ catalog: Catalog,
324
+ origin: string,
325
+ names: string[],
326
+ npm: Carried,
327
+ timing?: Report,
328
+ shelf?: Shelf,
329
+ ): Promise<Shared> => {
330
+ let has = new Set(names)
331
+ let deps = (name: string) => {
332
+ let pkg = JSON.parse(fs.read(`node_modules/${name}/package.json`)!)
333
+ return [
334
+ ...new Set([
335
+ ...Object.keys({
336
+ ...pkg.dependencies,
337
+ ...pkg.peerDependencies,
338
+ ...catalog[name]?.dependencies,
339
+ // React DOM's CommonJS imports React synchronously. Put both
340
+ // behind the same browser module graph and one React instance.
341
+ ...name == 'react' && { 'react-dom': '*' },
342
+ }),
343
+ ...npm.uses[name] ?? [],
344
+ ]),
345
+ ].flatMap((dep) => packageFor(setup, dep) ?? [])
346
+ .filter((dep, i, all) => has.has(dep) && all.indexOf(dep) == i).sort()
347
+ }
348
+ let result: Shared = { files: {}, urls: {}, tarballs: {} }
349
+ for (let group of groups(names, deps)) {
350
+ let own = new Set(group)
351
+ // Each entry by specifier, and the entry modules written here, by path.
352
+ let entries: Record<string, string> = {}
353
+ let picks: Record<string, string> = {}
354
+ for (let name of group) {
355
+ if (!npm.modules[name]) {
356
+ for (let [spec, file] of Object.entries(exportsOf(fs, name))) {
357
+ if (name == 'react' || name == 'react-dom') {
358
+ let entry = entries[spec] = `__picked/${spec}.js`
359
+ picks[entry] = commonJS(fs, file)
360
+ } else entries[spec] = file
361
+ }
362
+ }
363
+ for (let [spec, source] of Object.entries(npm.modules[name] ?? {})) {
364
+ entries[spec] = `__picked/${spec}.js`
365
+ picks[entries[spec]] = source
366
+ }
367
+ }
368
+ let resources: Record<string, string> = {}
369
+ let sources: Record<string, string> = {}
370
+ for (let name of group) {
371
+ for (let [path, source] of Object.entries(catalog[name]?.files ?? {})) {
372
+ sources[`node_modules/${name}/${path}`] = source
373
+ }
374
+ for (
375
+ let [path, text] of Object.entries(catalog[name]?.resources ?? {})
376
+ ) {
377
+ resources[`resources/${name}/${path}`] = text
378
+ }
379
+ }
380
+ // npm pins are scoped to this group's dependency closure: an unrelated
381
+ // app dependency does not change the toolkit's URL or its cache identity.
382
+ let pins: Record<string, string> = {}
383
+ let visit = (name: string) => {
384
+ if (has.has(name) && !own.has(name) || name in pins) return
385
+ let text = fs.read(`node_modules/${name}/package.json`)
386
+ if (!text) return
387
+ pins[name] = text
388
+ let pkg = JSON.parse(text)
389
+ for (let dep of Object.keys(pkg.dependencies ?? {})) visit(dep)
390
+ }
391
+ for (let name of group) visit(name)
392
+ let dependencies: Record<string, string> = {}
393
+ for (let name of group) {
394
+ for (let dep of deps(name)) {
395
+ if (own.has(dep)) continue
396
+ for (let [spec, url] of Object.entries(result.urls)) {
397
+ if (packageOf(spec) == dep) dependencies[spec] = url
398
+ }
399
+ }
400
+ }
401
+ let key = await digest([
402
+ sorted(entries),
403
+ sorted(picks),
404
+ sorted(sources),
405
+ sorted(resources),
406
+ sorted(pins),
407
+ sorted(dependencies),
408
+ setup.aliases,
409
+ origin,
410
+ ])
411
+ let rewritten = located(
412
+ sources,
413
+ 'module.js',
414
+ (path) => `./resources/${path.slice('node_modules/'.length)}`,
415
+ )
416
+ let read = (path: string) =>
417
+ picks[path] ??
418
+ (path.startsWith('node_modules/') && !path.split('/').includes('..')
419
+ ? rewritten[path] ?? fs.read(path)
420
+ : null)
421
+ let compiled = await held(key, read, async (source) => {
422
+ let specs = Object.keys(entries).sort()
423
+ let points = Object.fromEntries(specs.map((spec, i) => [
424
+ `entry-${i}`,
425
+ entries[spec],
426
+ ]))
427
+ // An npm package module is served from its package's home.
428
+ let home = homes((name) => fs.tarball(name), origin)
429
+ let emitted = await bundle(source, points, {
430
+ ...production,
431
+ packages: setup.aliases,
432
+ moved: home.moved,
433
+ external: (spec) => {
434
+ let name = packageOf(spec)
435
+ if (!name || !name.startsWith('@yaks/') && !has.has(name)) return
436
+ if (own.has(name)) {
437
+ if (packaged(fs, spec)) return
438
+ throw new Error(
439
+ `${spec}: missing browser export in the platform catalog`,
440
+ )
441
+ }
442
+ let url = result.urls[spec]
443
+ if (url) return url
444
+ throw new Error(
445
+ `${spec}: missing browser package or export in the platform catalog`,
446
+ )
447
+ },
448
+ })
449
+ for (let [path, text] of Object.entries(emitted.files)) {
450
+ if (!path.endsWith('.js')) continue
451
+ for (let imp of parse(text)[0]) {
452
+ if (
453
+ imp.n?.startsWith('.') &&
454
+ !(imp.n.replace(/^\.\//, '') in emitted.files)
455
+ ) {
456
+ throw new Error(
457
+ `${
458
+ group.join(', ')
459
+ } imports ${imp.n}, which names no emitted file`,
460
+ )
461
+ }
462
+ if (imp.n?.startsWith('/')) {
463
+ throw new Error(
464
+ `${
465
+ group.join(', ')
466
+ } imports ${imp.n}, which names no emitted file`,
467
+ )
468
+ }
469
+ if (imp.n && packageOf(imp.n)) {
470
+ throw new Error(
471
+ `${group.join(', ')} imports ${imp.n}, which is not installed`,
472
+ )
473
+ }
474
+ }
475
+ }
476
+ let outputs: Record<string, string> = {
477
+ ...emitted.files,
478
+ ...resources,
479
+ // Distinct packages with identical code still own distinct module state.
480
+ 'modules.json': JSON.stringify(
481
+ Object.fromEntries(specs.map((spec, i) => [
482
+ spec,
483
+ `entry-${i}.js`,
484
+ ])),
485
+ ),
486
+ }
487
+ let hash = await digest(sorted(outputs))
488
+ let prefix = `__packages/${hash}/`
489
+ return {
490
+ files: Object.fromEntries(
491
+ Object.entries(outputs).map(([path, text]) => [
492
+ prefix + path,
493
+ text,
494
+ ]),
495
+ ),
496
+ urls: Object.fromEntries(specs.map((spec, i) => [
497
+ spec,
498
+ `${origin}/${prefix}entry-${i}.js`,
499
+ ])),
500
+ tarballs: home.tarballs,
501
+ }
502
+ }, {
503
+ shelf,
504
+ looked: timing && ((hit, ms) => {
505
+ timing('cache', ms)
506
+ timing(hit ? 'hits' : 'misses', 1)
507
+ }),
508
+ })
509
+ Object.assign(result.files, compiled.files)
510
+ Object.assign(result.urls, compiled.urls)
511
+ Object.assign(result.tarballs, compiled.tarballs)
512
+ }
513
+ return result
514
+ }
515
+
516
+ /** Forget every shared group and analysis memory holds, as a container that
517
+ * restarts does. */
518
+ export let forget = (): void => {
519
+ held.clear()
520
+ analysis.clear()
521
+ kitGraphs.clear()
522
+ kitUses.clear()
523
+ offers.clear()
524
+ outputs.clear()
525
+ }
526
+
527
+ /** Compile shared groups. `groups` excludes carried/used, and includes the
528
+ * `cache` subset; the callback also reports group cache hit/miss counts. */
529
+ export let shared = async (
530
+ fs: Files,
531
+ setup: Seed,
532
+ catalog: Catalog,
533
+ origin: string,
534
+ pages: string[] = [],
535
+ options: { timing?: Report; shelves?: Shelves } = {},
536
+ ): Promise<Shared> => {
537
+ if (!options.timing) {
538
+ return await builds(fs, setup, catalog, origin, pages, options)
539
+ }
540
+ let at = performance.now(), discovery = 0
541
+ try {
542
+ return await builds(fs, setup, catalog, origin, pages, {
543
+ shelves: options.shelves,
544
+ timing: (name, value) => {
545
+ if (name == 'carried' || name == 'used') discovery += value
546
+ options.timing!(name, value)
547
+ },
548
+ })
549
+ } finally {
550
+ options.timing('groups', Math.max(0, performance.now() - at - discovery))
551
+ }
552
+ }
553
+
554
+ /** Replace a browser package import, refusing a toolkit import that cannot be
555
+ * served: a package the app's package.json does not declare, or an export
556
+ * the platform's copy of a declared one does not have, such as one newer than
557
+ * the platform serving the app. An import the page's own import map resolves
558
+ * (`mapped`) is the browser's and stays as written. Ordinary npm imports
559
+ * remain part of the app's entry. */
560
+ export let external = (
561
+ urls: Shared['urls'],
562
+ mapped: string[] = [],
563
+ ): Options['external'] =>
564
+ (spec) => {
565
+ if (mapped.includes(spec)) return spec
566
+ let url = urls[spec]
567
+ if (url) return url
568
+ let name = packageOf(spec) ?? ''
569
+ if (!spec.startsWith('@yaks/') && !singletons.includes(name)) return
570
+ let served = Object.keys(urls).filter((s) => packageOf(s) == name).sort()
571
+ throw new Error(
572
+ served.length
573
+ ? `${spec}: the platform's ${name} has no such browser export; it ` +
574
+ `exports ${served.join(', ')}. Import one of those, or deploy ` +
575
+ `again once the platform's ${name} exports it`
576
+ : `${spec}: missing browser package in the platform catalog; add ` +
577
+ `"${name}": ${
578
+ spec.startsWith('@yaks/') ? '"platform"' : '"<npm version range>"'
579
+ } to package.json dependencies, or map ${spec} in the import map ` +
580
+ 'of every page that loads this script',
581
+ )
582
+ }
583
+
584
+ // A shared module's path under `__packages/`, or '' for another URL.
585
+ let pathIn = (origin: string) => (url: string) =>
586
+ url.startsWith(`${origin}/`) ? url.slice(origin.length + 1) : ''
587
+
588
+ // What a shared module exports, through its `export*from`s.
589
+ let exported = (files: Shared['files'], origin: string) => {
590
+ let pathOf = pathIn(origin)
591
+ let exportsOf = (url: string, seen = new Set<string>()): Set<string> => {
592
+ let text = files[pathOf(url)]
593
+ let names = new Set<string>()
594
+ if (text == null || seen.has(url)) return names
595
+ seen.add(url)
596
+ let [imports, exports] = parse(text)
597
+ for (let e of exports) names.add(e.n)
598
+ for (let i of imports) {
599
+ if (i.d != -1 || !i.n) continue
600
+ if (!/^export\s*\*\s*from/.test(text.slice(i.ss, i.se))) continue
601
+ for (let n of exportsOf(new URL(i.n, url).href, seen)) {
602
+ if (n != 'default') names.add(n)
603
+ }
604
+ }
605
+ return names
606
+ }
607
+ return exportsOf
608
+ }
609
+
610
+ /// unexported('import{a,b as c}from"https://o/__packages/h/e.js"', { '__packages/h/e.js': 'let a,x;export{a,x as b}' }, 'https://o') -> []
611
+ /// unexported('import{show}from"https://o/__packages/h/e.js"', { '__packages/h/e.js': 'export*from"./c.js"', '__packages/h/c.js': 'export let a,b' }, 'https://o', { '@yaks/cli/answer': 'https://o/__packages/h/e.js' }) -> ['imports show from @yaks/cli/answer, which does not export it; it exports a, b']
612
+ /** The names a compiled page imports from shared modules that those modules
613
+ * do not export, each as an error line naming what the module does export, so
614
+ * the caller can pick the name it meant. esbuild leaves a shared import
615
+ * external and never checks it, and a browser refuses to link a page naming
616
+ * one, so the whole page's script stops; the compile refuses it instead, and
617
+ * the last release keeps serving. A namespace or dynamic import names
618
+ * nothing to check. */
619
+ export let unexported = (
620
+ code: string,
621
+ files: Shared['files'],
622
+ origin: string,
623
+ urls: Shared['urls'] = {},
624
+ ): string[] => {
625
+ let specs = new Map(Object.entries(urls).map(([spec, url]) => [url, spec]))
626
+ let pathOf = pathIn(origin)
627
+ let exportsOf = exported(files, origin)
628
+ return parse(code)[0].flatMap((i) => {
629
+ let url = i.n
630
+ if (i.d != -1 || !url || files[pathOf(url)] == null) return []
631
+ let clause = code.slice(i.ss, i.se).replace(/\s*from\s*["'][^]*$/, '')
632
+ .replace(/^(import|export)\s*/, '')
633
+ if (/^["']|\*/.test(clause)) return []
634
+ let names = [
635
+ ...(/^[\w$]+/.test(clause) ? ['default'] : []),
636
+ ...(/\{([^}]*)\}/.exec(clause)?.[1].split(',') ?? [])
637
+ .map((n) => n.trim().split(/\s+as\s+/)[0])
638
+ .filter(Boolean),
639
+ ]
640
+ let has = exportsOf(url)
641
+ let them = [...has].sort((a, b) => a.localeCompare(b)).join(', ')
642
+ return names.filter((n) => !has.has(n))
643
+ .map((n) =>
644
+ `imports ${n} from ${specs.get(url) ?? url}, which does not export it` +
645
+ (them ? `; it exports ${them}` : '')
646
+ )
647
+ })
648
+ }
649
+
650
+ /// flat('import"https://o/__packages/a/e.js"', { '__packages/a/e.js': 'import"./c.js"', '__packages/a/c.js': '' }, 'https://o') -> 'import"https://o/__packages/a/e.js"\nimport"https://o/__packages/a/c.js";'
651
+ /// flat('let n = 1', {}, 'https://o') -> 'let n = 1'
652
+ /** A page entry that also imports every shared module its own imports reach:
653
+ * the whole graph a browser links before the page runs, to judge it as one
654
+ * (./compile.ts `browserless`). The entry's own imports come first, and they
655
+ * already reach everything it adds, so nothing runs in another order.
656
+ * Dynamic imports stay lazy. */
657
+ export let flat = (
658
+ code: string,
659
+ files: Shared['files'],
660
+ origin: string,
661
+ ): string => {
662
+ let statics = (text: string, at?: string) =>
663
+ parse(text)[0].flatMap((i) => {
664
+ if (i.d != -1 || !i.n) return []
665
+ try {
666
+ return [new URL(i.n, at).href]
667
+ } catch {
668
+ return []
669
+ }
670
+ })
671
+ let own = statics(code)
672
+ let reached = new Set(own)
673
+ for (let url of reached) {
674
+ let path = url.startsWith(`${origin}/`) ? url.slice(origin.length + 1) : ''
675
+ let text = files[path]
676
+ if (text != null) { for (let dep of statics(text, url)) reached.add(dep) }
677
+ }
678
+ let added = [...reached].filter((url) => !own.includes(url))
679
+ return added.length
680
+ ? `${code}\n${added.map((url) => `import${JSON.stringify(url)};`).join('')}`
681
+ : code
682
+ }
683
+
684
+ // A name as an import or export clause writes it: bare, or quoted.
685
+ let written = (name: string) =>
686
+ /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name)
687
+
688
+ // The name the pack exports module `i`'s export `name` by. A name ends at its
689
+ // last `$`, so two modules' names never meet.
690
+ let aliasOf = (name: string, i: number) => written(`${name}$${i}`)
691
+
692
+ // A name as a clause writes it, bare or quoted, as the name itself.
693
+ let unquoted = (name: string) => /^["']/.test(name) ? JSON.parse(name) : name
694
+
695
+ /// repointed('import"U"', 'P', 0, new Set()) -> 'import"P"'
696
+ /// repointed('import d,{a as b,c}from"U"', 'P', 2, new Set()) -> 'import{default$2 as d,a$2 as b,c$2 as c}from"P"'
697
+ /// repointed('import*as n from"U"', 'P', 1, new Set()) -> 'import{$1 as n}from"P"'
698
+ /// repointed('export*from"U"', 'P', 3, new Set(['a', 'default'])) -> 'export{a$3 as a}from"P"'
699
+ /// repointed('export*as n from"U"', 'P', 3, new Set()) -> 'export{$3 as n}from"P"'
700
+ /** An import or export statement of shared module `i`, importing the same
701
+ * bindings from the pack at `url`. `names` are what the module exports, for
702
+ * an `export*from`. */
703
+ export let repointed = (
704
+ statement: string,
705
+ url: string,
706
+ i: number,
707
+ names: Set<string>,
708
+ ): string => {
709
+ let to = JSON.stringify(url)
710
+ let [, verb, clause] =
711
+ /^(import|export)\s*([^]*?)\s*(?:from\s*)?["'][^"']*["']\s*;?$/
712
+ .exec(statement)!
713
+ if (!clause) return `import${to}`
714
+ if (clause == '*') {
715
+ let all = [...names].filter((n) => n != 'default')
716
+ .map((n) => `${aliasOf(n, i)} as ${written(n)}`)
717
+ return `export{${all.join(',')}}from${to}`
718
+ }
719
+ let picked: string[] = []
720
+ let first = /^([\w$]+)\s*(?:,\s*|$)/.exec(clause)
721
+ if (first) {
722
+ picked.push(`${aliasOf('default', i)} as ${first[1]}`)
723
+ clause = clause.slice(first[0].length)
724
+ }
725
+ let star = /^\*\s*as\s+([\w$]+)$/.exec(clause)
726
+ if (star) picked.push(`$${i} as ${star[1]}`)
727
+ let list = /^\{([^}]*)\}$/.exec(clause)?.[1] ?? ''
728
+ for (let part of list.split(',').map((p) => p.trim()).filter(Boolean)) {
729
+ let [name, local = name] = part.split(/\s+as\s+/)
730
+ picked.push(`${aliasOf(unquoted(name), i)} as ${local}`)
731
+ }
732
+ return `${verb}{${picked.join(',')}}from${to}`
733
+ }
734
+
735
+ /** The packed pages and the pack's files. */
736
+ type Packed = { pages: Record<string, string>; files: Shared['files'] }
737
+
738
+ /** Link every shared module the pages import into one pack, and point the
739
+ * pages at it. A shared group is a graph of small modules, the splitting
740
+ * build that keeps one instance of each, and a cold page asked for every one
741
+ * of them: 95 files for a form. The pack is one file. Each module keeps its
742
+ * identity: the pages import the one pack, in which each module is one
743
+ * module whose `import.meta.url` is still its own URL, so `new
744
+ * URL('./Button.css', import.meta.url)` loads what it did. The pack is named
745
+ * by its bytes, like a group, so a release that changes only the app's own
746
+ * code keeps it, and apps importing the same shared modules share it.
747
+ * Modules evaluate in the order the pages first import them, and one
748
+ * imported lazily, by a page or a shared module, evaluates when the import
749
+ * runs; its bytes come with the pack, since splitting them out split the
750
+ * pack into a chunk for each set of lazy imports reaching its code. */
751
+ export let pack = async (
752
+ pages: Record<string, string>,
753
+ files: Shared['files'],
754
+ origin: string,
755
+ ): Promise<Packed> => {
756
+ let pathOf = pathIn(origin)
757
+ let exportsOf = exported(files, origin)
758
+ let shared = (i: { n?: string; d: number }) =>
759
+ i.d != -2 && !!i.n && files[pathOf(i.n)] != null
760
+ let order: string[] = [], eager = new Set<string>()
761
+ for (let code of Object.values(pages)) {
762
+ for (let i of parse(code)[0].filter(shared)) {
763
+ if (!order.includes(i.n!)) order.push(i.n!)
764
+ if (i.d == -1) eager.add(i.n!)
765
+ }
766
+ }
767
+ if (!order.length) return { pages, files: {} }
768
+ let entry = order.map((url, i) => {
769
+ let at = JSON.stringify(url)
770
+ if (!eager.has(url)) return `export let $${i}=()=>import(${at});`
771
+ let names = [...exportsOf(url)].map((n) =>
772
+ `${written(n)} as ${aliasOf(n, i)}`
773
+ )
774
+ return `export*as $${i} from${at};export{${names.join(',')}}from${at};`
775
+ }).join('\n')
776
+ let ENTRY = '__pack.js'
777
+ let built = await bundle(
778
+ {
779
+ read: (path) => {
780
+ if (path == ENTRY) return entry
781
+ let text = files[path]
782
+ if (text == null || !path.endsWith('.js')) return text ?? null
783
+ // A module keeps reading the URL it is served from in its group.
784
+ return moved(text, () => JSON.stringify(`${origin}/${path}`))
785
+ },
786
+ },
787
+ ENTRY,
788
+ {
789
+ minify: true,
790
+ alias: (spec) => files[pathOf(spec)] != null ? pathOf(spec) : undefined,
791
+ },
792
+ )
793
+ let prefix = `__packages/${await digest([['pack.js', built.code]])}/`
794
+ let url = `${origin}/${prefix}pack.js`
795
+ let repoint = (code: string) => {
796
+ for (let i of parse(code)[0].filter(shared).toReversed()) {
797
+ let n = order.indexOf(i.n!)
798
+ let to = i.d == -1
799
+ ? repointed(code.slice(i.ss, i.se), url, n, exportsOf(i.n!))
800
+ : `import(${JSON.stringify(url)}).then(m=>m.$${n}${
801
+ eager.has(i.n!) ? '' : '()'
802
+ })`
803
+ code = code.slice(0, i.ss) + to + code.slice(i.se)
804
+ }
805
+ return code
806
+ }
807
+ return {
808
+ pages: Object.fromEntries(
809
+ Object.entries(pages).map(([path, code]) => [path, repoint(code)]),
810
+ ),
811
+ files: { [`${prefix}pack.js`]: built.code },
812
+ }
813
+ }