dsh-ptc-plus 0.3.2 → 0.4.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 (206) hide show
  1. package/README.en.md +63 -80
  2. package/README.md +63 -80
  3. package/assets/ptc-plus-bindings-en.png +0 -0
  4. package/assets/ptc-plus-bindings-zh.png +0 -0
  5. package/assets/ptc-plus-repair-en.png +0 -0
  6. package/assets/ptc-plus-repair-zh.png +0 -0
  7. package/assets/ptc-plus-repl-workspace-en.png +0 -0
  8. package/assets/ptc-plus-repl-workspace-zh.png +0 -0
  9. package/assets/ptc-plus-settings-en.png +0 -0
  10. package/assets/ptc-plus-settings-zh.png +0 -0
  11. package/client.js +30827 -742
  12. package/compiler-amaro.cjs +5 -0
  13. package/compiler-amaro.cjs.map +6 -0
  14. package/compiler-asset-124f80c1bba92ff5fe79cfec6e8ad518f476de4a42514cae3919538887f510e8.txt +1 -0
  15. package/compiler-assets.json +3 -0
  16. package/compiler-core.cjs +556 -0
  17. package/compiler-core.cjs.map +6 -0
  18. package/compiler-platform.cjs +2 -0
  19. package/compiler-platform.cjs.map +6 -0
  20. package/compiler-typescript.cjs +388 -0
  21. package/compiler-typescript.cjs.map +6 -0
  22. package/docs/README.md +7 -0
  23. package/docs/adr/0004-declare-program-bindings-at-the-host.md +1 -1
  24. package/docs/adr/0006-rewrite-module-syntax-with-an-ast.md +5 -3
  25. package/docs/adr/0007-separate-worker-transport-from-session-semantics.md +1 -1
  26. package/docs/adr/0009-bound-expensive-acceptance-default.md +2 -0
  27. package/docs/adr/0010-session-log-derived-recovery-tips.md +59 -5
  28. package/docs/adr/0011-isolate-the-local-recovery-tip-provider.md +1 -1
  29. package/docs/adr/0012-preserve-mixed-destructuring-initialization.md +3 -1
  30. package/docs/adr/0013-isolate-repl-redeclaration-convenience.md +3 -1
  31. package/docs/adr/0014-persist-cell-rewrite-policy.md +6 -2
  32. package/docs/adr/0015-preserve-source-positions-through-rewrites.md +1 -1
  33. package/docs/adr/0016-archive-resolved-review-findings.md +1 -1
  34. package/docs/adr/0017-track-the-latest-dsh-public-surface.md +49 -0
  35. package/docs/adr/0018-use-versioned-fixture-for-ab-benchmark.md +3 -3
  36. package/docs/adr/0019-plugin-settings-and-kill-switch.md +5 -3
  37. package/docs/adr/0020-optional-cordis-tools-in-ptc-mode.md +2 -2
  38. package/docs/adr/0021-separate-host-bootstrap-from-session-runtime.md +12 -0
  39. package/docs/adr/0023-global-user-bindings.md +104 -0
  40. package/docs/adr/0024-repl-console-observation.md +33 -0
  41. package/docs/adr/0025-use-versioned-logical-binding-identities.md +119 -0
  42. package/docs/adr/0026-persist-the-delivery-verdict-against-the-verified-candidate.md +21 -0
  43. package/docs/adr/0027-run-the-session-kernel-in-a-killable-helper-process.md +37 -0
  44. package/docs/adr/0028-attach-to-the-host-ptc-execution-seam.md +103 -0
  45. package/docs/adr/0029-keep-plugin-unavailability-out-of-the-host-agent-lifecycle.md +27 -0
  46. package/docs/adr/0030-serve-both-typert-codec-generations-from-one-codec.md +27 -0
  47. package/docs/architecture.md +77 -21
  48. package/docs/binding-review-placement-design.md +200 -0
  49. package/docs/capability-projection.md +1 -1
  50. package/docs/client-ui.md +95 -19
  51. package/docs/durability-design.md +28 -10
  52. package/docs/evaluation.md +78 -6
  53. package/docs/installation.md +41 -6
  54. package/docs/publishing.md +5 -3
  55. package/docs/runtime-reference.md +76 -25
  56. package/docs/semantic-validation.md +29 -0
  57. package/docs/stateful-binding-updates-proposal.md +759 -0
  58. package/docs/user-bindings.en.md +66 -0
  59. package/docs/user-bindings.md +66 -0
  60. package/docs/value-wire.md +3 -3
  61. package/docs/verification-optimization-work.md +41 -0
  62. package/docs/verification.md +71 -0
  63. package/index.js +369 -92
  64. package/internal/ast-traversal.js +5 -2
  65. package/internal/async-local-storage-intrinsics.js +38 -0
  66. package/internal/binding-declaration-contract.js +8 -0
  67. package/internal/binding-descriptors.js +1 -0
  68. package/internal/binding-pattern-traversal.js +25 -0
  69. package/internal/binding-pattern.js +26 -29
  70. package/internal/binding-source-analysis.js +708 -0
  71. package/internal/binding-update-policy.js +72 -0
  72. package/internal/bounded-worker-round.js +56 -0
  73. package/internal/callable-definition-environment.js +42 -0
  74. package/internal/callable-source-catalog.js +129 -0
  75. package/internal/callable-source-encoding.js +47 -0
  76. package/internal/callable-source-facts.js +459 -0
  77. package/internal/callable-source-format.js +2 -0
  78. package/internal/callable-source-lowering.js +123 -0
  79. package/internal/cell-analysis-contract.js +25 -0
  80. package/internal/cell-analysis.js +253 -290
  81. package/internal/cell-completion.js +15 -0
  82. package/internal/cell-error.js +7 -0
  83. package/internal/cell-parser.js +66 -0
  84. package/internal/cell-rewriter.js +3 -677
  85. package/internal/commonjs-export-evidence.js +63 -0
  86. package/internal/commonjs-source-evidence.js +72 -0
  87. package/internal/compiler-amaro.cjs +2 -0
  88. package/internal/compiler-compression.js +12 -0
  89. package/internal/compiler-data.js +58 -0
  90. package/internal/compiler-descriptors.js +54 -0
  91. package/internal/compiler-dynamic-cache.js +48 -0
  92. package/internal/compiler-entry.js +35 -0
  93. package/internal/compiler-generated-names.js +17 -0
  94. package/internal/compiler-intrinsics.js +50 -0
  95. package/internal/compiler-module-links.js +37 -0
  96. package/internal/compiler-operations.js +61 -0
  97. package/internal/compiler-platform-factory.js +84 -0
  98. package/internal/compiler-platform.js +136 -0
  99. package/internal/compiler-record-roles.js +53 -0
  100. package/internal/compiler-region-output.js +259 -0
  101. package/internal/compiler-resource-lowering.js +103 -0
  102. package/internal/compiler-scope-facts.js +115 -0
  103. package/internal/compiler-service.js +109 -0
  104. package/internal/compiler-source-cache.js +32 -0
  105. package/internal/compiler-source-pieces.js +93 -0
  106. package/internal/compiler-source-regions.js +132 -0
  107. package/internal/compiler-storage-source.js +54 -0
  108. package/internal/compiler-text.js +15 -0
  109. package/internal/compiler-typescript.cjs +2 -0
  110. package/internal/config-spec.js +83 -27
  111. package/internal/cordis-tools-owner.js +130 -21
  112. package/internal/diagnostic.js +27 -1
  113. package/internal/direct-surface-owner.js +76 -23
  114. package/internal/dynamic-binding-evidence.js +16 -0
  115. package/internal/dynamic-environment-compiler.js +779 -0
  116. package/internal/dynamic-environment-integration.js +91 -0
  117. package/internal/dynamic-environment-runtime.js +383 -0
  118. package/internal/dynamic-native-calls.js +153 -0
  119. package/internal/dynamic-native-runtime.js +262 -0
  120. package/internal/dynamic-scope-analysis.js +90 -0
  121. package/internal/edit-transport-owner.js +27 -2
  122. package/internal/execution-seam-compat.js +193 -0
  123. package/internal/failure-reporting.js +136 -28
  124. package/internal/host-rpc.js +66 -0
  125. package/internal/isolated-worker.js +555 -0
  126. package/internal/kernel-child.js +139 -0
  127. package/internal/kernel-worker.js +1179 -233
  128. package/internal/language-semantics.js +14 -0
  129. package/internal/legacy-binding-catalog.js +48 -0
  130. package/internal/legacy-cell-analysis.js +600 -0
  131. package/internal/legacy-cell-parser.js +50 -0
  132. package/internal/legacy-cell-rewriter.js +631 -0
  133. package/internal/legacy-repl-convenience.js +291 -0
  134. package/internal/managed-module-operations.js +170 -0
  135. package/internal/module-compilation.js +322 -0
  136. package/internal/module-runtime-platform.js +19 -0
  137. package/internal/module-transform-contract.js +42 -0
  138. package/internal/native-await-declarations.js +68 -0
  139. package/internal/native-root-compilation.js +54 -0
  140. package/internal/native-root-dynamic.js +67 -0
  141. package/internal/record-utils.js +24 -15
  142. package/internal/recovery-tips.js +27 -15
  143. package/internal/rejected-cell-editor.js +13 -8
  144. package/internal/repl-convenience.js +2 -289
  145. package/internal/repl-memory-projection.js +81 -12
  146. package/internal/repl-observation-interest.js +70 -0
  147. package/internal/repl-rewrite-contract.js +6 -0
  148. package/internal/repl-scope-normalizer.js +2091 -0
  149. package/internal/repl-value-observer.js +117 -0
  150. package/internal/rpc-contract.js +52 -0
  151. package/internal/runtime-bridge-owner.js +172 -28
  152. package/internal/runtime-config.js +48 -52
  153. package/internal/runtime-contexts.js +82 -10
  154. package/internal/runtime-intrinsics.js +101 -0
  155. package/internal/runtime-messages.js +111 -0
  156. package/internal/session-cell-executor.js +402 -87
  157. package/internal/session-journal-recovery.js +684 -0
  158. package/internal/session-journal-schema.js +123 -0
  159. package/internal/session-journal.js +199 -654
  160. package/internal/session-log-view.js +42 -9
  161. package/internal/session-runtime.js +257 -95
  162. package/internal/session-state.js +247 -71
  163. package/internal/source-position-map.js +230 -71
  164. package/internal/stateful-module-compiler.js +154 -0
  165. package/internal/stateful-module-runtime.js +303 -0
  166. package/internal/stateful-root-compiler.js +600 -0
  167. package/internal/stateful-root-runtime.js +340 -0
  168. package/internal/typert-codec-compat.js +28 -0
  169. package/internal/typescript-transform.js +31 -0
  170. package/internal/user-binding-authoring.js +70 -0
  171. package/internal/user-binding-console-worker.js +244 -0
  172. package/internal/user-binding-console.js +148 -0
  173. package/internal/user-binding-draft-projection.js +335 -0
  174. package/internal/user-binding-model-context.js +31 -0
  175. package/internal/user-binding-runner.js +56 -0
  176. package/internal/user-bindings-owner.js +1065 -0
  177. package/internal/user-bindings-store.js +293 -0
  178. package/internal/user-bindings.js +361 -0
  179. package/internal/value-wire-schema.js +28 -0
  180. package/internal/value-wire.js +130 -91
  181. package/internal/worker-client.js +57 -67
  182. package/internal/worker-cwd-virtualization.js +80 -53
  183. package/internal/worker-environment.js +65 -0
  184. package/internal/worker-output-relay.js +29 -0
  185. package/internal/worker-repl-realm.js +134 -0
  186. package/internal/worker-shutdown.js +14 -0
  187. package/package.json +76 -7
  188. package/src/client-activity.js +95 -53
  189. package/src/client-authoring-view.js +580 -0
  190. package/src/client-binding-review.js +230 -0
  191. package/src/client-bindings-data.js +29 -0
  192. package/src/client-catalog.js +127 -0
  193. package/src/client-code-editor.js +84 -0
  194. package/src/client-console.js +112 -0
  195. package/src/client-copy.js +370 -0
  196. package/src/client-feature-gates.js +62 -0
  197. package/src/client-host-compat.js +150 -0
  198. package/src/client-indicator-view.js +267 -0
  199. package/src/client-repl-view.js +292 -0
  200. package/src/client-rpc.js +20 -0
  201. package/src/client-settings-view.js +221 -0
  202. package/src/client-styles.js +106 -0
  203. package/src/client-tool-view.js +108 -0
  204. package/src/client-transport.js +159 -0
  205. package/src/client-workbench.js +521 -0
  206. package/src/client.js +233 -615
@@ -1,678 +1,4 @@
1
- /** Adapts TypeScript module declarations to the async function-body grammar used by PTC cells. */
2
- import { parse } from '@babel/parser'
3
- import traverseModule, { Hub, NodePath } from '@babel/traverse'
4
- import { bindingNodes, createGeneratedNameAllocator } from './binding-pattern.js'
5
- import { applySourceEdits, createMappedTextBuilder, identitySourceMap } from './source-position-map.js'
6
- import {
7
- LEGACY_DEFAULT_EXPORT_BINDING,
8
- LIVE_DEFAULT_EXPORT_BINDING,
9
- } from './repl-rewrite-contract.js'
1
+ /** Historical module adapter; new cells use the versioned logical compiler. */
2
+ export { ModuleRewriteError } from './cell-error.js'
10
3
 
11
- export const STRIP_PREFIX = 'async function __ptc_cell__(){\n'
12
- export const STRIP_SUFFIX = '\n}'
13
-
14
- export class ModuleRewriteError extends SyntaxError {
15
- constructor(message, cellPosition) {
16
- super(message)
17
- if (cellPosition !== undefined) this.cellPosition = cellPosition
18
- }
19
- }
20
-
21
- const PARSER_PLUGINS = ['typescript', 'importAttributes']
22
- const TYPE_DECLARATIONS = new Set([
23
- 'TSDeclareFunction',
24
- 'TSEnumDeclaration',
25
- 'TSInterfaceDeclaration',
26
- 'TSModuleDeclaration',
27
- 'TSTypeAliasDeclaration',
28
- ])
29
- const traverse = traverseModule.default ?? traverseModule
30
-
31
- function declaredTypeNames(program) {
32
- const names = new Set()
33
- for (const node of program.body) {
34
- const declaration = node.type === 'ExportNamedDeclaration' || node.type === 'ExportDefaultDeclaration'
35
- ? node.declaration
36
- : node
37
- if (TYPE_DECLARATIONS.has(declaration?.type) && declaration.id?.type === 'Identifier') {
38
- names.add(declaration.id.name)
39
- }
40
- }
41
- return names
42
- }
43
-
44
- function createProgramScope(file) {
45
- const hub = new Hub()
46
- hub.buildError = (node, message, ErrorType = TypeError) => {
47
- const error = new ErrorType(message)
48
- error.loc = node.loc?.start
49
- return error
50
- }
51
- const path = NodePath.get({ hub, parent: file, container: file, key: 'program' })
52
- path.setContext()
53
- path.scope = path.getScope()
54
- path.scope.init()
55
- return path.scope
56
- }
57
-
58
- function validateLocalExports(file, programScope) {
59
- const localExports = file.program.body.filter(node => node.type === 'ExportNamedDeclaration'
60
- && node.source === null && node.declaration === null)
61
- const valueSpecifiers = localExports.flatMap(node => node.specifiers
62
- .filter(specifier => specifier.exportKind !== 'type'))
63
- if (valueSpecifiers.length === 0) return
64
- const typeNames = declaredTypeNames(file.program)
65
- const missing = valueSpecifiers.find(specifier => (
66
- programScope.getBinding(specifier.local.name) === undefined && !typeNames.has(specifier.local.name)
67
- ))
68
- if (missing === undefined) return
69
- throw new ModuleRewriteError(`Export '${missing.local.name}' is not defined.`, {
70
- line: missing.local.loc.start.line,
71
- column: missing.local.loc.start.column + 1,
72
- })
73
- }
74
-
75
- function parseCell(code) {
76
- try {
77
- const file = parse(code, {
78
- sourceType: 'script',
79
- allowAwaitOutsideFunction: true,
80
- allowImportExportEverywhere: true,
81
- allowReturnOutsideFunction: true,
82
- allowUndeclaredExports: true,
83
- plugins: PARSER_PLUGINS,
84
- })
85
- validateLocalExports(file, createProgramScope(file))
86
- return file.program
87
- } catch (error) {
88
- if (error instanceof ModuleRewriteError) throw error
89
- const loc = error?.loc
90
- throw new ModuleRewriteError(error instanceof Error ? error.message : String(error),
91
- Number.isSafeInteger(loc?.line) && Number.isSafeInteger(loc?.column)
92
- ? { line: loc.line, column: loc.column + 1 }
93
- : undefined)
94
- }
95
- }
96
-
97
- function parseSource(node) { return node.source.value }
98
- function importOptions(node) {
99
- if (!node.attributes || node.attributes.length === 0) return undefined
100
- const attributes = Object.fromEntries(node.attributes.map((attribute) => {
101
- const key = attribute.key.type === 'Identifier' ? attribute.key.name : attribute.key.value
102
- return [key, attribute.value.value]
103
- }))
104
- const keyword = node.attributes[0].type === 'ImportAttribute' ? 'with' : 'assert'
105
- return { [keyword]: attributes }
106
- }
107
- function moduleLoad(node, source, global = undefined, requiredExports = []) {
108
- return {
109
- source,
110
- ...(global === undefined ? {} : { global }),
111
- ...(requiredExports.length === 0 ? {} : { requiredExports }),
112
- ...(importOptions(node) === undefined ? {} : { options: importOptions(node) }),
113
- position: {
114
- line: node.source.loc.start.line,
115
- column: node.source.loc.start.column + 1,
116
- end: {
117
- line: node.source.loc.end.line,
118
- column: node.source.loc.end.column + 1,
119
- },
120
- },
121
- }
122
- }
123
- function record(kind, description, node, source) {
124
- return { kind, description, ...(source === undefined ? {} : { source }), at: node.start }
125
- }
126
- function preserveLines(original, replacement = '') {
127
- const missing = (original.match(/\n/g)?.length ?? 0) - (replacement.match(/\n/g)?.length ?? 0)
128
- return missing > 0 ? replacement + '\n'.repeat(missing) : replacement
129
- }
130
- function editNode(edits, node, code, replacement = '') {
131
- const mapped = typeof replacement === 'string' ? { text: replacement } : replacement
132
- const separated = node.end < code.length && code[node.end] !== '\n' && code[node.end] !== '\r'
133
- ? `${mapped.text}\n`
134
- : mapped.text
135
- edits.push({
136
- start: node.start,
137
- end: node.end,
138
- text: preserveLines(code.slice(node.start, node.end), separated),
139
- ...(mapped.mappings === undefined ? {} : { mappings: mapped.mappings }),
140
- })
141
- }
142
- function edit(edits, start, end, text) { edits.push({ start, end, text }) }
143
- function localName(specifier) { return specifier.local.name }
144
- function importedName(specifier) {
145
- if (specifier.type === 'ImportDefaultSpecifier') return 'default'
146
- if (specifier.type === 'ImportNamespaceSpecifier') return undefined
147
- return specifier.imported.type === 'Identifier' ? specifier.imported.name : specifier.imported.value
148
- }
149
-
150
- function importEdits(
151
- node,
152
- code,
153
- edits,
154
- rewrites,
155
- imports,
156
- importDeclarations,
157
- moduleLoads,
158
- namespaceCaptures,
159
- allocateNamespace,
160
- allocateGlobal,
161
- ) {
162
- const source = parseSource(node)
163
- const rewrite = record('import', `adapted the static import of ${JSON.stringify(source)} for REPL execution`, node, source)
164
- if (node.importKind === 'type') {
165
- editNode(edits, node, code)
166
- rewrites.push(record('import', `removed the type-only import of ${JSON.stringify(source)}`, node, source))
167
- return
168
- }
169
- if (node.specifiers.length > 0 && node.specifiers.every(specifier => specifier.importKind === 'type')) {
170
- editNode(edits, node, code)
171
- rewrites.push(record('import', `removed the type-only import of ${JSON.stringify(source)}`, node, source))
172
- return
173
- }
174
- const specifiers = node.specifiers.filter(specifier => specifier.importKind !== 'type')
175
- if (specifiers.length === 0) {
176
- moduleLoads.push(moduleLoad(node, source))
177
- editNode(edits, node, code)
178
- rewrites.push(rewrite)
179
- return
180
- }
181
- const namespace = allocateNamespace('import_namespace')
182
- const global = allocateGlobal('import_global')
183
- const requiredExports = []
184
- for (const specifier of specifiers) {
185
- const imported = importedName(specifier)
186
- imports.set(localName(specifier), { namespace, imported })
187
- if (imported !== undefined && !requiredExports.includes(imported)) requiredExports.push(imported)
188
- importDeclarations.push({
189
- name: localName(specifier),
190
- kind: 'import',
191
- span: {
192
- line: specifier.local.loc.start.line,
193
- column: specifier.local.loc.start.column + 1,
194
- end: {
195
- line: specifier.local.loc.end.line,
196
- column: specifier.local.loc.end.column + 1,
197
- },
198
- },
199
- definitionSpan: {
200
- line: node.loc.start.line,
201
- column: node.loc.start.column + 1,
202
- end: {
203
- line: node.loc.end.line,
204
- column: node.loc.end.column + 1,
205
- },
206
- },
207
- original: true,
208
- })
209
- }
210
- moduleLoads.push(moduleLoad(node, source, global, requiredExports))
211
- namespaceCaptures.push({ namespace, global, source: node.source })
212
- editNode(edits, node, code)
213
- rewrites.push(rewrite)
214
- }
215
-
216
- function importPrologueEdit(program, tree, namespaceCaptures) {
217
- if (namespaceCaptures.length === 0) return undefined
218
- const directive = tree.directives.at(-1)
219
- let insertion = directive?.end ?? tree.interpreter?.end ?? 0
220
- if (directive === undefined && tree.interpreter !== null && tree.interpreter !== undefined) {
221
- if (program[insertion] === '\r' && program[insertion + 1] === '\n') insertion += 2
222
- else if (program[insertion] === '\r' || program[insertion] === '\n') insertion += 1
223
- }
224
- const builder = createMappedTextBuilder(program)
225
- if (directive !== undefined && program[insertion - 1] !== ';') builder.append(';')
226
- for (const capture of namespaceCaptures) {
227
- builder.append('const ')
228
- builder.appendMapped(capture.namespace, capture.source.start, capture.source.end)
229
- builder.append(' = ')
230
- builder.appendMapped(capture.global, capture.source.start, capture.source.end)
231
- builder.append(';')
232
- }
233
- return { start: insertion, end: insertion, ...builder.result() }
234
- }
235
-
236
- function importMember(namespace, imported) {
237
- return imported === undefined ? namespace
238
- : /^[A-Za-z_$][\w$]*$/.test(imported) ? `${namespace}.${imported}`
239
- : `${namespace}[${JSON.stringify(imported)}]`
240
- }
241
-
242
- function appendReadonlyImportWrite(builder, appendValue) {
243
- builder.append("((__dsh_ptc_import_value__) => { throw new TypeError('Assignment to constant variable.'); })(")
244
- appendValue()
245
- builder.append(')')
246
- }
247
-
248
- function importedBindingFor(path, identifier, imports) {
249
- const binding = imports.get(identifier.name)
250
- return binding !== undefined && path.scope.getBinding(identifier.name) === undefined ? binding : undefined
251
- }
252
-
253
- function importedWriteBinding(path, imports) {
254
- if (path.isAssignmentExpression() && path.node.left.type === 'Identifier') {
255
- return importedBindingFor(path, path.node.left, imports)
256
- }
257
- return undefined
258
- }
259
-
260
- function assertNoImportedWriteAncestor(path, imports) {
261
- if (path.findParent(parent => importedWriteBinding(parent, imports) !== undefined) !== null) {
262
- throw new ModuleRewriteError('nested assignment to an imported binding is not supported')
263
- }
264
- }
265
-
266
- function preserveExpressionStatementBoundary(path, edits) {
267
- const statement = path.findParent(parent => parent.isExpressionStatement())
268
- if (statement?.node.expression.start === path.node.start) {
269
- edits.push({ start: path.node.start, end: path.node.start, text: ';' })
270
- }
271
- }
272
-
273
- function assertNoDynamicImportResolution(tree, imports) {
274
- if (imports.size === 0) return
275
- traverse(tree, {
276
- WithStatement() {
277
- throw new ModuleRewriteError('with statement is not supported while imported bindings are active')
278
- },
279
- CallExpression(path) {
280
- if (path.node.callee.type === 'Identifier' && path.node.callee.name === 'eval'
281
- && !imports.has('eval') && path.scope.getBinding('eval') === undefined) {
282
- throw new ModuleRewriteError('direct eval is not supported while imported bindings are active')
283
- }
284
- },
285
- })
286
- }
287
-
288
- function rewriteImportReferences(code, sourceMap, imports) {
289
- if (imports.size === 0) return { code, sourceMap }
290
- const parseRewritten = source => parse(source, {
291
- sourceType: 'script',
292
- allowAwaitOutsideFunction: true,
293
- allowReturnOutsideFunction: true,
294
- plugins: PARSER_PLUGINS,
295
- })
296
- let file = parseRewritten(code)
297
- const writeEdits = []
298
- traverse(file, {
299
- AssignmentExpression(path) {
300
- if (path.node.left.type !== 'Identifier') {
301
- const names = bindingNodes(path.node.left).map(node => node.name)
302
- if (names.some(name => imports.has(name) && path.scope.getBinding(name) === undefined)) {
303
- throw new ModuleRewriteError('destructuring assignment to an imported binding is not supported')
304
- }
305
- return
306
- }
307
- const binding = importedBindingFor(path, path.node.left, imports)
308
- if (binding === undefined) return
309
- assertNoImportedWriteAncestor(path, imports)
310
- const member = importMember(binding.namespace, binding.imported)
311
- const builder = createMappedTextBuilder(code)
312
- const appendMember = () => builder.appendMapped(member, path.node.left.start, path.node.left.end)
313
- const appendRight = () => builder.appendSource(path.node.right.start, path.node.right.end)
314
- if (path.node.operator === '=') appendReadonlyImportWrite(builder, appendRight)
315
- else if (['&&=', '||=', '??='].includes(path.node.operator)) {
316
- const operator = path.node.operator.slice(0, -1)
317
- appendMember()
318
- builder.append(` ${operator} `)
319
- appendReadonlyImportWrite(builder, appendRight)
320
- } else {
321
- appendReadonlyImportWrite(builder, () => {
322
- appendMember()
323
- builder.append(` ${path.node.operator.slice(0, -1)} (`)
324
- appendRight()
325
- builder.append(')')
326
- })
327
- }
328
- writeEdits.push({
329
- start: path.node.start,
330
- end: path.node.end,
331
- ...builder.result(),
332
- })
333
- },
334
- UpdateExpression(path) {
335
- if (path.node.argument.type !== 'Identifier') return
336
- const binding = importedBindingFor(path, path.node.argument, imports)
337
- if (binding === undefined) return
338
- assertNoImportedWriteAncestor(path, imports)
339
- const member = importMember(binding.namespace, binding.imported)
340
- const builder = createMappedTextBuilder(code)
341
- builder.append('((__dsh_ptc_import_value__) => { ')
342
- builder.append(path.node.operator === '++' ? '__dsh_ptc_import_value__++' : '__dsh_ptc_import_value__--')
343
- builder.append("; throw new TypeError('Assignment to constant variable.'); })(")
344
- builder.appendMapped(member, path.node.argument.start, path.node.argument.end)
345
- builder.append(')')
346
- writeEdits.push({
347
- start: path.node.start,
348
- end: path.node.end,
349
- ...builder.result(),
350
- })
351
- },
352
- UnaryExpression(path) {
353
- if (path.node.operator !== 'delete' || path.node.argument.type !== 'Identifier') return
354
- if (importedBindingFor(path, path.node.argument, imports) !== undefined) {
355
- throw new ModuleRewriteError('delete of an imported binding is not supported')
356
- }
357
- },
358
- ForInStatement(path) {
359
- if (path.node.left.type === 'VariableDeclaration') return
360
- const names = bindingNodes(path.node.left)
361
- if (names.some(node => importedBindingFor(path, node, imports) !== undefined)) {
362
- throw new ModuleRewriteError('for-in assignment to an imported binding is not supported')
363
- }
364
- },
365
- ForOfStatement(path) {
366
- if (path.node.left.type === 'VariableDeclaration') return
367
- const names = bindingNodes(path.node.left)
368
- if (names.some(node => importedBindingFor(path, node, imports) !== undefined)) {
369
- throw new ModuleRewriteError('for-of assignment to an imported binding is not supported')
370
- }
371
- },
372
- })
373
- const written = applySourceEdits(code, sourceMap, writeEdits)
374
- file = parseRewritten(written.code)
375
- const readEdits = []
376
- traverse(file, {
377
- ReferencedIdentifier(path) {
378
- const binding = imports.get(path.node.name)
379
- if (binding === undefined || path.scope.getBinding(path.node.name) !== undefined) return
380
- const member = importMember(binding.namespace, binding.imported)
381
- const parent = path.parent
382
- if (((parent.type === 'CallExpression' || parent.type === 'OptionalCallExpression') && parent.callee === path.node)
383
- || (parent.type === 'TaggedTemplateExpression' && parent.tag === path.node)) {
384
- preserveExpressionStatementBoundary(path, readEdits)
385
- readEdits.push({ start: path.node.start, end: path.node.end, text: `(0, ${member})` })
386
- return
387
- }
388
- if (parent.type === 'ObjectProperty' && parent.shorthand && parent.value === path.node) {
389
- readEdits.push({ start: parent.start, end: parent.end, text: `${path.node.name}: ${member}` })
390
- return
391
- }
392
- readEdits.push({ start: path.node.start, end: path.node.end, text: member })
393
- },
394
- })
395
- return applySourceEdits(written.code, written.sourceMap, readEdits)
396
- }
397
-
398
- function exportNamedEdits(node, code, edits, rewrites, moduleLoads) {
399
- const onlyTypeSpecifiers = node.specifiers.length > 0
400
- && node.specifiers.every(specifier => specifier.exportKind === 'type')
401
- if (node.exportKind === 'type' || onlyTypeSpecifiers
402
- || (node.declaration && ['TSInterfaceDeclaration', 'TSTypeAliasDeclaration', 'TSDeclareFunction'].includes(node.declaration.type))) {
403
- editNode(edits, node, code)
404
- const source = node.exportKind === 'type' || onlyTypeSpecifiers ? 'type' : node.declaration.type
405
- rewrites.push(record('export', 'removed a type-only export declaration', node, source))
406
- return
407
- }
408
- if (node.source !== null && node.source !== undefined) {
409
- const source = parseSource(node)
410
- moduleLoads.push(moduleLoad(node, source))
411
- editNode(edits, node, code)
412
- rewrites.push(record('export', `converted the re-export of ${JSON.stringify(source)} into a side-effect import`, node, source))
413
- return
414
- }
415
- if (node.declaration !== null && node.declaration !== undefined) {
416
- edit(edits, node.start, node.declaration.start, preserveLines(code.slice(node.start, node.declaration.start)))
417
- rewrites.push(record('export', 'stripped the export modifier from a top-level declaration', node))
418
- return
419
- }
420
- editNode(edits, node, code)
421
- rewrites.push(record('export', 'removed a local re-export declaration', node))
422
- }
423
-
424
- function exportAllEdits(node, code, edits, rewrites, moduleLoads) {
425
- if (node.exportKind === 'type') {
426
- editNode(edits, node, code)
427
- rewrites.push(record('export', 'removed a type-only export declaration', node, 'type'))
428
- return
429
- }
430
- const source = parseSource(node)
431
- moduleLoads.push(moduleLoad(node, source))
432
- editNode(edits, node, code)
433
- rewrites.push(record('export', `converted the re-export of ${JSON.stringify(source)} into a side-effect import`, node, source))
434
- }
435
-
436
- function exportDefaultEdits({
437
- node,
438
- code,
439
- edits,
440
- rewrites,
441
- defaultNameAvailable,
442
- exportDeclarations,
443
- imports,
444
- allocateNamespace,
445
- commitSignal,
446
- commitTargets,
447
- }) {
448
- const declaration = node.declaration
449
- if (declaration.type === 'TSInterfaceDeclaration') {
450
- editNode(edits, node, code)
451
- rewrites.push(record('export', 'removed a type-only export declaration', node, 'interface'))
452
- return
453
- }
454
- if (!defaultNameAvailable) {
455
- throw new ModuleRewriteError(
456
- 'export default cannot be exposed as __default because that name is already declared',
457
- { line: node.loc.start.line, column: node.loc.start.column + 1 },
458
- )
459
- }
460
- const namedDeclaration = (declaration.type === 'FunctionDeclaration'
461
- || declaration.type === 'ClassDeclaration') && declaration.id !== null
462
- const retainedNamedDeclaration = namedDeclaration && declaration.id.name !== '__default'
463
- const existingAlias = imports.get('__default')
464
- const reuseAlias = existingAlias?.syntheticDefault === true
465
- const namespace = reuseAlias ? existingAlias.namespace : allocateNamespace('default_namespace')
466
- const member = importMember(namespace, 'default')
467
- imports.set('__default', {
468
- namespace,
469
- imported: 'default',
470
- syntheticDefault: true,
471
- commitDependency: '__default',
472
- })
473
- commitTargets.add('__default')
474
- if (declaration.type === 'ClassDeclaration' && declaration.id !== null) {
475
- commitTargets.add(declaration.id.name)
476
- }
477
- exportDeclarations.push({
478
- name: '__default',
479
- kind: declaration.type === 'FunctionDeclaration'
480
- ? 'function'
481
- : declaration.type === 'ClassDeclaration' ? 'class' : 'variable',
482
- commitDependency: '__default',
483
- span: {
484
- line: node.loc.start.line,
485
- column: node.loc.start.column + 1,
486
- end: {
487
- line: node.loc.end.line,
488
- column: node.loc.end.column + 1,
489
- },
490
- },
491
- definitionSpan: {
492
- line: node.loc.start.line,
493
- column: node.loc.start.column + 1,
494
- end: {
495
- line: node.loc.end.line,
496
- column: node.loc.end.column + 1,
497
- },
498
- },
499
- original: true,
500
- })
501
- const rewrite = record('export', 'converted the default export into a local __default binding', node)
502
- const commit = [...new Set([...(declaration.type === 'ClassDeclaration' && declaration.id !== null
503
- ? [declaration.id.name]
504
- : []), '__default'])]
505
- .map(name => ` this[${JSON.stringify(commitSignal)}](${JSON.stringify(name)});`)
506
- .join('')
507
- const assignmentPrefix = reuseAlias ? `${member} = ` : `const ${namespace} = { default: `
508
- const assignmentSuffix = reuseAlias ? '' : ' }'
509
- if (retainedNamedDeclaration) {
510
- edit(edits, node.start, declaration.start, preserveLines(code.slice(node.start, declaration.start)))
511
- edit(edits, node.end, node.end,
512
- `; ${assignmentPrefix}${declaration.id.name}${assignmentSuffix};${commit}`)
513
- } else if (declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') {
514
- const prefix = code.slice(node.start, declaration.start)
515
- edit(edits, node.start, declaration.start, preserveLines(prefix, assignmentPrefix))
516
- edit(edits, node.end, node.end, `${assignmentSuffix};${commit}`)
517
- } else {
518
- const prefix = code.slice(node.start, declaration.start)
519
- edit(edits, node.start, declaration.start, preserveLines(prefix, assignmentPrefix))
520
- edit(edits, node.end, node.end, `${assignmentSuffix};${commit}`)
521
- }
522
- rewrites.push(rewrite)
523
- }
524
-
525
- function legacyExportDefaultEdits(node, code, edits, rewrites, defaultNameAvailable, exportDeclarations) {
526
- const declaration = node.declaration
527
- if (declaration.type === 'TSInterfaceDeclaration') {
528
- editNode(edits, node, code)
529
- rewrites.push(record('export', 'removed a type-only export declaration', node, 'interface'))
530
- return
531
- }
532
- if (declaration.id?.name === '__default') {
533
- edit(edits, node.start, declaration.start, preserveLines(code.slice(node.start, declaration.start)))
534
- rewrites.push(record('export', 'stripped the export modifier from the __default declaration', node))
535
- return
536
- }
537
- if (!defaultNameAvailable) {
538
- throw new ModuleRewriteError(
539
- 'export default cannot be exposed as __default because that name is already declared',
540
- { line: node.loc.start.line, column: node.loc.start.column + 1 },
541
- )
542
- }
543
- exportDeclarations.push({
544
- name: '__default',
545
- kind: declaration.type === 'FunctionDeclaration'
546
- ? 'function'
547
- : declaration.type === 'ClassDeclaration' ? 'class' : 'variable',
548
- span: {
549
- line: node.loc.start.line,
550
- column: node.loc.start.column + 1,
551
- end: {
552
- line: node.loc.end.line,
553
- column: node.loc.end.column + 1,
554
- },
555
- },
556
- definitionSpan: {
557
- line: node.loc.start.line,
558
- column: node.loc.start.column + 1,
559
- end: {
560
- line: node.loc.end.line,
561
- column: node.loc.end.column + 1,
562
- },
563
- },
564
- original: true,
565
- })
566
- const rewrite = record('export', 'converted the default export into a local __default binding', node)
567
- if (declaration.type === 'FunctionDeclaration' && declaration.id !== null) {
568
- const prefix = code.slice(node.start, declaration.start)
569
- edit(edits, node.start, declaration.start, preserveLines(prefix, `const __default = ${declaration.id.name}; `))
570
- } else if (declaration.type === 'ClassDeclaration' && declaration.id !== null) {
571
- edit(edits, node.start, declaration.start, preserveLines(code.slice(node.start, declaration.start)))
572
- edit(edits, node.end, node.end, `; const __default = ${declaration.id.name};`)
573
- } else if (declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') {
574
- const prefix = code.slice(node.start, declaration.start)
575
- edit(edits, node.start, declaration.start, preserveLines(prefix, 'const __default = '))
576
- edit(edits, node.end, node.end, ';')
577
- } else {
578
- const prefix = code.slice(node.start, declaration.start)
579
- edit(edits, node.start, declaration.start, preserveLines(prefix, 'const __default = '))
580
- }
581
- rewrites.push(rewrite)
582
- }
583
-
584
- function ascending(left, right) { return left.at - right.at }
585
-
586
- export function rewriteModuleImportsExports(program, enabled, existingImports = new Map(), existingNamespaces = new Set(), unavailableNames = new Set(), moduleSemantics = { defaultExportBinding: LIVE_DEFAULT_EXPORT_BINDING }) {
587
- if (![LEGACY_DEFAULT_EXPORT_BINDING, LIVE_DEFAULT_EXPORT_BINDING]
588
- .includes(moduleSemantics?.defaultExportBinding)) {
589
- throw new TypeError('ptc-plus: unsupported default export binding semantics')
590
- }
591
- const tree = parseCell(program)
592
- const edits = []
593
- const rewrites = []
594
- const imports = new Map(existingImports)
595
- const importDeclarations = []
596
- const exportDeclarations = []
597
- const moduleLoads = []
598
- const importNamespaces = new Set(existingNamespaces)
599
- const allocateName = createGeneratedNameAllocator(tree, [...unavailableNames, ...importNamespaces])
600
- const commitSignal = allocateName('redeclaration_commit')
601
- const generatedNamespaces = new Set()
602
- const allocateImportName = purpose => {
603
- const name = allocateName(purpose)
604
- importNamespaces.add(name)
605
- generatedNamespaces.add(name)
606
- return name
607
- }
608
- const namespaceCaptures = []
609
- const commitTargets = new Set()
610
- const currentCellDefaultNameAvailable = !tree.body.some((node) => {
611
- const declaration = node.type === 'ExportNamedDeclaration' ? node.declaration : node
612
- if (declaration?.type === 'VariableDeclaration' && declaration.declare !== true) {
613
- return declaration.declarations.some(entry => bindingNodes(entry.id).some(binding => binding.name === '__default'))
614
- }
615
- if (declaration?.type === 'FunctionDeclaration' || declaration?.type === 'ClassDeclaration') {
616
- return declaration.id?.name === '__default'
617
- }
618
- return node.type === 'ImportDeclaration' && node.importKind !== 'type' && node.specifiers.some(specifier => (
619
- specifier.importKind !== 'type' && specifier.local.name === '__default'
620
- ))
621
- })
622
- const existingDefault = existingImports.get('__default')
623
- const persistentDefaultNameAvailable = !unavailableNames.has('__default')
624
- || existingDefault?.syntheticDefault === true
625
- const defaultNameAvailable = currentCellDefaultNameAvailable
626
- && (moduleSemantics.defaultExportBinding === LEGACY_DEFAULT_EXPORT_BINDING
627
- || persistentDefaultNameAvailable)
628
- for (const node of tree.body) {
629
- if (node.type === 'ImportDeclaration' && enabled.autoRewriteImports) {
630
- importEdits(node, program, edits, rewrites, imports, importDeclarations,
631
- moduleLoads, namespaceCaptures, allocateImportName, allocateName)
632
- }
633
- else if (node.type === 'ExportNamedDeclaration' && enabled.autoStripExports) {
634
- exportNamedEdits(node, program, edits, rewrites, moduleLoads)
635
- }
636
- else if (node.type === 'ExportAllDeclaration' && enabled.autoStripExports) {
637
- exportAllEdits(node, program, edits, rewrites, moduleLoads)
638
- }
639
- else if (node.type === 'ExportDefaultDeclaration' && enabled.autoStripExports) {
640
- if (moduleSemantics.defaultExportBinding === LEGACY_DEFAULT_EXPORT_BINDING) {
641
- legacyExportDefaultEdits(
642
- node, program, edits, rewrites, defaultNameAvailable, exportDeclarations,
643
- )
644
- } else {
645
- exportDefaultEdits({
646
- node,
647
- code: program,
648
- edits,
649
- rewrites,
650
- defaultNameAvailable,
651
- exportDeclarations,
652
- imports,
653
- allocateNamespace: allocateImportName,
654
- commitSignal,
655
- commitTargets,
656
- })
657
- }
658
- }
659
- }
660
- assertNoDynamicImportResolution(tree, imports)
661
- const prologue = importPrologueEdit(program, tree, namespaceCaptures)
662
- if (prologue !== undefined) edits.push(prologue)
663
- const applied = applySourceEdits(program, identitySourceMap(program.length), edits)
664
- const rewritten = rewriteImportReferences(applied.code, applied.sourceMap, imports)
665
- rewrites.sort(ascending)
666
- return {
667
- ...rewritten,
668
- imports,
669
- importNamespaces,
670
- generatedNamespaces,
671
- importDeclarations,
672
- exportDeclarations,
673
- moduleLoads,
674
- commitSignal,
675
- commitTargets,
676
- rewrites: rewrites.map(({ at: _at, ...rest }) => rest),
677
- }
678
- }
4
+ export { rewriteModuleImportsExports } from './legacy-cell-rewriter.js'