@runeditrun/rer 0.2.83 → 0.2.85

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 (269) hide show
  1. package/README.md +21 -24
  2. package/cli/README.md +17 -1
  3. package/cli/authoring.mjs +1 -0
  4. package/cli/bounded.mjs +1 -1
  5. package/cli/business/carry.mjs +149 -0
  6. package/cli/business/command.mjs +6 -1
  7. package/cli/business/connect.mjs +1 -1
  8. package/cli/business/local-commands.mjs +2 -0
  9. package/cli/business/opt-ins.mjs +8 -4
  10. package/cli/business/questions.mjs +4 -1
  11. package/cli/business/state.mjs +1 -1
  12. package/cli/business/supervisor.mjs +7 -1
  13. package/cli/container-transfer.mjs +2 -2
  14. package/cli/contract.mjs +7 -7
  15. package/cli/demo-host.mjs +5 -1
  16. package/cli/demo-native.mjs +2 -1
  17. package/cli/demo.mjs +6 -1
  18. package/cli/deploy-command.mjs +6 -4
  19. package/cli/deploy.mjs +9 -7
  20. package/cli/errors.mjs +1 -1
  21. package/cli/export.mjs +1 -1
  22. package/cli/human-error.mjs +20 -0
  23. package/cli/lifecycle.mjs +23 -5
  24. package/cli/main.mjs +1 -1
  25. package/cli/managed-data-schema.mjs +114 -0
  26. package/cli/managed-data-zip.mjs +116 -0
  27. package/cli/managed-data.mjs +110 -0
  28. package/cli/managed-server.mjs +25 -14
  29. package/cli/native-owner-entry.mjs +86 -0
  30. package/cli/output.mjs +3 -2
  31. package/cli/parse.mjs +3 -3
  32. package/cli/portability-empty.mjs +59 -0
  33. package/cli/portability-migrations.mjs +7 -5
  34. package/cli/portability-policy.mjs +5 -2
  35. package/cli/portability-worker.mjs +15 -6
  36. package/cli/portability.mjs +30 -8
  37. package/cli/ready-summary.mjs +9 -0
  38. package/cli/run-transfers.mjs +37 -0
  39. package/cli/runtime-front-door.mjs +4 -4
  40. package/cli/server-proxy.mjs +4 -3
  41. package/cli/server-registry.mjs +13 -8
  42. package/cli/site.mjs +6 -1
  43. package/cli/transfers.mjs +17 -4
  44. package/edition-authoring/base-copies.mjs +125 -30
  45. package/edition-authoring/copy-checkout.mjs +7 -120
  46. package/edition-authoring/edition-migrations.mjs +41 -0
  47. package/edition-authoring/files.mjs +67 -0
  48. package/edition-authoring/lock.mjs +2 -2
  49. package/edition-authoring/module-closure.mjs +232 -0
  50. package/edition-authoring/module-edges.mjs +100 -0
  51. package/edition-authoring/module-resolution.mjs +66 -0
  52. package/edition-authoring/module-syntax.mjs +57 -0
  53. package/edition-authoring/package-target.mjs +92 -0
  54. package/edition-authoring/runtime-dependencies.mjs +74 -97
  55. package/edition-authoring/vendor/babel-parser/LICENSE +22 -0
  56. package/edition-authoring/vendor/babel-parser/README.md +21 -0
  57. package/edition-authoring/vendor/babel-parser/babel-helper-string-parser/index.mjs +292 -0
  58. package/edition-authoring/vendor/babel-parser/babel-helper-validator-identifier/identifier.mjs +66 -0
  59. package/edition-authoring/vendor/babel-parser/babel-helper-validator-identifier/index.mjs +13 -0
  60. package/edition-authoring/vendor/babel-parser/babel-helper-validator-identifier/keyword.mjs +31 -0
  61. package/edition-authoring/vendor/babel-parser/babel-parser/index.mjs +99 -0
  62. package/edition-authoring/vendor/babel-parser/babel-parser/options.mjs +81 -0
  63. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/bind-operator-errors.mjs +8 -0
  64. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/module-errors.mjs +15 -0
  65. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/parse-expression-errors.mjs +10 -0
  66. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/pipeline-operator-errors.mjs +29 -0
  67. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/standard-errors.mjs +224 -0
  68. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/strict-mode-errors.mjs +17 -0
  69. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error/to-node-description.mjs +31 -0
  70. package/edition-authoring/vendor/babel-parser/babel-parser/parse-error.mjs +114 -0
  71. package/edition-authoring/vendor/babel-parser/babel-parser/parser/base.mjs +34 -0
  72. package/edition-authoring/vendor/babel-parser/babel-parser/parser/comments.mjs +199 -0
  73. package/edition-authoring/vendor/babel-parser/babel-parser/parser/expression.mjs +1794 -0
  74. package/edition-authoring/vendor/babel-parser/babel-parser/parser/index.mjs +76 -0
  75. package/edition-authoring/vendor/babel-parser/babel-parser/parser/lval.mjs +439 -0
  76. package/edition-authoring/vendor/babel-parser/babel-parser/parser/node.mjs +111 -0
  77. package/edition-authoring/vendor/babel-parser/babel-parser/parser/statement.mjs +1962 -0
  78. package/edition-authoring/vendor/babel-parser/babel-parser/parser/util.mjs +244 -0
  79. package/edition-authoring/vendor/babel-parser/babel-parser/plugin-utils.mjs +116 -0
  80. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/estree.mjs +417 -0
  81. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/flow/index.mjs +2412 -0
  82. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/flow/scope.mjs +37 -0
  83. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/jsx/index.mjs +420 -0
  84. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/jsx/xhtml.mjs +261 -0
  85. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/placeholders.mjs +205 -0
  86. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/typescript/index.mjs +2889 -0
  87. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/typescript/scope.mjs +115 -0
  88. package/edition-authoring/vendor/babel-parser/babel-parser/plugins/v8intrinsic.mjs +26 -0
  89. package/edition-authoring/vendor/babel-parser/babel-parser/tokenizer/context.mjs +22 -0
  90. package/edition-authoring/vendor/babel-parser/babel-parser/tokenizer/index.mjs +1037 -0
  91. package/edition-authoring/vendor/babel-parser/babel-parser/tokenizer/state.mjs +178 -0
  92. package/edition-authoring/vendor/babel-parser/babel-parser/tokenizer/types.mjs +583 -0
  93. package/edition-authoring/vendor/babel-parser/babel-parser/types.mjs +1 -0
  94. package/edition-authoring/vendor/babel-parser/babel-parser/util/class-scope.mjs +82 -0
  95. package/edition-authoring/vendor/babel-parser/babel-parser/util/expression-scope.mjs +121 -0
  96. package/edition-authoring/vendor/babel-parser/babel-parser/util/identifier.mjs +23 -0
  97. package/edition-authoring/vendor/babel-parser/babel-parser/util/location.mjs +34 -0
  98. package/edition-authoring/vendor/babel-parser/babel-parser/util/production-parameter.mjs +40 -0
  99. package/edition-authoring/vendor/babel-parser/babel-parser/util/scope.mjs +173 -0
  100. package/edition-authoring/vendor/babel-parser/babel-parser/util/scopeflags.mjs +66 -0
  101. package/edition-authoring/vendor/babel-parser/babel-parser/util/whitespace.mjs +61 -0
  102. package/edition-authoring/vendor/yaml/LICENSE +13 -0
  103. package/edition-authoring/vendor/yaml/README.md +11 -0
  104. package/edition-authoring/vendor/yaml/compose/compose-collection.mjs +88 -0
  105. package/edition-authoring/vendor/yaml/compose/compose-doc.mjs +43 -0
  106. package/edition-authoring/vendor/yaml/compose/compose-node.mjs +110 -0
  107. package/edition-authoring/vendor/yaml/compose/compose-scalar.mjs +86 -0
  108. package/edition-authoring/vendor/yaml/compose/composer.mjs +218 -0
  109. package/edition-authoring/vendor/yaml/compose/resolve-block-map.mjs +115 -0
  110. package/edition-authoring/vendor/yaml/compose/resolve-block-scalar.mjs +198 -0
  111. package/edition-authoring/vendor/yaml/compose/resolve-block-seq.mjs +49 -0
  112. package/edition-authoring/vendor/yaml/compose/resolve-end.mjs +37 -0
  113. package/edition-authoring/vendor/yaml/compose/resolve-flow-collection.mjs +207 -0
  114. package/edition-authoring/vendor/yaml/compose/resolve-flow-scalar.mjs +228 -0
  115. package/edition-authoring/vendor/yaml/compose/resolve-props.mjs +148 -0
  116. package/edition-authoring/vendor/yaml/compose/util-contains-newline.mjs +34 -0
  117. package/edition-authoring/vendor/yaml/compose/util-empty-scalar-position.mjs +27 -0
  118. package/edition-authoring/vendor/yaml/compose/util-flow-indent-check.mjs +15 -0
  119. package/edition-authoring/vendor/yaml/compose/util-map-includes.mjs +13 -0
  120. package/edition-authoring/vendor/yaml/doc/Document.mjs +333 -0
  121. package/edition-authoring/vendor/yaml/doc/anchors.mjs +74 -0
  122. package/edition-authoring/vendor/yaml/doc/applyReviver.mjs +54 -0
  123. package/edition-authoring/vendor/yaml/doc/createNode.mjs +88 -0
  124. package/edition-authoring/vendor/yaml/doc/directives.mjs +176 -0
  125. package/edition-authoring/vendor/yaml/errors.mjs +57 -0
  126. package/edition-authoring/vendor/yaml/index.mjs +17 -0
  127. package/edition-authoring/vendor/yaml/log.mjs +11 -0
  128. package/edition-authoring/vendor/yaml/nodes/Alias.mjs +119 -0
  129. package/edition-authoring/vendor/yaml/nodes/Collection.mjs +147 -0
  130. package/edition-authoring/vendor/yaml/nodes/Node.mjs +38 -0
  131. package/edition-authoring/vendor/yaml/nodes/Pair.mjs +36 -0
  132. package/edition-authoring/vendor/yaml/nodes/Scalar.mjs +24 -0
  133. package/edition-authoring/vendor/yaml/nodes/YAMLMap.mjs +144 -0
  134. package/edition-authoring/vendor/yaml/nodes/YAMLSeq.mjs +113 -0
  135. package/edition-authoring/vendor/yaml/nodes/addPairToJSMap.mjs +62 -0
  136. package/edition-authoring/vendor/yaml/nodes/identity.mjs +36 -0
  137. package/edition-authoring/vendor/yaml/nodes/toJS.mjs +35 -0
  138. package/edition-authoring/vendor/yaml/parse/cst-scalar.mjs +214 -0
  139. package/edition-authoring/vendor/yaml/parse/cst-stringify.mjs +61 -0
  140. package/edition-authoring/vendor/yaml/parse/cst-visit.mjs +97 -0
  141. package/edition-authoring/vendor/yaml/parse/cst.mjs +98 -0
  142. package/edition-authoring/vendor/yaml/parse/lexer.mjs +722 -0
  143. package/edition-authoring/vendor/yaml/parse/line-counter.mjs +39 -0
  144. package/edition-authoring/vendor/yaml/parse/parser.mjs +975 -0
  145. package/edition-authoring/vendor/yaml/public-api.mjs +102 -0
  146. package/edition-authoring/vendor/yaml/schema/Schema.mjs +37 -0
  147. package/edition-authoring/vendor/yaml/schema/common/map.mjs +17 -0
  148. package/edition-authoring/vendor/yaml/schema/common/null.mjs +15 -0
  149. package/edition-authoring/vendor/yaml/schema/common/seq.mjs +17 -0
  150. package/edition-authoring/vendor/yaml/schema/common/string.mjs +14 -0
  151. package/edition-authoring/vendor/yaml/schema/core/bool.mjs +19 -0
  152. package/edition-authoring/vendor/yaml/schema/core/float.mjs +43 -0
  153. package/edition-authoring/vendor/yaml/schema/core/int.mjs +38 -0
  154. package/edition-authoring/vendor/yaml/schema/core/schema.mjs +23 -0
  155. package/edition-authoring/vendor/yaml/schema/json/schema.mjs +62 -0
  156. package/edition-authoring/vendor/yaml/schema/tags.mjs +96 -0
  157. package/edition-authoring/vendor/yaml/schema/yaml-1.1/binary.mjs +59 -0
  158. package/edition-authoring/vendor/yaml/schema/yaml-1.1/bool.mjs +26 -0
  159. package/edition-authoring/vendor/yaml/schema/yaml-1.1/float.mjs +46 -0
  160. package/edition-authoring/vendor/yaml/schema/yaml-1.1/int.mjs +71 -0
  161. package/edition-authoring/vendor/yaml/schema/yaml-1.1/merge.mjs +67 -0
  162. package/edition-authoring/vendor/yaml/schema/yaml-1.1/omap.mjs +74 -0
  163. package/edition-authoring/vendor/yaml/schema/yaml-1.1/pairs.mjs +78 -0
  164. package/edition-authoring/vendor/yaml/schema/yaml-1.1/schema.mjs +39 -0
  165. package/edition-authoring/vendor/yaml/schema/yaml-1.1/set.mjs +93 -0
  166. package/edition-authoring/vendor/yaml/schema/yaml-1.1/timestamp.mjs +101 -0
  167. package/edition-authoring/vendor/yaml/stringify/foldFlowLines.mjs +146 -0
  168. package/edition-authoring/vendor/yaml/stringify/stringify.mjs +130 -0
  169. package/edition-authoring/vendor/yaml/stringify/stringifyCollection.mjs +155 -0
  170. package/edition-authoring/vendor/yaml/stringify/stringifyComment.mjs +20 -0
  171. package/edition-authoring/vendor/yaml/stringify/stringifyDocument.mjs +85 -0
  172. package/edition-authoring/vendor/yaml/stringify/stringifyNumber.mjs +25 -0
  173. package/edition-authoring/vendor/yaml/stringify/stringifyPair.mjs +150 -0
  174. package/edition-authoring/vendor/yaml/stringify/stringifyString.mjs +338 -0
  175. package/edition-authoring/vendor/yaml/util.mjs +11 -0
  176. package/edition-authoring/vendor/yaml/visit.mjs +233 -0
  177. package/edition-authoring/workflow-copies.mjs +125 -0
  178. package/edition-authoring/workflow-scripts.mjs +112 -0
  179. package/foundation/runtime/contract-docs.mjs +754 -0
  180. package/foundation/runtime/run-data.d.mts +1 -0
  181. package/foundation/runtime/run-data.mjs +2 -0
  182. package/global/CHANGELOG.md +55 -3
  183. package/global/README.md +21 -24
  184. package/global/cli/command.mjs +8 -2
  185. package/global/cli/install.mjs +4 -5
  186. package/global/cli/path-link.mjs +3 -2
  187. package/global/cli/repo-command.mjs +3 -7
  188. package/global/launch/dev.mjs +12 -2
  189. package/global/launch/facts.mjs +2 -2
  190. package/global/launch/render.mjs +16 -9
  191. package/global/launch/state.mjs +4 -4
  192. package/global/main.mjs +12 -7
  193. package/install.sh +17 -6
  194. package/modules/container/README.md +6 -1
  195. package/modules/container/adapters/d1-limits.mjs +286 -0
  196. package/modules/container/adapters/d1-sqlite.mjs +95 -0
  197. package/modules/container/adapters/d1-workerd-preload.mjs +19 -0
  198. package/modules/container/adapters/d1-workerd-setup.mjs +26 -0
  199. package/modules/container/adapters/d1-workerd.mjs +5 -0
  200. package/modules/container/adapters/sqlite-worker.mjs +5 -3
  201. package/modules/container/build.mjs +1 -0
  202. package/modules/container/image-variables.mjs +8 -3
  203. package/modules/container/transfer.mjs +14 -4
  204. package/modules/container/worker-engine.mjs +3 -3
  205. package/modules/demo/declaration.mjs +1 -4
  206. package/modules/demo/vite.mjs +1 -1
  207. package/modules/demo-host/build.mjs +1 -0
  208. package/modules/demo-host/native/prepare.mjs +2 -1
  209. package/modules/demo-host/native/sql.mjs +7 -2
  210. package/modules/deploy-kit/README.md +23 -3
  211. package/modules/deploy-kit/d1-import-diagnostics.mjs +56 -0
  212. package/modules/deploy-kit/d1-import.mjs +17 -5
  213. package/modules/deploy-kit/diagnostics.mjs +29 -3
  214. package/modules/deploy-kit/owner-cli.mjs +20 -7
  215. package/modules/deploy-kit/provider-transport.mjs +19 -4
  216. package/modules/deploy-kit/provider.mjs +57 -22
  217. package/modules/deploy-kit/readiness-window.mjs +1 -1
  218. package/modules/deploy-kit/site.mjs +8 -3
  219. package/modules/deploy-kit/templates.mjs +3 -3
  220. package/modules/deploy-kit/worker.mjs +4 -4
  221. package/modules/import-kit/src/d1/README.md +23 -4
  222. package/modules/import-kit/src/d1/atomic-prefix.ts +2 -2
  223. package/modules/import-kit/src/d1/budget.ts +15 -7
  224. package/modules/import-kit/src/d1/column-layout.ts +5 -0
  225. package/modules/import-kit/src/d1/creation.ts +15 -8
  226. package/modules/import-kit/src/d1/database.ts +3 -3
  227. package/modules/import-kit/src/d1/erasure-pages.ts +2 -1
  228. package/modules/import-kit/src/d1/erasure.ts +2 -2
  229. package/modules/import-kit/src/d1/jobs.ts +10 -6
  230. package/modules/import-kit/src/d1/plans.ts +14 -8
  231. package/modules/import-kit/src/d1/retirement.ts +2 -2
  232. package/modules/import-kit/src/d1/sets.ts +1 -3
  233. package/modules/import-kit/src/d1/staged-creation.ts +3 -3
  234. package/modules/import-kit/src/door/limits.ts +1 -1
  235. package/modules/import-kit/src/door/refusals.ts +1 -1
  236. package/modules/portability/README.md +112 -4
  237. package/modules/portability/backfills.mjs +9 -8
  238. package/modules/portability/bridge.mjs +12 -5
  239. package/modules/portability/catalogue.mjs +12 -5
  240. package/modules/portability/files.mjs +4 -3
  241. package/modules/portability/http.mjs +3 -3
  242. package/modules/portability/import.mjs +18 -9
  243. package/modules/portability/index.d.mts +4 -3
  244. package/modules/portability/index.mjs +1 -1
  245. package/modules/portability/ledgers.mjs +3 -2
  246. package/modules/portability/legacy-safety.mjs +11 -2
  247. package/modules/portability/migration-history.mjs +2 -2
  248. package/modules/portability/progress.mjs +1 -0
  249. package/modules/portability/restore-empty.mjs +12 -0
  250. package/modules/release/github-verify.mjs +11 -2
  251. package/onboarding/adapter.mjs +35 -6
  252. package/onboarding/app-fetch.mjs +6 -4
  253. package/onboarding/development-runtime.mjs +19 -0
  254. package/onboarding/local/operation.mjs +45 -27
  255. package/onboarding/loopback-fetch.mjs +16 -0
  256. package/onboarding/operator-installer.mjs +4 -6
  257. package/onboarding/process-diagnostics.mjs +6 -2
  258. package/onboarding/production-runtime.mjs +4 -2
  259. package/onboarding/readiness.mjs +1 -0
  260. package/package.json +1 -1
  261. package/scripts/publish-check/README.md +6 -0
  262. package/scripts/publish-check/history_scan.py +5 -3
  263. package/scripts/publish-check/hygiene_config.py +2 -1
  264. package/scripts/publish-check/public_hygiene.py +1 -1
  265. package/scripts/publish-check/report.py +9 -3
  266. package/scripts/publish-check/third-party-notices.json +13 -0
  267. package/scripts/publish-check/third_party_notices.py +38 -0
  268. package/scripts/publish-check/tree_scan.py +6 -0
  269. package/scripts/publish-check.mjs +1 -1
@@ -38,6 +38,63 @@ export function safe(name) {
38
38
  }
39
39
  return name;
40
40
  }
41
+ // One physical spelling/type check for refresh writes and dependencies. Cache
42
+ // directory entries only for one read-only planning pass; removals take priority.
43
+ export function freedEntries(root) {
44
+ const removed = new Set();
45
+ const identity = (name, stat) => stat.nlink > 1 ? name : `${stat.dev}:${stat.ino}`;
46
+ return {
47
+ add: (name, stat) => removed.add(identity(name, stat)),
48
+ has(relative, stat, parent) {
49
+ if (stat.isFile()) return removed.has(identity(relative, stat));
50
+ if (!parent || !stat.isDirectory() || !removed.size) return false;
51
+ let found = false;
52
+ const empty = directory => fs.readdirSync(directory).every(name => {
53
+ const absolute = path.join(directory, name), child = fs.lstatSync(absolute);
54
+ if (child.isDirectory()) return empty(absolute);
55
+ const freed = child.isFile() && removed.has(identity(path.relative(root, absolute), child));
56
+ found ||= freed;
57
+ return freed;
58
+ });
59
+ return empty(path.join(root, relative)) && found;
60
+ },
61
+ };
62
+ }
63
+ export function physicalEntry(root, name, {cache = new Map(), freed = () => false} = {}) {
64
+ let parent = root, parentStat = fs.lstatSync(root);
65
+ const parts = safe(name).split('/');
66
+ for (const [i, part] of parts.entries()) {
67
+ const target = path.join(parent, part), relative = parts.slice(0, i + 1).join('/');
68
+ let stat;
69
+ try { stat = fs.lstatSync(target); }
70
+ catch (error) { if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error; }
71
+ if (!stat || freed(relative, stat, i < parts.length - 1)) return {absent: true, parent, parentStat};
72
+ if (!cache.has(parent)) cache.set(parent, fs.readdirSync(parent));
73
+ const entries = cache.get(parent);
74
+ if (!entries.includes(part)) {
75
+ const physical = entries.find(entry => {
76
+ const other = fs.lstatSync(path.join(parent, entry));
77
+ return other.dev === stat.dev && other.ino === stat.ino;
78
+ });
79
+ return {kind: 'alias', path: relative, physical: path.relative(root, path.join(parent, physical ?? part))};
80
+ }
81
+ if (stat.isSymbolicLink()) return {kind: 'symlink', path: relative};
82
+ if (i < parts.length - 1 && !stat.isDirectory()) return {kind: 'non-directory parent', path: relative};
83
+ if (i === parts.length - 1) return stat.isFile() ? {stat, target, parent, parentStat} : {kind: 'non-regular', path: relative};
84
+ parent = target; parentStat = stat;
85
+ }
86
+ }
87
+ export function requirePhysical(root, name, options) {
88
+ const entry = physicalEntry(root, name, options);
89
+ if (entry.kind) {
90
+ const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
91
+ const indexed = raw(root, '--literal-pathspecs', 'ls-files', '--', entry.path).length > 0;
92
+ const command = `backup=$(mktemp -d) && mv -- ${quote(entry.physical ?? entry.path)} "$backup/"${indexed ? ' && git restore -- ' + quote(entry.path) : ''}`;
93
+ const reason = entry.kind === 'symlink' ? 'Symlink in destination path' : entry.kind === 'non-regular' ? 'destination is not a regular file' : entry.kind;
94
+ throw Error(`Cannot refresh ${name}: ${reason} at ${entry.physical ?? entry.path}. Run ${command}, then repeat refresh-base; no files were refreshed.`);
95
+ }
96
+ return entry;
97
+ }
41
98
  export function noLinks(root, relative) {
42
99
  let current = root;
43
100
  for (const part of relative.split('/')) {
@@ -62,6 +119,16 @@ export function tracked(root, allowMissing = false) {
62
119
  return result;
63
120
  }
64
121
  export const digest = files => hash(json(files));
122
+ // The complete tool in `dir`, as sorted relative paths: its non-test modules and
123
+ // every vendored parser file with its licence. Copies and the lock identity use it.
124
+ export function toolFiles(dir) {
125
+ const modules = fs.readdirSync(dir).filter(p => p.endsWith('.mjs') && !p.endsWith('.test.mjs'));
126
+ const vendored = fs.readdirSync(path.join(dir, 'vendor'), {recursive: true, withFileTypes: true}).filter(entry => {
127
+ if (!entry.isFile() && !entry.isDirectory()) throw Error(`Unsupported vendored tool entry: ${entry.name}`);
128
+ return entry.isFile();
129
+ }).map(entry => path.relative(dir, path.join(entry.parentPath, entry.name)).split(path.sep).join('/'));
130
+ return [...modules, ...vendored].sort();
131
+ }
65
132
  // Base's test, fixture and browser-check sources, which portable copies leave out.
66
133
  // Composition pins its tooling alone, so composition/git-source.mjs keeps its own copy.
67
134
  export function testSource(path) {
@@ -3,11 +3,11 @@ import path from 'node:path';
3
3
  import {fileURLToPath} from 'node:url';
4
4
  import {manifest, VERSION} from './manifest.mjs';
5
5
  import {snapshot, merge} from './sources.mjs';
6
- import {hash, json, tracked} from './files.mjs';
6
+ import {hash, json, tracked, toolFiles} from './files.mjs';
7
7
 
8
8
  function toolsIdentity() {
9
9
  const dir = path.dirname(fileURLToPath(import.meta.url));
10
- const names = fs.readdirSync(dir).filter(p => p.endsWith('.mjs') && !p.endsWith('.test.mjs')).sort();
10
+ const names = toolFiles(dir);
11
11
  const bytes = names.map(p => p + '\0' + fs.readFileSync(path.join(dir, p), 'utf8')).join('\0');
12
12
  return {id: 'runeditrun/edition-authoring', version: VERSION, sha256: hash(bytes)};
13
13
  }
@@ -0,0 +1,232 @@
1
+ // All recorded code uses the same source graph and seed ownership boundary.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {raw, safe, requirePhysical, testSource, freedEntries} from './files.mjs';
5
+ import {dependencies, resolve, external, bindings, lexicalExports} from './runtime-dependencies.mjs';
6
+ const code = name => /\.(?:[cm]?[jt]s|[jt]sx)$/.test(name) && !testSource(name);
7
+ const inside = (name, prefix) => prefix === '.' ? !name.startsWith('../') && !path.posix.isAbsolute(name) : name === prefix || name.startsWith(prefix + '/');
8
+ const mapped = (source, copy) => copy.path + source.slice(copy.originPath.length);
9
+ const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
10
+
11
+ export function completeModuleCopies(root, plans, {tree, read, revision, base, deliveries = [], ownerSources = new Map()}) {
12
+ const index = new Set(raw(root, 'ls-files', '-z').toString('utf8').split('\0').filter(Boolean));
13
+ const required = new Set();
14
+ const cache = new Map(), planned = new Map(), recorded = new Map(), queue = [], withheld = [];
15
+ const disk = {has: name => {
16
+ try { return fs.lstatSync(path.join(root, name)).isFile(); }
17
+ catch (error) { if (['ENOENT', 'ENOTDIR'].includes(error.code)) return false; throw error; }
18
+ }, read: name => local(name)};
19
+ const blob = entry => read.blobs([entry.object]).get(entry.object).toString('utf8');
20
+ const local = target => fs.readFileSync(path.join(root, target), 'utf8');
21
+ tree.read = name => blob(tree.get(name));
22
+ const refuse = (target, reason, recovery) => { throw Error(`Cannot refresh module ${target}: ${reason}. Run ${recovery}, then repeat refresh-base; no files were refreshed.`); };
23
+ const removedObjects = freedEntries(root);
24
+ for (const plan of plans) for (const target of plan.removed) {
25
+ const stat = requirePhysical(root, target, {cache}).stat;
26
+ if (stat) removedObjects.add(target, stat);
27
+ }
28
+ const inspect = target => requirePhysical(root, safe(target), {cache, freed: removedObjects.has});
29
+ function enqueue(plan, source, entry, adapted = false) {
30
+ const target = mapped(source, plan.copy);
31
+ if (!adapted) planned.set(target, {plan, source, entry});
32
+ if (code(source)) queue.push({plan, source, target, entry, adapted});
33
+ }
34
+ for (const plan of plans) {
35
+ for (const target of Object.keys(plan.copy.files)) recorded.set(target, plan);
36
+ for (const [source, entry] of plan.sources) enqueue(plan, source, entry);
37
+ for (const target of Object.keys(plan.copy.adapted ?? {})) enqueue(plan, plan.copy.originPath + target.slice(plan.copy.path.length), null, true);
38
+ }
39
+ const directoryAdditions = new Set([...planned].filter(([target, {plan}]) => !Object.hasOwn(plan.copy.files, target) && !tree.has(plan.copy.originPath)).map(([target]) => target));
40
+ function witness(target, source) {
41
+ return plans.some(({copy}) => {
42
+ const file = Object.hasOwn(copy.files, copy.path) || tree.has(copy.originPath);
43
+ if (file && path.posix.basename(copy.path) !== path.posix.basename(copy.originPath)) return false;
44
+ const to = file ? path.posix.dirname(copy.path) : copy.path;
45
+ const from = file ? path.posix.dirname(copy.originPath) : copy.originPath;
46
+ return inside(target, to) && path.posix.join(from, path.posix.relative(to, target)) === source;
47
+ });
48
+ }
49
+ function include(source, target) {
50
+ required.add(target);
51
+ if (withheld.some(item => item.path === target)) refuse(target, 'a required module has an unplaceable dependency', '${EDITOR:-vi} base-copies.json');
52
+ const physical = inspect(target), owner = recorded.get(target);
53
+ if (owner?.removed.includes(target)) {
54
+ const origin = owner.copy.originPath + target.slice(owner.copy.path.length);
55
+ refuse(target, 'recorded dependency was removed but is still imported', index.has(target) ? `git restore -- ${quote(target)}` : `git -C ${quote(base)} show ${quote(owner.copy.revision + ':' + origin)} > ${quote(target)}`);
56
+ }
57
+ if (planned.has(target)) return;
58
+ if (owner) return;
59
+ if (index.has(target)) {
60
+ if (!physical.stat) refuse(target, 'tracked edition source is missing', `git restore -- ${quote(target)}`);
61
+ ownerSources.set(target, source);
62
+ return; // Tracked, unrecorded source remains edition-owned, even at equal bytes.
63
+ }
64
+ if (physical.stat && !index.has(target)) refuse(target, 'existing file has no Base copy record or Git index entry', `git add -f -- ${quote(target)}`);
65
+ let plan = plans.find(plan => inside(target, plan.copy.path));
66
+ if (plan && mapped(source, plan.copy) !== target) refuse(target, 'conflicting directory mapping', '${EDITOR:-vi} base-copies.json');
67
+ if (!plan) {
68
+ if (plans.some(plan => inside(plan.copy.path, target))) refuse(target, 'overlapping copy mapping', '${EDITOR:-vi} base-copies.json');
69
+ plan = {copy: {path: target, originPath: source, revision, files: {}, modes: {}}, sources: [], removed: []};
70
+ plans.push(plan);
71
+ }
72
+ const entry = tree.get(source);
73
+ plan.sources.push([source, entry]);
74
+ enqueue(plan, source, entry);
75
+ }
76
+ for (const {source, origin, importers} of deliveries) {
77
+ const targets = importers.map(importer => path.posix.join(path.posix.dirname(importer), path.posix.relative(path.posix.dirname(origin), source)));
78
+ if (!tree.has(source)) refuse(source, 'migration delivery has no Base source', '${EDITOR:-vi} base-copies.json');
79
+ for (const target of new Set(targets)) {
80
+ if (!witness(target, source)) refuse(target, 'migration delivery has no witnessed destination', '${EDITOR:-vi} base-copies.json');
81
+ include(source, target);
82
+ }
83
+ }
84
+ // Template files can refer to another recorded copy whose Base origin is
85
+ // elsewhere (for example foundation/template -> foundation/runtime). Existing
86
+ // records and plans satisfy that local edge before looking for a new source.
87
+ const view = {
88
+ has: name => planned.has(name) || recorded.has(name) || index.has(name) && disk.has(name),
89
+ read: name => planned.has(name) ? blob(planned.get(name).entry) : local(name),
90
+ };
91
+ function requests(bytes, source, target) {
92
+ return dependencies(bytes, source).filter(request => {
93
+ const origin = {}, localScope = {};
94
+ resolve(tree, source, request.specifier, {...request, package: origin});
95
+ resolve(disk, target, request.specifier, {...request, package: localScope});
96
+ return request.specifier.startsWith('.') || origin.managed || localScope.managed;
97
+ });
98
+ }
99
+ function edge(source, target, request) {
100
+ const {specifier} = request;
101
+ const originScope = {}, targetScope = {}, manifests = new Set();
102
+ const dependency = resolve(tree, source, specifier, {...request, manifests, package: originScope});
103
+ const destination = resolve(view, target, specifier, {...request, package: targetScope});
104
+ if (!specifier.startsWith('.')) {
105
+ if (originScope.external && targetScope.external && originScope.value === targetScope.value) return {...request, external: true};
106
+ if (!targetScope.managed || originScope.external || targetScope.external) return {...request, reason: 'runtime package scope differs from its Base source'};
107
+ if (destination && !dependency) return {...request, external: true};
108
+ const expected = originScope.target && path.posix.join(path.posix.dirname(target), path.posix.relative(path.posix.dirname(source), originScope.target));
109
+ if (expected !== targetScope.target || expected && ['.js', '.ts', '.jsx', '.tsx'].includes(path.posix.extname(expected)) && originScope.type !== targetScope.type) {
110
+ return {...request, reason: 'runtime package target or format differs from its Base namespace'};
111
+ }
112
+ }
113
+ if (destination && destination !== external) {
114
+ const owner = recorded.get(destination);
115
+ const source = planned.get(destination)?.source ?? (owner && owner.copy.originPath + destination.slice(owner.copy.path.length)) ?? dependency;
116
+ return {...request, dependency: source, destination, satisfied: true};
117
+ }
118
+ return {...request, manifests, dependency, destination: dependency && path.posix.join(path.posix.dirname(target), path.posix.relative(path.posix.dirname(source), dependency))};
119
+ }
120
+ const key = (target, request) => JSON.stringify([target, request.kind, request.types, request.specifier]);
121
+ const bootstrap = source => /^(?:edition-authoring|(?:default-seed|export)\/scripts\/base-cli\/edition-authoring)\//.test(source);
122
+ // Snapshot the original unresolved set once, before closure can add a file.
123
+ // Only toolkit bootstraps and recorded removals may change that baseline.
124
+ const baseline = new Set();
125
+ for (const {plan, source, target} of queue) {
126
+ if (!Object.hasOwn(plan.copy.files, target) || !disk.has(target) || bootstrap(source)) continue;
127
+ for (const request of requests(local(target), source, target)) {
128
+ const candidate = edge(source, target, request);
129
+ if (!resolve(disk, target, request.specifier, request) && !recorded.has(candidate.destination)) baseline.add(key(target, request));
130
+ }
131
+ }
132
+ // Do not let an optional directory addition incidentally fill an old edge.
133
+ for (const {plan, source, target} of queue) {
134
+ if (!Object.hasOwn(plan.copy.files, target) || !disk.has(target)) continue;
135
+ for (const request of requests(local(target), source, target)) if (baseline.has(key(target, request))) {
136
+ const destination = resolve(view, target, request.specifier, request);
137
+ if (!directoryAdditions.has(destination)) continue;
138
+ const addition = planned.get(destination);
139
+ addition.plan.sources = addition.plan.sources.filter(([name]) => name !== addition.source);
140
+ planned.delete(destination);
141
+ withheld.push({path: destination, originPath: addition.source, dependency: request.specifier});
142
+ }
143
+ }
144
+ const incoming = new Set();
145
+ for (const item of queue) for (const request of requests(item.adapted ? local(item.target) : blob(item.entry), item.source, item.target)) {
146
+ if (baseline.has(key(item.target, request))) continue;
147
+ const {destination} = edge(item.source, item.target, request);
148
+ if (destination) incoming.add(destination);
149
+ }
150
+ function exportsAt(target, types = false, seen = new Set()) {
151
+ if (seen.has(target)) return new Set();
152
+ seen.add(target); inspect(target);
153
+ if (!disk.has(target)) return null;
154
+ if (!types && /\.d\.[cm]?ts$/.test(target)) return new Set();
155
+ if (target.endsWith('.json')) return new Set(['default']);
156
+ const result = lexicalExports(local(target), specifier => {
157
+ const next = resolve(disk, target, specifier, {types});
158
+ return next ? exportsAt(next, types, seen) : null;
159
+ }, types);
160
+ if (result === null) return null;
161
+ const declaration = target.replace(/\.mjs$/, '.d.mts').replace(/\.js$/, '.d.ts');
162
+ if (types && declaration !== target && disk.has(declaration)) {
163
+ const declared = exportsAt(declaration, true, seen);
164
+ if (declared === null) return null;
165
+ for (const name of declared) result.add(name);
166
+ }
167
+ return result;
168
+ }
169
+ const seen = new Set();
170
+ for (let i = 0; i < queue.length; i++) {
171
+ const item = queue[i], {plan, source, target, entry, adapted} = item;
172
+ if (seen.has(target) || !adapted && !plan.sources.some(([name]) => name === source)) continue;
173
+ seen.add(target);
174
+ const bytes = adapted ? local(target) : blob(entry);
175
+ const before = Object.hasOwn(plan.copy.files, target) && disk.has(target) ? local(target) : '';
176
+ const imports = bindings(bytes), oldBindings = bindings(before);
177
+ const typeImports = bindings(bytes, true), oldTypes = bindings(before, true);
178
+ const edges = requests(bytes, source, target).map(request => edge(source, target, request));
179
+ for (const {manifests = []} of [...edges]) for (const dependency of manifests) {
180
+ edges.push({dependency, destination: path.posix.join(path.posix.dirname(target), path.posix.relative(path.posix.dirname(source), dependency))});
181
+ }
182
+ const declaration = source.replace(/\.mjs$/, '.d.mts').replace(/\.cjs$/, '.d.cts');
183
+ if (declaration !== source && tree.has(declaration)) edges.push({dependency: declaration, destination: target.replace(/\.mjs$/, '.d.mts').replace(/\.cjs$/, '.d.cts')});
184
+ const novel = directoryAdditions.has(target) && !required.has(target) && !incoming.has(target);
185
+ const preserved = request => baseline.has(key(target, request));
186
+ let hold;
187
+ for (const edge of edges) {
188
+ const {specifier, dependency, destination, satisfied} = edge;
189
+ if (edge.external || preserved(edge)) continue;
190
+ if (satisfied) continue;
191
+ if (!dependency) refuse(target, edge.reason ?? `no Base source for ${specifier}`, `\${EDITOR:-vi} ${quote(target)}`);
192
+ if (!witness(destination, dependency)) {
193
+ if (novel) { hold = {path: target, originPath: source, dependency}; break; }
194
+ refuse(target, `no copy mapping witnesses ${destination} from ${dependency}`, '${EDITOR:-vi} base-copies.json');
195
+ }
196
+ }
197
+ if (hold) {
198
+ plan.sources = plan.sources.filter(([name]) => name !== source);
199
+ planned.delete(target); withheld.push(hold); continue;
200
+ }
201
+ for (const edge of edges) {
202
+ const {specifier, dependency, destination} = edge;
203
+ if (edge.external || preserved(edge)) continue;
204
+ include(dependency, destination);
205
+ const owner = recorded.get(destination);
206
+ if (!adapted && !planned.has(destination) && (index.has(destination) || owner?.copy.adapted?.[destination])) {
207
+ for (const [types, current, previous] of [[false, imports, oldBindings], [true, typeImports, oldTypes]]) {
208
+ const exported = exportsAt(destination, types);
209
+ for (const name of current.get(specifier) ?? []) if (exported && !exported.has(name) && !previous.get(specifier)?.has(name)) {
210
+ refuse(target, `${destination} does not export ${name}; merge Base ${dependency} at ${revision} into that seed-owned file`, `git -C ${quote(base)} show ${quote(revision + ':' + dependency)} > ${quote(destination + '.base')}`);
211
+ }
212
+ }
213
+ }
214
+ }
215
+ }
216
+ const expected = new Set(), unresolved = new Set();
217
+ const removed = new Set(plans.flatMap(plan => plan.removed));
218
+ const final = {has: name => planned.has(name) || !removed.has(name) && disk.has(name), read: view.read};
219
+ for (const {plan, source, target, entry, adapted} of queue) {
220
+ if (!adapted && !plan.sources.some(([name]) => name === source)) continue;
221
+ for (const request of requests(adapted ? local(target) : blob(entry), source, target)) {
222
+ const id = key(target, request);
223
+ if (!baseline.has(id)) continue;
224
+ expected.add(id);
225
+ if (!resolve(final, target, request.specifier, request)) unresolved.add(id);
226
+ }
227
+ }
228
+ if (expected.size !== unresolved.size || [...expected].some(id => !unresolved.has(id))) {
229
+ refuse('baseline imports', 'a planned file would resolve an edition-owned unresolved edge', '${EDITOR:-vi} base-copies.json');
230
+ }
231
+ return withheld;
232
+ }
@@ -0,0 +1,100 @@
1
+ import {canonical} from './module-resolution.mjs';
2
+ import {parse} from './vendor/babel-parser/babel-parser/index.mjs';
3
+
4
+ const literal = node => node?.type === 'StringLiteral' ? node.value :
5
+ node?.type === 'TemplateLiteral' && !node.expressions.length ? node.quasis[0].value.cooked : undefined;
6
+ const unwrap = node => ['TSAsExpression', 'TSTypeAssertion', 'TSNonNullExpression', 'TSInstantiationExpression', 'ParenthesizedExpression'].includes(node?.type) ? unwrap(node.expression) : node;
7
+ const property = node => node?.computed ? literal(node.property) : node?.property?.name;
8
+ const member = node => ['MemberExpression', 'OptionalMemberExpression'].includes(node?.type);
9
+ const call = node => ['CallExpression', 'OptionalCallExpression', 'NewExpression'].includes(node?.type);
10
+ function* nodes(root) {
11
+ const pending = [root];
12
+ while (pending.length) {
13
+ const node = pending.pop();
14
+ if (!node || typeof node.type !== 'string') continue;
15
+ yield node;
16
+ for (const value of Object.values(node)) {
17
+ if (Array.isArray(value)) pending.push(...value);
18
+ else if (value && typeof value === 'object' && typeof value.type === 'string') pending.push(value);
19
+ }
20
+ }
21
+ }
22
+
23
+ const parsed = new Map();
24
+
25
+ // Parsing, including erased TS edges and calls nested in templates/JSX, precedes
26
+ // resolution. Every resulting edge uses the same virtual Node resolver.
27
+ export function dependencies(source, filename = 'module.mjs') {
28
+ let versions = parsed.get(filename);
29
+ if (versions?.has(source)) return versions.get(source);
30
+ const plugins = ['decorators-legacy', 'deprecatedImportAssert'];
31
+ if (/\.[cm]?tsx?$/.test(filename)) plugins.push(['typescript', {dts: /\.d\.[cm]?ts$/.test(filename)}]);
32
+ if (/\.[jt]sx$/.test(filename)) plugins.push('jsx');
33
+ const ast = parse(source, {sourceFilename: filename, sourceType: 'unambiguous', plugins,
34
+ createImportExpressions: true, allowReturnOutsideFunction: true, allowUndeclaredExports: true});
35
+ const all = [...nodes(ast)], result = [], loaders = new Set(['require']), factories = new Set(), moduleNamespaces = new Set();
36
+ const identifier = (node, names) => node?.type === 'Identifier' && names.has(node.name);
37
+ const moduleRequest = node => call(node) && identifier(unwrap(node.callee), loaders) && ['module', 'node:module'].includes(literal(node.arguments[0]));
38
+ for (const node of all) if (node.type === 'ImportDeclaration' && ['module', 'node:module'].includes(node.source.value)) {
39
+ for (const item of node.specifiers) {
40
+ if (item.type === 'ImportSpecifier' && (item.imported.name ?? item.imported.value) === 'createRequire') factories.add(item.local.name);
41
+ if (['ImportNamespaceSpecifier', 'ImportDefaultSpecifier'].includes(item.type)) moduleNamespaces.add(item.local.name);
42
+ }
43
+ }
44
+ const requireFunction = node => {
45
+ node = unwrap(node);
46
+ return identifier(node, loaders) || call(node) && (factory(node.callee) || member(node.callee) && property(node.callee) === 'bind' && requireFunction(node.callee.object)) || member(node) && property(node) === 'require' && node.object?.type === 'Identifier' && node.object.name === 'module';
47
+ };
48
+ const factory = node => {
49
+ node = unwrap(node);
50
+ return identifier(node, factories) || call(node) && member(node.callee) && property(node.callee) === 'bind' && factory(node.callee.object) || member(node) && property(node) === 'createRequire' && (identifier(node.object, moduleNamespaces) || moduleRequest(node.object));
51
+ };
52
+ // Static aliases reach a fixed point, independently of declaration order.
53
+ let changed;
54
+ do {
55
+ changed = false;
56
+ const add = (names, name) => { if (!names.has(name)) { names.add(name); changed = true; } };
57
+ for (const node of all) if (node.type === 'VariableDeclarator') {
58
+ const init = unwrap(node.init);
59
+ if (node.id.type === 'Identifier') {
60
+ if (requireFunction(init) || call(init) && factory(init.callee)) add(loaders, node.id.name);
61
+ if (factory(init)) add(factories, node.id.name);
62
+ if (moduleRequest(init)) add(moduleNamespaces, node.id.name);
63
+ } else if (node.id.type === 'ObjectPattern' && moduleRequest(init)) {
64
+ for (const item of node.id.properties) if (item.type === 'ObjectProperty' && (item.key.name ?? literal(item.key)) === 'createRequire' && item.value.type === 'Identifier') add(factories, item.value.name);
65
+ }
66
+ }
67
+ } while (changed);
68
+ const add = (node, kind, types = false) => {
69
+ const specifier = literal(unwrap(node));
70
+ if (specifier) result.push({specifier: canonical(specifier, kind), kind, types});
71
+ };
72
+ for (const node of all) {
73
+ if (node.type === 'ImportDeclaration') {
74
+ const erased = node.importKind === 'type' || node.specifiers.length > 0 && node.specifiers.every(item => item.importKind === 'type');
75
+ add(node.source, 'import', erased);
76
+ } else if (['ExportNamedDeclaration', 'ExportAllDeclaration'].includes(node.type) && node.source) {
77
+ const erased = node.exportKind === 'type' || node.specifiers?.length > 0 && node.specifiers.every(item => item.exportKind === 'type');
78
+ add(node.source, 'import', erased);
79
+ } else if (node.type === 'TSImportType') add(node.argument, 'import', true);
80
+ else if (node.type === 'TSImportEqualsDeclaration' && node.moduleReference.type === 'TSExternalModuleReference') add(node.moduleReference.expression, 'require', node.importKind === 'type');
81
+ else if (node.type === 'ImportExpression') add(node.source, 'import');
82
+ else if (call(node)) {
83
+ let callee = unwrap(node.callee), argument = node.arguments[0];
84
+ if (member(callee) && property(callee) === 'bind' && requireFunction(callee.object)) { add(node.arguments[1], 'require'); continue; }
85
+ if (member(callee) && callee.object?.type === 'Identifier' && callee.object.name === 'Reflect' && ['apply', 'construct'].includes(property(callee)) && requireFunction(node.arguments[0])) {
86
+ add(node.arguments[property(callee) === 'apply' ? 2 : 1]?.elements?.[0], 'require'); continue;
87
+ }
88
+ if (callee?.type === 'Import') { add(argument, 'import'); continue; }
89
+ if (member(callee) && ['call', 'apply'].includes(property(callee))) {
90
+ argument = property(callee) === 'apply' ? node.arguments[1]?.elements?.[0] : node.arguments[1];
91
+ callee = unwrap(callee.object);
92
+ }
93
+ if (member(callee) && property(callee) === 'resolve') callee = unwrap(callee.object);
94
+ if (requireFunction(callee)) add(argument, 'require');
95
+ }
96
+ }
97
+ if (!versions) parsed.set(filename, versions = new Map());
98
+ versions.set(source, result);
99
+ return result;
100
+ }
@@ -0,0 +1,66 @@
1
+ import path from 'node:path';
2
+ import {packageTarget} from './package-target.mjs';
3
+ export const external = Symbol('external package target');
4
+ export function canonical(specifier, kind = 'import') {
5
+ return kind !== 'require' && specifier?.startsWith('.') ? specifier.split(/[?#]/)[0] : specifier;
6
+ }
7
+
8
+ const declaration = name => /\.d\.[cm]?ts$/.test(name);
9
+ const sourceExtensions = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.json'];
10
+
11
+ // Every import kind uses this resolver. Runtime JS follows Node's file/require
12
+ // rules; source TS also recognizes filenames produced by its compiler. An
13
+ // erased type edge is the only route that can resolve a declaration file.
14
+ // Package-name imports belong to the edition's package manager, not this graph.
15
+ export function resolve(tree, source, specifier, {types = false, kind = 'import', manifests = new Set(), package: packageState = {}} = {}) {
16
+ types ||= declaration(source);
17
+ const packaged = !specifier.startsWith('.');
18
+ const packagePath = packaged && packageTarget(tree, source, specifier, {kind, types, package: packageState});
19
+ if (packageState.external) return external;
20
+ if (packaged && !packagePath) return;
21
+ const relative = canonical(specifier, kind);
22
+ if (kind !== 'require' && /%2f|%5c/i.test(relative)) throw Error(`Invalid encoded separator in module specifier ${specifier}`);
23
+ const name = packaged ? packagePath : path.posix.normalize(path.posix.join(path.posix.dirname(source), kind === 'require' ? relative : decodeURIComponent(relative)));
24
+ const sourceModule = /\.(?:[cm]?ts|[jt]sx)$/.test(source);
25
+ const file = candidate => (types || !declaration(candidate)) && tree.has(candidate) ? candidate : undefined;
26
+ if (!types && declaration(name)) return;
27
+ const direct = file(name);
28
+ if (direct) return direct;
29
+ const extension = path.posix.extname(name);
30
+ if (sourceModule || types) {
31
+ const replacements = {'.js': ['.ts', '.tsx'], '.mjs': ['.mts'], '.cjs': ['.cts']}[extension] ?? [];
32
+ if (types) replacements.push(...({'.js': ['.d.ts'], '.mjs': ['.d.mts'], '.cjs': ['.d.cts']}[extension] ?? []));
33
+ for (const replacement of replacements) {
34
+ const found = file(name.slice(0, -extension.length) + replacement);
35
+ if (found) return found;
36
+ }
37
+ }
38
+ // Exports/imports targets are exact files; require's legacy directory and
39
+ // extension searches do not apply to a package export target.
40
+ if (packaged) return;
41
+ if (sourceModule || types || kind === 'require') {
42
+ const suffixes = sourceModule || types ? [...sourceExtensions, ...(types ? ['.d.ts', '.d.mts', '.d.cts'] : [])] : ['.js', '.json', '.node'];
43
+ for (const suffix of suffixes) {
44
+ const found = file(name + suffix);
45
+ if (found) return found;
46
+ }
47
+ // Relative require-directory resolution consults main, never types/typings
48
+ // or exports. Node only consults exports when resolving a package name.
49
+ const manifest = name + '/package.json';
50
+ if (kind === 'require' && tree.has(manifest) && tree.read) {
51
+ const main = JSON.parse(tree.read(manifest)).main;
52
+ if (typeof main === 'string') {
53
+ const target = path.posix.join(name, main);
54
+ if (!types && declaration(target) && tree.has(target)) return;
55
+ for (const candidate of [target, ...['.js', '.json', '.node'].map(suffix => target + suffix), ...['.js', '.json', '.node'].map(suffix => target + '/index' + suffix)]) {
56
+ const found = file(candidate);
57
+ if (found) { manifests.add(manifest); return found; }
58
+ }
59
+ }
60
+ }
61
+ for (const suffix of suffixes) {
62
+ const found = file(name + '/index' + suffix);
63
+ if (found) return found;
64
+ }
65
+ }
66
+ }
@@ -0,0 +1,57 @@
1
+ // Lex module syntax without treating comments, strings or template text as code.
2
+ // Template interpolations are code, including nested templates and import().
3
+ export function tokens(source) {
4
+ const result = [];
5
+ let i = 0;
6
+ function quoted(quote) {
7
+ const start = i++;
8
+ while (i < source.length) {
9
+ if (source[i] === '\\') { i += 2; continue; }
10
+ if (source[i++] === quote) break;
11
+ }
12
+ return source.slice(start, i);
13
+ }
14
+ function template() {
15
+ const start = i++;
16
+ let interpolated = false;
17
+ while (i < source.length) {
18
+ if (source[i] === '\\') { i += 2; continue; }
19
+ if (source[i] === '`') { i++; break; }
20
+ if (source[i] === '$' && source[i + 1] === '{') {
21
+ interpolated = true; i += 2; result.push(';'); scan(true); result.push(';');
22
+ } else i++;
23
+ }
24
+ if (!interpolated) result.push(source.slice(start, i));
25
+ }
26
+ function scan(interpolation = false) {
27
+ let braces = 0;
28
+ while (i < source.length) {
29
+ const c = source[i];
30
+ if (/\s/.test(c)) { i++; continue; }
31
+ if (source.startsWith('//', i)) {
32
+ while (i < source.length && source[i] !== '\n') i++;
33
+ continue;
34
+ }
35
+ if (source.startsWith('/*', i)) {
36
+ const end = source.indexOf('*/', i + 2); i = end < 0 ? source.length : end + 2; continue;
37
+ }
38
+ if (c === "'" || c === '"') { result.push(quoted(c)); continue; }
39
+ if (c === '`') { template(); continue; }
40
+ if (interpolation && c === '}' && !braces) { i++; return; }
41
+ if (c === '{') braces++;
42
+ if (c === '}') braces--;
43
+ if (/[\w$]/.test(c)) {
44
+ const start = i++;
45
+ while (i < source.length && /[\w$]/.test(source[i])) i++;
46
+ result.push(source.slice(start, i));
47
+ } else { result.push(c); i++; }
48
+ }
49
+ }
50
+ scan(); return result;
51
+ }
52
+
53
+ export function unquote(value) {
54
+ if (!/^['"`]/.test(value ?? '') || value[0] === '`' && value.includes('${')) return null;
55
+ return value.slice(1, -1).replace(/\\(?:x([\da-fA-F]{2})|u(?:\{([\da-fA-F]+)\}|([\da-fA-F]{4}))|([\s\S]))/g,
56
+ (_, x, codepoint, u, character) => x || codepoint || u ? String.fromCodePoint(parseInt(x ?? codepoint ?? u, 16)) : character === '\n' ? '' : ({n:'\n',r:'\r',t:'\t',b:'\b',f:'\f',v:'\v',0:'\0'}[character] ?? character));
57
+ }
@@ -0,0 +1,92 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import * as modules from 'node:module';
5
+ import {fileURLToPath, pathToFileURL} from 'node:url';
6
+
7
+ let runtimeConditions, nodeResolve, temporary;
8
+ const scopes = new Map();
9
+ if (typeof modules.registerHooks === 'function') {
10
+ const captured = {};
11
+ let phase = 'import';
12
+ const hook = modules.registerHooks({resolve(specifier, context, next) {
13
+ if (specifier === 'node:fs' && context.parentURL === import.meta.url) {
14
+ captured[phase] = new Set(context.conditions);
15
+ if (phase === 'import') nodeResolve = next;
16
+ }
17
+ return next(specifier, context);
18
+ }});
19
+ try {
20
+ await import('node:fs');
21
+ phase = 'require';
22
+ modules.createRequire(import.meta.url)('node:fs');
23
+ } finally { hook.deregister(); }
24
+ if (!captured.import || !captured.require || !nodeResolve) throw Error('Cannot determine Node package resolution.');
25
+ runtimeConditions = captured;
26
+ }
27
+ function conditions(kind, types) {
28
+ if (!runtimeConditions) throw Error('Use the pinned Node runtime before refreshing local package imports.');
29
+ const selected = new Set(runtimeConditions[kind]);
30
+ if (!types && selected.has('types')) throw Error('The types condition cannot satisfy runtime imports; remove it from Node options.');
31
+ if (types) selected.add('types');
32
+ return [...selected];
33
+ }
34
+ function scope(text) {
35
+ if (scopes.has(text)) return scopes.get(text);
36
+ if (!temporary) {
37
+ temporary = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'rer-package-scopes-')));
38
+ process.once('exit', () => fs.rmSync(temporary, {recursive: true, force: true}));
39
+ }
40
+ const root = path.join(temporary, String(scopes.size));
41
+ fs.mkdirSync(root); fs.writeFileSync(path.join(root, 'package.json'), text);
42
+ const item = {root, parent: pathToFileURL(path.join(root, 'entry.mjs')).href, results: new Map()};
43
+ scopes.set(text, item);
44
+ return item;
45
+ }
46
+ function selectedTarget(text, specifier, kind, types) {
47
+ const active = conditions(kind, types), item = scope(text), key = JSON.stringify([specifier, kind, types]);
48
+ if (item.results.has(key)) return item.results.get(key);
49
+ // Only metadata is materialized. Node selects and validates the package target;
50
+ // actual file satisfaction is checked against the immutable/virtual tree below.
51
+ let result, url;
52
+ try {
53
+ url = nodeResolve(specifier, {parentURL: item.parent, conditions: active, importAttributes: {}}).url;
54
+ } catch (error) {
55
+ // Node's import.meta.resolve also exposes a selected missing file's URL.
56
+ // Presence is evaluated against the virtual tree rather than this metadata scope.
57
+ if (['ERR_MODULE_NOT_FOUND', 'ERR_UNSUPPORTED_DIR_IMPORT'].includes(error.code) && error.url) url = error.url;
58
+ else if (error.code === 'ERR_MODULE_NOT_FOUND') result = {external: true, value: 'external package'};
59
+ else if (['ERR_PACKAGE_PATH_NOT_EXPORTED', 'ERR_PACKAGE_IMPORT_NOT_DEFINED', 'ERR_INVALID_PACKAGE_TARGET', 'ERR_INVALID_PACKAGE_CONFIG', 'ERR_INVALID_MODULE_SPECIFIER'].includes(error.code)) result = {};
60
+ else throw error;
61
+ }
62
+ if (url?.startsWith('file:')) {
63
+ const relative = path.relative(item.root, fileURLToPath(url));
64
+ if (relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) throw Error('Package target escapes its package scope.');
65
+ result = {relative: relative.split(path.sep).join('/')};
66
+ } else if (url) result = {external: true, value: url};
67
+ item.results.set(key, result);
68
+ return result;
69
+ }
70
+
71
+ // Node owns condition order, null/array targets, patterns and target validation.
72
+ // This only supplies the nearest package scope from the virtual source tree.
73
+ export function packageTarget(tree, source, specifier, {kind, types, package: state = {}}) {
74
+ if (!tree.read || /^[a-z][a-z\d+.-]*:/i.test(specifier) || specifier.startsWith('/')) return;
75
+ let directory = path.posix.dirname(source);
76
+ while (true) {
77
+ const manifest = path.posix.join(directory, 'package.json');
78
+ if (tree.has(manifest)) {
79
+ const text = tree.read(manifest), data = JSON.parse(text);
80
+ const privateImport = specifier.startsWith('#') && Object.hasOwn(data, 'imports');
81
+ const self = typeof data.name === 'string' && (specifier === data.name || specifier.startsWith(data.name + '/')) && data.exports != null;
82
+ if (!privateImport && !self) return;
83
+ state.managed = true; state.manifest = manifest; state.type = data.type;
84
+ const selected = selectedTarget(text, specifier, kind, types);
85
+ Object.assign(state, selected);
86
+ if (selected.relative !== undefined) state.target = path.posix.join(directory, selected.relative);
87
+ return state.target;
88
+ }
89
+ if (directory === '.') return;
90
+ directory = path.posix.dirname(directory);
91
+ }
92
+ }