@vizhub/runtime 0.0.1 → 0.0.3

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 (120) hide show
  1. package/dist/assets/setupV3Runtime-BVr5lyKp.js +240 -0
  2. package/dist/computeSrcDoc.d.ts +13 -0
  3. package/dist/computeSrcDoc.d.ts.map +1 -0
  4. package/{src/index.ts → dist/index.d.ts} +1 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/{src/v2Runtime/bundle/rollup.browser.js → dist/index.js} +9286 -12810
  7. package/dist/useRuntime.d.ts +13 -0
  8. package/dist/useRuntime.d.ts.map +1 -0
  9. package/dist/v2Runtime/bundle/bubleJSXOnly.d.ts +5 -0
  10. package/dist/v2Runtime/bundle/bubleJSXOnly.d.ts.map +1 -0
  11. package/dist/v2Runtime/bundle/packageJson.d.ts +10 -0
  12. package/dist/v2Runtime/bundle/packageJson.d.ts.map +1 -0
  13. package/dist/v2Runtime/computeSrcDocV2.d.ts +3 -0
  14. package/dist/v2Runtime/computeSrcDocV2.d.ts.map +1 -0
  15. package/dist/v2Runtime/computeSrcDocV2.test.d.ts +2 -0
  16. package/dist/v2Runtime/computeSrcDocV2.test.d.ts.map +1 -0
  17. package/dist/v2Runtime/getComputedIndexHtml.d.ts +4 -0
  18. package/dist/v2Runtime/getComputedIndexHtml.d.ts.map +1 -0
  19. package/dist/v2Runtime/getComputedIndexHtml.test.d.ts +2 -0
  20. package/dist/v2Runtime/getComputedIndexHtml.test.d.ts.map +1 -0
  21. package/dist/v2Runtime/getText.d.ts +3 -0
  22. package/dist/v2Runtime/getText.d.ts.map +1 -0
  23. package/dist/v2Runtime/transformFiles.d.ts +3 -0
  24. package/dist/v2Runtime/transformFiles.d.ts.map +1 -0
  25. package/dist/v2Runtime/v3FilesToV2Files.d.ts +3 -0
  26. package/dist/v2Runtime/v3FilesToV2Files.d.ts.map +1 -0
  27. package/dist/v2Runtime/v3FilesToV2Files.test.d.ts +2 -0
  28. package/dist/v2Runtime/v3FilesToV2Files.test.d.ts.map +1 -0
  29. package/dist/v3Runtime/build.d.ts +14 -0
  30. package/dist/v3Runtime/build.d.ts.map +1 -0
  31. package/dist/v3Runtime/build.test.d.ts +2 -0
  32. package/dist/v3Runtime/build.test.d.ts.map +1 -0
  33. package/dist/v3Runtime/cleanRollupErrorMessage.d.ts +5 -0
  34. package/dist/v3Runtime/cleanRollupErrorMessage.d.ts.map +1 -0
  35. package/dist/v3Runtime/computeSrcDocV3.d.ts +7 -0
  36. package/dist/v3Runtime/computeSrcDocV3.d.ts.map +1 -0
  37. package/dist/v3Runtime/extractVizImport.d.ts +7 -0
  38. package/dist/v3Runtime/extractVizImport.d.ts.map +1 -0
  39. package/dist/v3Runtime/extractVizImport.test.d.ts +2 -0
  40. package/dist/v3Runtime/extractVizImport.test.d.ts.map +1 -0
  41. package/dist/v3Runtime/generateRollupErrorMessage.d.ts +5 -0
  42. package/dist/v3Runtime/generateRollupErrorMessage.d.ts.map +1 -0
  43. package/dist/v3Runtime/importFromViz.d.ts +1 -0
  44. package/dist/v3Runtime/importFromViz.d.ts.map +1 -0
  45. package/{src/v3Runtime/index.ts → dist/v3Runtime/index.d.ts} +1 -0
  46. package/dist/v3Runtime/index.d.ts.map +1 -0
  47. package/dist/v3Runtime/parseId.d.ts +7 -0
  48. package/dist/v3Runtime/parseId.d.ts.map +1 -0
  49. package/dist/v3Runtime/setupV3Runtime.d.ts +15 -0
  50. package/dist/v3Runtime/setupV3Runtime.d.ts.map +1 -0
  51. package/dist/v3Runtime/transformDSV/index.d.ts +3 -0
  52. package/dist/v3Runtime/transformDSV/index.d.ts.map +1 -0
  53. package/dist/v3Runtime/transformSvelte.d.ts +6 -0
  54. package/dist/v3Runtime/transformSvelte.d.ts.map +1 -0
  55. package/dist/v3Runtime/types.d.ts +65 -0
  56. package/dist/v3Runtime/types.d.ts.map +1 -0
  57. package/dist/v3Runtime/urlLoad.d.ts +1 -0
  58. package/dist/v3Runtime/urlLoad.d.ts.map +1 -0
  59. package/dist/v3Runtime/virtual.d.ts +1 -0
  60. package/dist/v3Runtime/virtual.d.ts.map +1 -0
  61. package/dist/v3Runtime/vizCache.d.ts +11 -0
  62. package/dist/v3Runtime/vizCache.d.ts.map +1 -0
  63. package/dist/v3Runtime/vizCache.test.d.ts +2 -0
  64. package/dist/v3Runtime/vizCache.test.d.ts.map +1 -0
  65. package/dist/v3Runtime/vizLoad.d.ts +8 -0
  66. package/dist/v3Runtime/vizLoad.d.ts.map +1 -0
  67. package/dist/v3Runtime/vizLoadSvelte.d.ts +1 -0
  68. package/dist/v3Runtime/vizLoadSvelte.d.ts.map +1 -0
  69. package/dist/v3Runtime/vizResolve.d.ts +10 -0
  70. package/dist/v3Runtime/vizResolve.d.ts.map +1 -0
  71. package/dist/v3Runtime/worker.d.ts +2 -0
  72. package/dist/v3Runtime/worker.d.ts.map +1 -0
  73. package/package.json +13 -6
  74. package/src/computeSrcDoc.ts +0 -68
  75. package/src/useRuntime.ts +0 -394
  76. package/src/v2Runtime/bundle/bubleJSXOnly.ts +0 -34
  77. package/src/v2Runtime/bundle/getLibraries.js +0 -31
  78. package/src/v2Runtime/bundle/hypothetical.js +0 -232
  79. package/src/v2Runtime/bundle/index.js +0 -88
  80. package/src/v2Runtime/bundle/packageJson.ts +0 -49
  81. package/src/v2Runtime/bundle.test.js +0 -151
  82. package/src/v2Runtime/computeSrcDocV2.test.ts +0 -163
  83. package/src/v2Runtime/computeSrcDocV2.ts +0 -34
  84. package/src/v2Runtime/getComputedIndexHtml.test.ts +0 -33
  85. package/src/v2Runtime/getComputedIndexHtml.ts +0 -106
  86. package/src/v2Runtime/getText.ts +0 -19
  87. package/src/v2Runtime/magicSandbox.js +0 -291
  88. package/src/v2Runtime/packageJson.js +0 -42
  89. package/src/v2Runtime/transformFiles.test.js +0 -18
  90. package/src/v2Runtime/transformFiles.ts +0 -15
  91. package/src/v2Runtime/v3FilesToV2Files.test.ts +0 -20
  92. package/src/v2Runtime/v3FilesToV2Files.ts +0 -14
  93. package/src/v3Runtime/build.test.ts +0 -474
  94. package/src/v3Runtime/build.ts +0 -270
  95. package/src/v3Runtime/cleanRollupErrorMessage.ts +0 -15
  96. package/src/v3Runtime/computeSrcDocV3.ts +0 -151
  97. package/src/v3Runtime/extractVizImport.test.ts +0 -41
  98. package/src/v3Runtime/extractVizImport.ts +0 -34
  99. package/src/v3Runtime/generateRollupErrorMessage.ts +0 -84
  100. package/src/v3Runtime/importFromViz.ts +0 -36
  101. package/src/v3Runtime/parseId.ts +0 -14
  102. package/src/v3Runtime/setupV3Runtime.ts +0 -478
  103. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/bundle-modified-src.js +0 -121
  104. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/bundle-modified.js +0 -121
  105. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/bundle.js +0 -239
  106. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/index.js +0 -1
  107. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/package-lock.json +0 -475
  108. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/package.json +0 -19
  109. package/src/v3Runtime/transformDSV/d3-dsv-custom-build/rollup.config.js +0 -9
  110. package/src/v3Runtime/transformDSV/index.ts +0 -71
  111. package/src/v3Runtime/transformSvelte.ts +0 -111
  112. package/src/v3Runtime/types.ts +0 -158
  113. package/src/v3Runtime/urlLoad.ts +0 -33
  114. package/src/v3Runtime/virtual.ts +0 -27
  115. package/src/v3Runtime/vizCache.test.ts +0 -126
  116. package/src/v3Runtime/vizCache.ts +0 -60
  117. package/src/v3Runtime/vizLoad.ts +0 -68
  118. package/src/v3Runtime/vizLoadSvelte.ts +0 -46
  119. package/src/v3Runtime/vizResolve.ts +0 -100
  120. package/src/v3Runtime/worker.ts +0 -231
@@ -1,478 +0,0 @@
1
- // @ts-ignore
2
- import Worker from './worker.ts?worker';
3
-
4
- import {
5
- ResolvedVizFileId,
6
- V3BuildResult,
7
- V3WindowMessage,
8
- V3WorkerMessage,
9
- } from './types';
10
- import { Content, VizId, getFileText } from 'entities';
11
- import { parseId } from './parseId';
12
- import { cleanRollupErrorMessage } from './cleanRollupErrorMessage';
13
-
14
- // Flag for debugging.
15
- const debug = false;
16
-
17
- // Nothing happening.
18
- const IDLE = 'IDLE';
19
-
20
- // An update has been enqueued
21
- // via requestAnimationFrame.
22
- const ENQUEUED = 'ENQUEUED';
23
-
24
- // An update (build and run) is pending,
25
- // and the files have not changed.
26
- const PENDING_CLEAN = 'PENDING_CLEAN';
27
-
28
- // An update (build and run) is pending,
29
- // and the files have changed
30
- // while this run is taking place.
31
- const PENDING_DIRTY = 'PENDING_DIRTY';
32
-
33
- export type V3Runtime = {
34
- // Performs a hot reload of a new build.
35
- handleCodeChange: (content: Content) => void;
36
-
37
- // Performs a hot reload of a new build.
38
- invalidateVizCache: (changedVizIds: Array<VizId>) => void;
39
-
40
- // Performs a hard reset of the srcdoc and
41
- // entire runtime environment.
42
- resetSrcdoc: (changedVizIds: Array<VizId>) => void;
43
- };
44
-
45
- export const setupV3Runtime = ({
46
- vizId,
47
- iframe,
48
- setSrcdocErrorMessage,
49
- getLatestContent,
50
- resolveSlugKey,
51
- writeFile,
52
- }: {
53
- vizId: VizId;
54
- iframe: HTMLIFrameElement;
55
- setSrcdocErrorMessage: (error: string | null) => void;
56
- getLatestContent: (vizId: VizId) => Promise<Content>;
57
- resolveSlugKey: (slugKey: string) => Promise<VizId>;
58
- writeFile: (fileName: string, content: string) => void;
59
- }): V3Runtime => {
60
- // The "build worker", a Web Worker that does the building.
61
- const worker = new Worker();
62
-
63
- // Valid State Transitions:
64
- //
65
- // * IDLE --> ENQUEUED
66
- // When the system is idle and files are changed.
67
- //
68
- // * ENQUEUED --> PENDING_CLEAN
69
- // When the pending changes run.
70
- //
71
- // * PENDING_CLEAN --> IDLE
72
- // When the pending update finishes running
73
- // and files were not changed in the mean time.
74
- //
75
- // * PENDING_CLEAN --> PENDING_DIRTY
76
- // When files are changed while an update is pending.
77
- //
78
- // * PENDING_DIRTY --> ENQUEUED
79
- // When the pending update finishes running
80
- // and files were changed in the mean time.
81
- //
82
- // When a build error happens, the state is set to IDLE.
83
- // This is to prevent a build error from causing
84
- // the whole system to stop working.
85
- //
86
- // Valid State Transitions (with build errors):
87
- // TODO complete this section
88
-
89
- let state:
90
- | typeof IDLE
91
- | typeof ENQUEUED
92
- | typeof PENDING_CLEAN
93
- | typeof PENDING_DIRTY = IDLE;
94
-
95
- if (debug) {
96
- setInterval(() => {
97
- console.log('state', state);
98
- }, 1000);
99
- }
100
-
101
- // Pending promise resolvers.
102
- let pendingBuildPromise:
103
- | ((buildResult?: V3BuildResult) => void)
104
- | null = null;
105
- let pendingRunPromise: (() => void) | null = null;
106
-
107
- // Logic around profiling build times.
108
- const profileBuildTimes = debug;
109
- let buildTimes: Array<number> = [];
110
- const avg = (arr: Array<number>) =>
111
- arr.reduce((a, b) => a + b, 0) / arr.length;
112
- const n = 100;
113
-
114
- // This runs when the build worker sends a message.
115
- worker.addEventListener('message', async ({ data }) => {
116
- const message: V3WorkerMessage =
117
- data as V3WorkerMessage;
118
-
119
- // Handle 'buildResponse' messages.
120
- // These are sent by the build worker in response
121
- // to a 'buildRequest' message.
122
- if (message.type === 'buildResponse') {
123
- const buildResult: V3BuildResult | undefined =
124
- message.buildResult;
125
- const error: Error | undefined = message.error;
126
-
127
- if (profileBuildTimes && buildResult) {
128
- buildTimes.push(buildResult.time);
129
- // Every n times, log the rolling average.
130
- if (buildTimes.length % n === 0) {
131
- console.log(
132
- 'Average build time: ' +
133
- avg(buildTimes) +
134
- ' ms',
135
- );
136
- buildTimes = [];
137
- }
138
- }
139
-
140
- // Regardless of whether the build succeeded or failed,
141
- // resolve the pending build promise,
142
- // so that the system remains responsive.
143
- if (pendingBuildPromise) {
144
- pendingBuildPromise(buildResult);
145
- pendingBuildPromise = null;
146
- }
147
-
148
- if (error) {
149
- setSrcdocErrorMessage(
150
- cleanRollupErrorMessage({
151
- rawMessage: error.message,
152
- vizId,
153
- }),
154
- );
155
- }
156
- }
157
-
158
- // Handle 'contentRequest' messages.
159
- // These are sent by the worker when it needs
160
- // to get the content of a file, in order to
161
- // populate its VizCache.
162
- if (message.type === 'contentRequest') {
163
- const { vizId } = message;
164
-
165
- const content = await getLatestContent(vizId);
166
-
167
- const contentResponseMessage: V3WorkerMessage = {
168
- type: 'contentResponse',
169
- vizId: message.vizId,
170
- content,
171
- };
172
-
173
- if (debug) {
174
- console.log(
175
- '[v3 runtime] received contentRequest, sending contentResponse',
176
- contentResponseMessage,
177
- );
178
- }
179
-
180
- // Send the content back to the worker.
181
- worker.postMessage(contentResponseMessage);
182
- }
183
-
184
- // Handle 'resolveSlugRequest' messages.
185
- // These are sent by the worker when it needs
186
- // to resolve a slug import to a viz ID.
187
- if (message.type === 'resolveSlugRequest') {
188
- const { slugKey } = message;
189
-
190
- const resolveSlugResponseMessage: V3WorkerMessage = {
191
- type: 'resolveSlugResponse',
192
- slugKey,
193
- requestId: message.requestId,
194
- vizId: await resolveSlugKey(slugKey),
195
- };
196
-
197
- if (debug) {
198
- console.log(
199
- '[v3 runtime] received resolveSlugRequest, sending resolveSlugResponse',
200
- resolveSlugResponseMessage,
201
- );
202
- }
203
- // Send the viz ID back to the worker.
204
- worker.postMessage(resolveSlugResponseMessage);
205
- }
206
-
207
- // Handle 'invalidateVizCacheResponse' messages.
208
- // These are sent by the worker in response to
209
- // an 'invalidateVizCacheRequest' message.
210
- if (message.type === 'invalidateVizCacheResponse') {
211
- if (debug) {
212
- console.log(
213
- '[v3 runtime] received invalidateVizCacheResponse',
214
- message,
215
- );
216
- }
217
- // Leverage existing infra for executing the hot reloading.
218
- handleCodeChange();
219
- }
220
-
221
- if (message.type === 'resetSrcdocResponse') {
222
- const srcdoc: string | undefined = message.srcdoc;
223
- const error: Error | undefined = message.error;
224
-
225
- if (error) {
226
- setSrcdocErrorMessage(
227
- cleanRollupErrorMessage({
228
- rawMessage: error.message,
229
- vizId,
230
- }),
231
- );
232
- } else {
233
- setSrcdocErrorMessage(null);
234
-
235
- // Really reset the srcdoc!
236
- // console.log('Really reset the srcdoc!');
237
- if (srcdoc) {
238
- iframe.srcdoc = srcdoc;
239
- }
240
- }
241
- }
242
- });
243
-
244
- // This runs when the IFrame sends a message.
245
- window.addEventListener('message', ({ data }) => {
246
- // Handle 'runDone' and 'runError' messages.
247
- // These happen in response to sending a 'runJS' message.
248
- if (
249
- data.type === 'runDone' ||
250
- data.type === 'runError'
251
- ) {
252
- // console.log('got ' + data.type);
253
- if (pendingRunPromise) {
254
- // TODO pass errors out for display
255
- // pendingRunPromise(data as V3WindowMessage);
256
- pendingRunPromise();
257
- pendingRunPromise = null;
258
- }
259
- }
260
- if (data.type === 'runError') {
261
- setSrcdocErrorMessage(data.error.message);
262
- }
263
- if (data.type === 'writeFile') {
264
- if (data.fileName && data.content) {
265
- writeFile(data.fileName, data.content);
266
- }
267
- }
268
- });
269
-
270
- const handleCodeChange = () => {
271
- if (state === IDLE) {
272
- state = ENQUEUED;
273
- update();
274
- } else if (state === PENDING_CLEAN) {
275
- state = PENDING_DIRTY;
276
- }
277
- };
278
-
279
- // This runs when one or more imported vizzes are changed.
280
- const invalidateVizCache = (
281
- changedVizIds: Array<VizId>,
282
- ): void => {
283
- // Send a message to the worker to invalidate the cache.
284
- const message: V3WorkerMessage = {
285
- type: 'invalidateVizCacheRequest',
286
- changedVizIds,
287
- };
288
- worker.postMessage(message);
289
- };
290
-
291
- const profileHotReloadFPS = true;
292
- let updateCount = 0;
293
- if (profileHotReloadFPS) {
294
- setInterval(() => {
295
- if (debug && updateCount > 0) {
296
- console.log(
297
- updateCount +
298
- ' hot reload' +
299
- (updateCount !== 1 ? 's' : '') +
300
- ' in the last second',
301
- );
302
- }
303
- updateCount = 0;
304
- }, 1000);
305
- }
306
-
307
- const build = () => {
308
- return new Promise<V3BuildResult | undefined>(
309
- (resolve) => {
310
- pendingBuildPromise = resolve;
311
- const message: V3WorkerMessage = {
312
- type: 'buildRequest',
313
- vizId,
314
- enableSourcemap: true,
315
- };
316
- worker.postMessage(message);
317
- },
318
- );
319
- };
320
-
321
- // Builds and runs the latest files.
322
- const update = async () => {
323
- state = PENDING_CLEAN;
324
- if (debug) {
325
- console.log('update: before run');
326
- }
327
-
328
- // Build the code. This may fail and return `undefined`.
329
- const buildResult: V3BuildResult | undefined =
330
- await build();
331
-
332
- // If the build was successful, run the code.
333
- if (buildResult !== undefined) {
334
- await run(buildResult);
335
- }
336
-
337
- if (debug) {
338
- console.log('update: after run');
339
- }
340
- updateCount++;
341
- // TypeScript can't comprehend that `state`
342
- // may change during the await calls above.
343
- // @ts-ignore
344
- if (state === PENDING_DIRTY) {
345
- requestAnimationFrame(update);
346
- state = ENQUEUED;
347
- } else {
348
- state = IDLE;
349
- }
350
- };
351
-
352
- let previousCSSFiles: Array<ResolvedVizFileId> = [];
353
- const run = (buildResult: V3BuildResult) => {
354
- return new Promise<void>((resolve) => {
355
- const { src, warnings, cssFiles } = buildResult;
356
-
357
- // Sanity check.
358
- // At this point, since there were no errors,
359
- // we expect there to be a `src` property.
360
- // This should never happen, but log & error just in case!
361
- if (src === undefined) {
362
- if (debug) {
363
- console.log(
364
- '[v3 runtime] src is undefined, but no errors!',
365
- );
366
- }
367
- throw new Error(
368
- '[v3 runtime] src is undefined, but no errors!',
369
- );
370
- }
371
-
372
- // Set pendingRunPromise because at this point,
373
- // we expect an asynchronous response when the run is done.
374
- // The iframe should send either a `runDone` or `runError` message.
375
- pendingRunPromise = resolve;
376
-
377
- // Handle build warnings
378
- if (warnings.length > 0) {
379
- // TODO: Distinguish between warnings and errors in UI
380
- setSrcdocErrorMessage(
381
- warnings
382
- .map((warning) => warning.message)
383
- .join('\n\n'),
384
- );
385
- } else {
386
- setSrcdocErrorMessage(null); // Clear error message if no warnings
387
- }
388
-
389
- if (iframe.contentWindow) {
390
- // For each cssFiles
391
- for (const cssFile of cssFiles) {
392
- const { vizId, fileName } = parseId(cssFile);
393
-
394
- getLatestContent(vizId).then((content) => {
395
- const src = getFileText(content, fileName);
396
-
397
- if (src === null) {
398
- // The file doesn't exist.
399
- // TODO surface this error to the user
400
- // in a nicer way than this.
401
- console.warn(
402
- `Imported CSS file ${fileName} doesn't exist.`,
403
- );
404
- return;
405
- }
406
-
407
- // TODO only inject CSS if it has changed.
408
- const runCSSMessage: V3WindowMessage = {
409
- type: 'runCSS',
410
- id: cssFile,
411
- src,
412
- };
413
-
414
- if (debug) {
415
- console.log('runCSSMessage', runCSSMessage);
416
- }
417
-
418
- iframe.contentWindow?.postMessage(
419
- runCSSMessage,
420
- window.location.origin,
421
- );
422
- });
423
- }
424
-
425
- // Detect which CSS files have been removed
426
- // and remove them from the iframe.
427
- const removedCSSFiles = previousCSSFiles.filter(
428
- (id) => !cssFiles.includes(id),
429
- );
430
- previousCSSFiles = cssFiles;
431
- if (debug) {
432
- console.log('removedCSSFiles', removedCSSFiles);
433
- }
434
- for (const id of removedCSSFiles) {
435
- const removeCSSMessage: V3WindowMessage = {
436
- type: 'runCSS',
437
- id,
438
- src: '',
439
- };
440
- iframe.contentWindow?.postMessage(
441
- removeCSSMessage,
442
- window.location.origin,
443
- );
444
- }
445
-
446
- // Clear the console before each run.
447
- console.clear();
448
-
449
- const runJSMessage: V3WindowMessage = {
450
- type: 'runJS',
451
- src,
452
- };
453
- iframe.contentWindow.postMessage(
454
- runJSMessage,
455
- window.location.origin,
456
- );
457
- }
458
- });
459
- };
460
-
461
- const resetSrcdoc = (changedVizIds: Array<VizId>) => {
462
- state = IDLE;
463
- pendingBuildPromise = null;
464
- pendingRunPromise = null;
465
- const message: V3WorkerMessage = {
466
- type: 'resetSrcdocRequest',
467
- vizId,
468
- changedVizIds,
469
- };
470
- worker.postMessage(message);
471
- };
472
-
473
- return {
474
- handleCodeChange,
475
- invalidateVizCache,
476
- resetSrcdoc,
477
- };
478
- };
@@ -1,121 +0,0 @@
1
- export const dsvParseSrc = `var EOL = {},
2
- EOF = {},
3
- QUOTE = 34,
4
- NEWLINE = 10,
5
- RETURN = 13;
6
-
7
- function objectConverter(columns) {
8
- return new Function(
9
- 'd',
10
- 'return {' +
11
- columns
12
- .map(function (name, i) {
13
- return (
14
- JSON.stringify(name) + ': d[' + i + '] || ""'
15
- );
16
- })
17
- .join(',') +
18
- '}',
19
- );
20
- }
21
-
22
- function customConverter(columns, f) {
23
- var object = objectConverter(columns);
24
- return function (row, i) {
25
- return f(object(row), i, columns);
26
- };
27
- }
28
-
29
- function dsv(delimiter) {
30
- var DELIMITER = delimiter.charCodeAt(0);
31
-
32
- function parse(text, f) {
33
- var convert,
34
- columns,
35
- rows = parseRows(text, function (row, i) {
36
- if (convert) return convert(row, i - 1);
37
- (columns = row),
38
- (convert = f
39
- ? customConverter(row, f)
40
- : objectConverter(row));
41
- });
42
- rows.columns = columns || [];
43
- return rows;
44
- }
45
-
46
- function parseRows(text, f) {
47
- var rows = [], // output rows
48
- N = text.length,
49
- I = 0, // current character index
50
- n = 0, // current line number
51
- t, // current token
52
- eof = N <= 0, // current token followed by EOF?
53
- eol = false; // current token followed by EOL?
54
-
55
- // Strip the trailing newline.
56
- if (text.charCodeAt(N - 1) === NEWLINE) --N;
57
- if (text.charCodeAt(N - 1) === RETURN) --N;
58
-
59
- function token() {
60
- if (eof) return EOF;
61
- if (eol) return (eol = false), EOL;
62
-
63
- // Unescape quotes.
64
- var i,
65
- j = I,
66
- c;
67
- if (text.charCodeAt(j) === QUOTE) {
68
- while (
69
- (I++ < N && text.charCodeAt(I) !== QUOTE) ||
70
- text.charCodeAt(++I) === QUOTE
71
- );
72
- if ((i = I) >= N) eof = true;
73
- else if ((c = text.charCodeAt(I++)) === NEWLINE)
74
- eol = true;
75
- else if (c === RETURN) {
76
- eol = true;
77
- if (text.charCodeAt(I) === NEWLINE) ++I;
78
- }
79
- return text.slice(j + 1, i - 1).replace(/""/g, '"');
80
- }
81
-
82
- // Find next delimiter or newline.
83
- while (I < N) {
84
- if ((c = text.charCodeAt((i = I++))) === NEWLINE)
85
- eol = true;
86
- else if (c === RETURN) {
87
- eol = true;
88
- if (text.charCodeAt(I) === NEWLINE) ++I;
89
- } else if (c !== DELIMITER) continue;
90
- return text.slice(j, i);
91
- }
92
-
93
- // Return last token before EOF.
94
- return (eof = true), text.slice(j, N);
95
- }
96
-
97
- while ((t = token()) !== EOF) {
98
- var row = [];
99
- while (t !== EOL && t !== EOF)
100
- row.push(t), (t = token());
101
- if (f && (row = f(row, n++)) == null) continue;
102
- rows.push(row);
103
- }
104
-
105
- return rows;
106
- }
107
-
108
- return {
109
- parse: parse,
110
- };
111
- }
112
-
113
- var csv = dsv(',');
114
-
115
- var csvParse = csv.parse;
116
-
117
- var tsv = dsv('\t');
118
-
119
- var tsvParse = tsv.parse;
120
-
121
- export { csvParse, tsvParse };`;
@@ -1,121 +0,0 @@
1
- var EOL = {},
2
- EOF = {},
3
- QUOTE = 34,
4
- NEWLINE = 10,
5
- RETURN = 13;
6
-
7
- function objectConverter(columns) {
8
- return new Function(
9
- 'd',
10
- 'return {' +
11
- columns
12
- .map(function (name, i) {
13
- return (
14
- JSON.stringify(name) + ': d[' + i + '] || ""'
15
- );
16
- })
17
- .join(',') +
18
- '}',
19
- );
20
- }
21
-
22
- function customConverter(columns, f) {
23
- var object = objectConverter(columns);
24
- return function (row, i) {
25
- return f(object(row), i, columns);
26
- };
27
- }
28
-
29
- function dsv(delimiter) {
30
- var DELIMITER = delimiter.charCodeAt(0);
31
-
32
- function parse(text, f) {
33
- var convert,
34
- columns,
35
- rows = parseRows(text, function (row, i) {
36
- if (convert) return convert(row, i - 1);
37
- (columns = row),
38
- (convert = f
39
- ? customConverter(row, f)
40
- : objectConverter(row));
41
- });
42
- rows.columns = columns || [];
43
- return rows;
44
- }
45
-
46
- function parseRows(text, f) {
47
- var rows = [], // output rows
48
- N = text.length,
49
- I = 0, // current character index
50
- n = 0, // current line number
51
- t, // current token
52
- eof = N <= 0, // current token followed by EOF?
53
- eol = false; // current token followed by EOL?
54
-
55
- // Strip the trailing newline.
56
- if (text.charCodeAt(N - 1) === NEWLINE) --N;
57
- if (text.charCodeAt(N - 1) === RETURN) --N;
58
-
59
- function token() {
60
- if (eof) return EOF;
61
- if (eol) return (eol = false), EOL;
62
-
63
- // Unescape quotes.
64
- var i,
65
- j = I,
66
- c;
67
- if (text.charCodeAt(j) === QUOTE) {
68
- while (
69
- (I++ < N && text.charCodeAt(I) !== QUOTE) ||
70
- text.charCodeAt(++I) === QUOTE
71
- );
72
- if ((i = I) >= N) eof = true;
73
- else if ((c = text.charCodeAt(I++)) === NEWLINE)
74
- eol = true;
75
- else if (c === RETURN) {
76
- eol = true;
77
- if (text.charCodeAt(I) === NEWLINE) ++I;
78
- }
79
- return text.slice(j + 1, i - 1).replace(/""/g, '"');
80
- }
81
-
82
- // Find next delimiter or newline.
83
- while (I < N) {
84
- if ((c = text.charCodeAt((i = I++))) === NEWLINE)
85
- eol = true;
86
- else if (c === RETURN) {
87
- eol = true;
88
- if (text.charCodeAt(I) === NEWLINE) ++I;
89
- } else if (c !== DELIMITER) continue;
90
- return text.slice(j, i);
91
- }
92
-
93
- // Return last token before EOF.
94
- return (eof = true), text.slice(j, N);
95
- }
96
-
97
- while ((t = token()) !== EOF) {
98
- var row = [];
99
- while (t !== EOL && t !== EOF)
100
- row.push(t), (t = token());
101
- if (f && (row = f(row, n++)) == null) continue;
102
- rows.push(row);
103
- }
104
-
105
- return rows;
106
- }
107
-
108
- return {
109
- parse: parse,
110
- };
111
- }
112
-
113
- var csv = dsv(',');
114
-
115
- var csvParse = csv.parse;
116
-
117
- var tsv = dsv('\t');
118
-
119
- var tsvParse = tsv.parse;
120
-
121
- export { csvParse, tsvParse };